码迷,mamicode.com
首页 > 其他好文 > 详细

2019.03.24 表单类

时间:2019-03-24 21:55:47      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:提交数据   end   line   auto   list   rms   star   ace   ade   

Form.form是一种内置的模板吧,它有自己设置的表单样式

可以引用它,但我觉得还是自己写会比较好吧

继承的是forms类了而不是models类了

然后就是表单得验证,也是用了内置得数据库叫做  

authenticate,login
就是存admin密码的那个



概述

表单既可以在模板页面利用HTML编写,也可以使用Django提供的表单类编写。

相关属性参考官网:https://docs.djangoproject.com/en/1.11/ref/forms/fields/

实现熟悉的用户登录功能

  1. 创建新应用account

  2. settings中添加应用

  3. 配置URL

  4. 在account应用中创建forms.py文件

  5. 编写views函数

  6. 创建模板页面

  7. 启动服务器运行程序

配置URL

from django.conf.urls import url, include
from 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 url
import 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 HttpResponse
from django.shortcuts import render
from .forms import LoginForm
from 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>
?

 

应用场景

  1. 查询时表单类只需要继承于forms.Form。

  2. 增删改时表单类需要继承于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 forms
from .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, include
from 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 url
import views
?
urlpatterns=[
  url(r‘^register/$‘,views.register)
?
]
?

创建视图


# -*- coding: utf-8 -*-
from __future__ import unicode_literals
?
from django.http import HttpResponse
from django.shortcuts import render
from .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>
?

 

 

 

  1. JS前端校验

  2. forms表单类自定义校验

表单类


#coding=utf-8
?
?
from django import forms
from .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 HttpResponse
from django.shortcuts import render
from .forms import Add_Clazz,Add_Stu
from . 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>

 

2019.03.24 表单类

标签:提交数据   end   line   auto   list   rms   star   ace   ade   

原文地址:https://www.cnblogs.com/Py-king/p/10590373.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!