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': '邮箱格式错误'})

def fm(request):
    if request.method == 'POST':
        obj = FM(request.POST)
        if obj.is_valid():
# 这里obj.cleaned_data是一个字典,如果存数据,例如:
# models.xxx.objects.create(**obj.cleaned_data) 注册就完成了.
            # print obj.cleaned_data
            return redirect('/xxx/') 
        else:
            print obj.errors
    else:
        obj = FM()
    return render(request, 'fm.html', {'obj': obj})

template




    
    


{% csrf_token %} 写法一

{{ obj.errors.username.0 }}

{{ obj.errors.password.0 }}

{{ obj.errors.email.0 }}

写法二

{{ obj.username }} {{ obj.errors.username.0 }}

{{ obj.password }} {{ obj.errors.password.0 }}

{{ obj.email }} {{ obj.errors.email.0 }}

写法三

{{ obj.as_p }}

或者 {{ obj.as_table }}
或者

{{ obj.as_ul }}

你可能感兴趣的:(django的Form一 未完善(接二))