Form对与一个网站来说就是一个灵魂,今天我们就来说说Django的Form概述.
本文内容来自官网,互联网及自己实验所得.
表单(forms.py)的定义:
#coding:utf-8
from django import forms
from django.forms.extras.widgets import SelectDateWidget
SEX_CHOICES=(
(‘male‘,‘男‘),
(‘female‘,‘女‘)
)
BIRTH_YEAR_CHOICES = (‘1980‘, ‘1981‘, ‘1982‘,‘1983‘,‘1984‘)
#注册表单
class Register(forms.Form):
nickname = forms.CharField(max_length=20,label="昵称",help_text="请输入您的别名!",widget=forms.TextInput(attrs={‘class‘:‘special‘,‘id‘:‘nick‘}),error_messages={‘required‘:u‘别名不能为空‘})
username = forms.CharField(label="用户名",error_messages={‘required‘:u‘用户名不能为空‘})
password = forms.CharField(label="密码",widget=forms.PasswordInput)
sex = forms.ChoiceField(widget=forms.RadioSelect,choices=SEX_CHOICES,label="性别")
email = forms.EmailField(label="邮箱",error_messages={‘required‘:u‘邮箱不能为空‘,‘invalid‘:u‘请输入正确的邮箱‘})
phone = forms.CharField(required=False,label="手机号")
birthday = forms.DateField(widget=SelectDateWidget(years=BIRTH_YEAR_CHOICES))
以上是表单经常使用的属性,供其参考.
如,我们需要更改某个表单默认的元素就需要使用widget,并且改变其元素属性就需要使用attrs。
视图(应用)逻辑
views.py
#coding:utf-8
from django.shortcuts import render
from django.http import HttpResponse
from forms import Register
from django.forms.util import ErrorList
# Create your views here.
#重新定义检验错误输出
class DivErrorList(ErrorList):
def __unicode__(self):
return self.as_divs()
def as_divs(self):
if not self: return u‘‘
return u‘%s‘ %‘‘.join([u‘<div class="error">%s</div>‘ % e for e in self])
def register(request):
if request.method == ‘POST‘:
regform = Register(request.POST,auto_id="%s",error_class=DivErrorList)
if regform.is_valid():
nickname = regform.cleaned_data[‘nickname‘] #别名
#print nickname
return HttpResponse(u"{0},欢迎您!".format(nickname))
else:
regform = Register(auto_id="%s",label_suffix=":") #auto_id有3种设置:True/False/str 若是False不需要html元素中的id标识与True相反,auto_id="%s",则是field的名字
return render(request,"register.html",{‘reg‘:regform})
模板
base.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>
{% block title %}
首页
{% endblock%}
</title>
</head>
<body>
{% block content %}
这是内容
{% endblock %}
</body>
</html>
register.html
{% extends "base.html" %}
{% block title %}
用户注册
{% endblock %}
{% block content %}
<form method="POST">{% csrf_token %}
<label><h1>用户注册</h1></label></br>
{% comment%}
{% for err_label,err_value in reg.errors.items %}
{{err_label}}:{{err_value}}
{% endfor %}
{% endcomment %}
<label>别名:</label>{{reg.nickname}} {{reg.nickname.help_text}} {{reg.nickname.errors|safe}}</br>
<label>用户名:</label>{{reg.username}} {{reg.username.errors|safe}}</br>
<label>密码:</label>{{reg.password}}</br>
<label>性别:</label>
{% for sex in reg.sex %}
{{ sex }}
{% endfor %}
</br>
<label>邮箱:</label>{{reg.email}}{{reg.email.errors|safe}}</br>
<label>电话:</label>{{reg.phone}}</br>
<label>生日:</label>{{reg.birthday}}</br>
<input type="submit" value="注册"/>
</form>
{% endblock %}
长啥子样?
表单基础通过以上,基本也就这样了,后面就要去研究下表单数据验证这块!