1.在html中生成表单框架,2.验证数据
https://www.cnblogs.com/zongfa/p/7709639.html
class Users(models.Model):
uname = models.CharField(max_length=30,unique=True,verbose_name="用户名")
upet = models.CharField(max_length=30,verbose_name="昵称")
upawd = models.CharField(max_length=30,verbose_name="密码")
email = models.EmailField(verbose_name="电子邮件")
url = models.URLField(verbose_name="网址")
有两种写法:
(1)定义表单模型
from django import forms
class UserForm(forms.Form):
uname = forms.CharField(max_length=100 ,label='用户名')
email = forms.EmailField(label='电子邮件')
upet = forms.CharField(max_length=30,required=False,label='昵称')
upawd = forms.CharField(label='密码',widget=forms.Textarea)
url = forms.URLField(required=False ,label='网址')
(2)继承model
from django.forms import ModelForm
from myblog.users.models import Users
class UsersForm(ModelForm):
class Meta:
model = Users
fields = ('uname','upet', 'upawd','email','url')
def contact(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
username=form.cleaned_data['uname']
usernick=form.cleaned_data['upet']
pawd1=form.cleaned_data['upawd']
email=form.cleaned_data['email']
weburl=form.cleaned_data['url']
Users(uname=username,upet=usernick,upawd=pawd1,
email=email,url=weburl).save()
return HttpResponseRedirect('/index/')
else:
<form action="/contact/" method="post">
<table class="form-table">
<!--{{ form.as_ul }}--> # 这是第一种写法,在<ul> 显示表单
<!-- {{ form.as_p }}--> # 这是第二种写法,在<p> 显示表单
<!--{{ form.as_table }}--> # 这是第三种写法,在<table>显示表单
{% for field in form %} # 这是第四种写法,以循环形式显示表单
{{ field.label_tag }}:{{ field }}
{{ field.errors }}
{% endfor %}
</table>
<p class="submit"><input type="submit" name="submit" id="submit" class="button-primary" value="注册信息" /></p>
</form>