django的Form一 未完善(接二)

urls.py

from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^fm/', views.fm, name='fm'),
]

views.py

from django.shortcuts import render, redirect, HttpResponse

# ###################form#############################
from django import forms

class FM(forms.Form):
# username,password,email必須與template的form 中name屬性字段一致
    username = forms.CharField(error_messages={'required': '用戶名不能為空'})
    password = forms.CharField(
        max_length=12,
        min_length=6,
        error_messages={'required': '密碼不能為空', 'min_length': '密碼小于6', 'max_length': '密碼大于12'}
    )
    email = forms.EmailField(error_messages={'required': '郵箱不能為空', 'invalid': '郵箱格式錯(cuò)誤'})

def fm(request):
    if request.method == 'POST':
        obj = FM(request.POST)
        if obj.is_valid():
# 這里obj.cleaned_data是一個(gè)字典,如果存數(shù)據(jù),例如:
# models.xxx.objects.create(**obj.cleaned_data) 注冊(cè)就完成了.
            # print obj.cleaned_data
            return redirect('/xxx/') 
        else:
            print obj.errors
    else:
        obj = FM()
    return render(request, 'fm.html', {'obj': obj})

template

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<form action="/fm/" method="post">
    {% csrf_token %}
寫法一
<p><input type="text" placeholder="username" name="username">{{ obj.errors.username.0 }}</p>
<p><input type="text" placeholder="password" name="password">{{ obj.errors.password.0 }}</p>
<p><input type="text" placeholder="email" name="email">{{ obj.errors.email.0 }}</p>
<input type="submit" value="submit">

寫法二
<p>{{ obj.username }} {{ obj.errors.username.0 }}</p>
<p>{{ obj.password }} {{ obj.errors.password.0 }}</p>
<p>{{ obj.email }} {{ obj.errors.email.0 }}</p>
<input type="submit" value="submit">

寫法三
 <p>{{ obj.as_p }}</p>
 <input type="submit" value="submit">
或者
<table>{{ obj.as_table }}</table>
<input type="submit" value="submit">
或者
 <p>{{ obj.as_ul }}</p>
 <input type="submit" value="submit">

</form>
</body>
</html>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容