用Django内置form组件实现注册

Posted wen-kang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了用Django内置form组件实现注册相关的知识,希望对你有一定的参考价值。

html页面代码块:

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5 
 6     <link rel="stylesheet" href="/static/bootstrap/css/bootstrap.min.css">
 7     <title>首页</title>
 8 </head>
 9 <body>
10 
11 <div class="container">
12     <div class="row">
13         <div class="col-md-6 col-md-offset-3">
14             <form action="/index/" method="post" novalidate>
15                 {% csrf_token %}
16                 <div class="form-group {% if reg.user.errors.0 %} has-error {% endif %}">
17                     {{ reg.user.label }}
18                     {{ reg.user }}
19                     <span class="help-block" id="s1">{{ reg.user.errors.0 }}</span>
20                 </div>
21                 <div class="form-group {% if reg.psd.errors.0 %} has-error {% endif %}">
22                     {{ reg.psd.label }}
23                     {{ reg.psd }}
24                     <span class="help-block">{{ reg.psd.errors.0 }}</span>
25                 </div>
26                 <div class="form-group {% if reg.re_pwd.errors.0 %} has-error {% endif %}">
27                     {{ reg.re_pwd.label }}
28                     {{ reg.re_pwd }}
29                     <span class="help-block">{{ reg.re_pwd.errors.0 }}</span>
30                 </div>
31                 <div class="form-group {% if reg.email.errors.0 %} has-error {% endif %}">
32                     {{ reg.email.label }}
33                     {{ reg.email }}
34                     <span class="help-block">{{ reg.email.errors.0 }}</span>
35                 </div>
36                 <div class="form-group {% if reg.mobile.errors.0 %} has-error {% endif %}">
37                     {{ reg.mobile.label }}
38                     {{ reg.mobile }}
39                     <span class="help-block">{{ reg.mobile.errors.0 }}</span>
40                 </div>
41 
42                 <div class="form-group {% if reg.city.errors.0 %} has-error {% endif %}">
43                     {{ reg.city.label }}
44                     {{ reg.city }}
45                     <span class="help-block">{{ reg.city.errors.0 }}</span>
46                 </div>
47                 <div class="form-group">
48                     <button type="submit" class="btn btn-success">登录</button>
49                 </div>
50 
51             </form>
52         </div>
53     </div>
54 
55 </div>
56 
57 <script src="/static/jquery-3.3.1.min.js"></script>
58 <script src="/static/csrf_ajax.js"></script>
59 <script src="/static/bootstrap/js/bootstrap.min.js"></script>
60 <script>
61     $("#id_user").on (input,function () {
62         var user=$(this).val();
63         $("#s1").text(‘‘);
64         $.ajax({
65             url:/check/,
66             type:POST,
67             data:{"user":user},
68             datatype:json,
69             success:function (arg) {
70                 if (arg){
71 
72                     $("#s1").text(arg).css("color", "red");
73 
74                 }
75 
76             }
77         })
78     })
79 </script>   
80 </body>
81 </html>

views代码块的逻辑处理:>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

 1 from django.shortcuts import render,redirect,HttpResponse
 2 
 3 # Create your views here.
 4 
 5 from appfind import models
 6 
 7 def check(request):
 8     if request.method=="POST":
 9         user=request.POST.get(user)
10         user_obj=models.UserInfo.objects.filter(user=user)
11         if user_obj:
12             msg=用户名已存在。请更换!
13         else:
14             msg=‘‘
15         return HttpResponse(msg)
16 
17 from django import forms
18 from django.forms import widgets
19 from django.core.validators import RegexValidator
20 from  django.core.exceptions import ValidationError
21 class RegForm(forms.Form):  #利用RegForm去生成HTML字段标签
22     user=forms.CharField(max_length=32,label=用户名,
23                          error_messages={"required": "该字段不能为空",},
24                          widget=widgets.TextInput(attrs={class:form-control}))
25     psd=forms.CharField(label=密码,min_length=6,max_length=30,
26                         widget=widgets.PasswordInput(attrs={class:form-control},render_value=True),
27                         error_messages={min_length:密码不能少于6位,
28                                         "max_length": "密码最长30位!",
29                                         "required": "该字段不能为空",})
30     re_pwd = forms.CharField(label=确认密码, min_length=6, max_length=30,
31                              widget=widgets.PasswordInput(attrs={class: form-control}, render_value=True),
32                              error_messages={min_length: 密码不能少于6位,
33                                              "max_length": "密码最长30位!",
34                                              "required": "该字段不能为空", })
35     email=forms.EmailField( label="邮箱",
36                             widget=widgets.EmailInput(attrs={"class": "form-control"}),
37                             error_messages={
38                                 "required": "该字段不能为空",
39                             })
40     mobile = forms.CharField(label="手机",
41                              validators=[
42                                  RegexValidator(r^[0-9]+$,手机号码必须是数字),
43                                  RegexValidator(r^1[3-8][0-9]{9}$,手机格式有误)
44                              ],
45                              widget=widgets.TextInput(attrs={"class": "form-control"}),
46                              error_messages={
47                                  "required": "该字段不能为空",
48                              })
49     def clean_user(self):  #clean_user  user 就是要检验的字段
50         value=self.cleaned_data.get(user)
51         if "独裁" in value:
52             raise ValidationError("不符合社会主义核心价值观!")
53         return value
54 
55     def clean(self):   #重写父类的clean方法
56         # 此时 通过检验的字段的数据都保存在 self.cleaned_data
57         psd=self.cleaned_data.get(psd)
58         re_pwd=self.cleaned_data.get(re_pwd)
59         if psd != re_pwd:
60             self.add_error(re_pwd,ValidationError(两次密码不一致))
61             raise ValidationError(两次密码不一致)
62         return self.cleaned_data
63 
64     city=forms.ChoiceField(
65         choices=models.City.objects.all().values_list(id,name),
66         label=城市,   
67         initial=1,
68         widget=forms.widgets.Select
69     )
70 
71     def __init__(self,*args,**kwargs):   #重写父类的__init__方法
72         super().__init__(*args,**kwargs)  #每次初始化加载插件就重新再数据库里取值
73         self.fields[city].widget.choices=models.City.objects.all().values_list(id,name)
74 
75 def index(request):
76     regform=RegForm()           #实例化一个RegForm对象
77     if request.method=="POST":
78         regform = RegForm(request.POST)  #获取对象
79         if regform.is_valid():           #校验对象的所有字段
80             del regform.cleaned_data[re_pwd]     #删除部分用户表不需要存储的字段
81             del regform.cleaned_data[city]
82             models.UserInfo.objects.create(**regform.cleaned_data)  #数据库添加用户数据
83             return HttpResponse(恭喜,注册成功!)
84 
85     return render(request,index.html,{reg:regform})
86     #get请求直接把RegForm对象传给页面

 

以上是关于用Django内置form组件实现注册的主要内容,如果未能解决你的问题,请参考以下文章

forms组件

Django form表单

Django基于form组件实现注册校验

django—Form组件

Django 第十七篇使用Form组件和Ajax实现用户注册

Django - 基于forms组件和Ajax实现注册登录 - FileField字段 - Media配置