文章目录
form的主要作用:
python中的、1.在html中生成表单框架,2.验证数据
https://www.cnblogs.com/zongfa/p/7709639.html
1.在model里创建一些数据类型
python表单。class Users(models.Model):
uname = models.CharField(max_length=30,unique=True,verbose_name="用户名")
upet = models.CharField(max_length=30,verbose_name="昵称")
python中的类,upawd = models.CharField(max_length=30,verbose_name="密码")
email = models.EmailField(verbose_name="电子邮件")
url = models.URLField(verbose_name="网址")
python main、2.在model.py同级目录下新建forms.py
有两种写法:
(1)定义表单模型
python opencv、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')
3.在view视图中 ,做表单验证
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:
4.在html页面,代码超简单,这点django做的不错
# 这是第一种写法,在
# 这是第二种写法,在
显示表单
# 这是第三种写法,在
{% for field in form %} # 这是第四种写法,以循环形式显示表单
{{ field.label_tag }}:{{ field }}
{{ field.errors }}
{% endfor %}
标签:form,Python,表单,forms,models,使用,label,email
来源: https://blog.csdn.net/weixin_45414731/article/details/100735091
版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。
工作时间:8:00-18:00
客服电话
电子邮件
admin@qq.com
扫码二维码
获取最新动态