Form.form是一种内置的模板吧,它有自己设置的表单样式
可以引用它,但我觉得还是自己写会比较好吧
继承的是forms类了而不是models类了
然后就是表单得验证,也是用了内置得数据库叫做
authenticate,login就是存admin密码的那个
概述
表单既可以在模板页面利用HTML编写,也可以使用Django提供的表单类编写。
相关属性参考官网:https://docs.djangoproject.com/en/1.11/ref/forms/fields/
实现熟悉的用户登录功能
- 创建新应用account
- settings中添加应用
- 配置URL
- 在account应用中创建forms.py文件
- 编写views函数
- 创建模板页面
- 启动服务器运行程序
配置URL
from django.conf.urls import url, includefrom django.contrib import admin?urlpatterns = [ url(r‘^admin/‘, admin.site.urls), url(r‘^account/‘,include(‘account.urls‘,namespace=‘account‘,app_name=‘account‘))]??
#coding=utf-8??from django.conf.urls import urlimport views?urlpatterns=[ url(r‘^login/$‘,views.login_view,name=‘login‘)]? ?
编写表单类(account.forms.LoginForm)
#coding=utf-8??from django import forms?class LoginForm(forms.Form): username = forms.CharField(label=u‘用户名‘) password = forms.CharField(label=u‘密码‘,widget=forms.PasswordInput)???
配置视图函数
# -*- coding: utf-8 -*-from __future__ import unicode_literals?from django.http import HttpResponsefrom django.shortcuts import renderfrom .forms import LoginFormfrom django.contrib.auth import authenticate,login???# Create your views here.def login_view(request): if request.method==‘GET‘: login_form = LoginForm() return render(request,‘login.html‘,{‘login_form‘:login_form})? else: login_form= LoginForm(request.POST)?? #校验表单数据是否合法 if login_form.is_valid(): #以字典形式返回合法数据 cd = login_form.cleaned_data print cd #检验用户输入的用户和密码是否正确 user = authenticate(username=cd[‘username‘],password=cd[‘password‘]) print user? if user: #实现用户登录,将用户信息保存到session中完成登录操作 login(request,user) return HttpResponse(‘success‘)? return HttpResponse(‘failed‘)?
配置模板页面(login.html)
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title></head><body>? <form action="" method="post"> {% csrf_token %} {{ login_form.as_p }}?{# {% for field in login_form %}#}{# {{ field.label_tag }}{{ field }}#}{# {{ field.errors }}#}{# {% endfor %}#}? <input type="submit" value="登录"/> </form></body></html>?
应用场景
- 查询时表单类只需要继承于forms.Form。
- 增删改时表单类需要继承于forms.ModelForm。
学生注册案例
创建模型类
# -*- coding: utf-8 -*-from __future__ import unicode_literals?from django.db import models?# Create your models here.?class Clazz(models.Model): cno = models.AutoField(primary_key=True) cname = models.CharField(max_length=20)? def __unicode__(self): return u‘Clazz:%s‘%self.cname ?class Stu(models.Model): sno = models.AutoField(primary_key=True) sname = models.CharField(max_length=30) clazz = models.ForeignKey(Clazz,on_delete=models.CASCADE)? def __unicode__(self): return u‘Stu:%s,%s‘%(self.sno,self.sname)????
创建表单类(应用包下创建forms.py)
#coding=utf-8??from django import formsfrom .models import *?class Add_Clazz(forms.ModelForm): class Meta: model = Clazz #元组形式 fields = (‘cname‘,)??class Add_Stu(forms.ModelForm): class Meta: model = Stu fields = (‘sname‘,)?
配置URL
from django.conf.urls import url, includefrom django.contrib import admin?urlpatterns = [ url(r‘^admin/‘, admin.site.urls), url(r‘^student/‘, include(‘student.urls‘)),]??
#coding=utf-8??from django.conf.urls import urlimport views?urlpatterns=[ url(r‘^register/$‘,views.register)?]?
创建视图
# -*- coding: utf-8 -*-from __future__ import unicode_literals?from django.http import HttpResponsefrom django.shortcuts import renderfrom .forms import Add_Clazz,Add_Stu# Create your views here.?def register(request): if request.method==‘POST‘: ac = Add_Clazz(request.POST) astu = Add_Stu(request.POST)? if ac.is_valid()*astu.is_valid(): new_clazz = ac.save() new_stu = astu.save(commit=False) new_stu.clazz = new_clazz new_stu.save() return HttpResponse(‘successfully‘) else: return HttpResponse(‘sorry,you can not register.‘) else: ac = Add_Clazz() astu = Add_Stu() return render(request,‘register.html‘,{‘ac‘:ac,‘astu‘:astu})?
创建模板
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title></head><body>??<form action="/student/register/" method="post"> {% csrf_token %} <p> <label for="{{ astu.sname.id_for_label }}">姓名:</label>{{ astu.sname }} </p> <p> <label for="{{ ac.cname.id_for_label }}">班级:</label>{{ ac.cname }} </p> <p> <input type="submit" value="注册" /> </p>?</form>?</body></html>?
- JS前端校验
- forms表单类自定义校验
表单类
#coding=utf-8??from django import formsfrom .models import *?class Add_Clazz(forms.ModelForm): class Meta: model = Clazz fields = (‘cname‘,)??class Add_Stu(forms.ModelForm): password = forms.CharField(max_length=30,widget=forms.PasswordInput) password2 = forms.CharField(max_length=30,widget=forms.PasswordInput)?? class Meta: model = Stu fields = (‘sname‘,)? def clean_password2(self): cd = self.cleaned_data if cd[‘password‘]!=cd[‘password2‘]: self.errors[‘password2‘] = [‘密码不一致‘]? # raise forms.ValidationError(‘密码不一致!‘) return cd[‘password2‘]???
视图函数
# -*- coding: utf-8 -*-from __future__ import unicode_literals?from django.http import HttpResponsefrom django.shortcuts import renderfrom .forms import Add_Clazz,Add_Stufrom . models import *# Create your views here.?def register(request): if request.method==‘POST‘: ac = Add_Clazz(request.POST) astu = Add_Stu(request.POST)??? if ac.is_valid()*astu.is_valid(): try: new_clazz = Clazz.objects.get(cname=ac.cleaned_data[‘cname‘]) except Clazz.DoesNotExist: #保存数据到数据库 new_clazz = ac.save() #保存数据对象不提交数据库 new_stu = astu.save(commit=False) new_stu.clazz = new_clazz new_stu.password = astu.clean_password2() new_stu.save() return HttpResponse(‘successfully‘) else: return render(request,‘register.html‘,{‘ac‘:ac,‘astu‘:astu}) else: ac = Add_Clazz() astu = Add_Stu() return render(request,‘register.html‘,{‘ac‘:ac,‘astu‘:astu})?
模板页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/student/register/" method="post">
{% csrf_token %}
<p>
<label for="{{ astu.sname.id_for_label }}">姓名:</label>{{ astu.sname }}
</p>
<p>
<label for="{{ astu.password.id_for_label }}">密码:</label>{{ astu.password }}
</p>
<p>
<label for="{{ astu.password2.id_for_label }}">密码:</label>{{ astu.password2 }}<span style="color: red;">{{ astu.errors.password2.0 }}</span>
</p>
<p>
<label for="{{ ac.cname.id_for_label }}">班级:</label>{{ ac.cname }}
</p>
<p>
<input type="submit" value="注册" />
</p>
</form>
</body>
</html>
原文地址:https://www.cnblogs.com/Py-king/p/10590373.html