Django用户注册、登录

一、用户注册

 1 '''
 2 注册的表单模型
 3 forms.py 的例子
 4 '''
 5 
 6 from django import forms #表单功能
 7 from django.contrib.auth.models import User
 8 class RegForm(forms.Form):
 9     '''
10     用户注册表单
11     '''
12     #用户
13     username = forms.CharField(label='用户名',max_length=30,min_length=3,widget=forms.TextInput(
14                                 attrs={'class':'form-control','placeholder':'请输入用户名'}))
15     #邮箱
16     email = forms.EmailField(label='邮箱',widget=forms.EmailInput(
17                                 attrs={'class':'form-control','placeholder':'请输入邮箱'}))
18     #密码
19     password = forms.CharField(label='密码',min_length=8,widget=forms.PasswordInput(
20                                 attrs={'class':'form-control','placeholder':'请输入密码'}))
21     #再次输入密码
22     password_again = forms.CharField(label='再次输入密码',min_length=8,widget=forms.PasswordInput(
23                                 attrs={'class':'form-control','placeholder':'请再次输入密码'}))
24 
25 
26     def clean_username(self):
27         '''
28         清洗输入的用户名
29         :return: 清洗后的用户名
30         '''
31         username =  self.cleaned_data['username']
32         if User.objects.filter(username=username).exists():
33             raise forms.ValidationError('用户名已存在')
34         return username
35 
36 
37     def clean_email(self):
38         '''
39         清洗输入的邮箱
40         :return: 清洗后输入的邮箱
41         '''
42         email = self.cleaned_data['email']
43         if User.objects.filter(email=email).exists():
44             raise forms.ValidationError('邮箱已存在')
45         return email
46 
47 
48     def clean_password_again(self):
49         '''
50         清洗输入的密码
51         :return: 输出对比一致的密码
52         '''
53         password = self.cleaned_data['password']
54         password_again = self.cleaned_data['password_again']
55         if password != password_again:
56             raise forms.ValidationError('两次输入的密码不一致')
57         return password
forms.py
 1 '''
 2 注册的函数模型
 3 views.py样子
 4 '''
 5 from django.shortcuts import redirect,render
 6 from django.contrib import auth #django标准的权限管理模型
 7 from django.urls import reverse #反向解析
 8 from django.contrib.auth.models import User
 9 from .forms import  RegForm
10 
11 def register(request):
12     '''
13     用户注册相关功能处理
14     :param request:请求对象
15     :return: 注册充公返回首页,失败返回注册表单
16     '''
17     if request.method == 'POST':
18         reg_form = RegForm(request.POST)
19         if reg_form.is_valid():
20             username = reg_form.cleaned_data['username']
21             email = reg_form.cleaned_data['email']
22             password = reg_form.cleaned_data['password']
23             user = User.objects.create_user(username=username,email=email,password=password)
24             user.save()
25             user = auth.authenticate(username,password)
26             auth.login(request,user)
27             return redirect(request.GET.get('from',reverse('blog:home')))
28     else:
29         reg_form = RegForm()
30     context = {'reg_form':reg_form}
31     return render(request,'user/register.html',context)
views.py
<div class="col-xs-11 col-sm-5 col-lg-4 col-sm-offset-4 blog-border side-info">
    <h4>欢迎注册h4>
    <form action="" method="POST">{% csrf_token %}

        {% for field in reg_form %}
            {# label去冒号 #}
            <label for="{{ field.id_for_label }}">{{ field.label }}label>
                {{ field }}
            <p class="text-danger">{{ field.errors.as_text }}p>
        {% endfor %}
            {# 错误信息标红 #}
            <span class="pull-left text-danger">{{ login_form.non_field_errors }}span>
            {# <span>用户名:span> #}
            {# <input type="text" name="username"> #}
            {# <span>密码:span> #}
            {# <input type="password" name="password"> #}
            <span style="font-weight: bold;">已有帐号?<a style="color: #337ab7;" href="{% url 'user:login' %}">点击登录a>span>
        <input class="btn btn-primary pull-right" style="margin-bottom: 0.5em" type="submit" value="注册">
    form>
    {% if user.is_authenticated %}
        <script type="text/javascript">
            window.location.href = '/';
        script>
    {% else %}

    {% endif %}
div>
View Code

二、用户登录

 1 '''
 2 用户登录表单模型
 3 forms.py 的例子
 4 '''
 5 from django import forms #表单功能
 6 from django.contrib.auth.models import User
 7 from django.contrib import auth
 8 class LoginForm(forms.Form):
 9     '''
10     用户登录
11     '''
12     username = forms.CharField(label='用户名', max_length=30, min_length=3, widget=forms.TextInput(
13         attrs={'class': 'form-control', 'placeholder': '请输入用户名'}))
14     password = forms.CharField(label='密码', min_length=8, widget=forms.PasswordInput(
15         attrs={'class': 'form-control', 'placeholder': '请输入密码'}))
16 
17 
18     def clean(self):
19         '''
20         清洗输入不合格的表单
21         :return: 清洗后的数据
22         '''
23         username = self.cleaned_data['username']
24         password = self.cleaned_data['password']
25         user = auth.authenticate(username,password)
26         if user is None:
27             raise forms.ValidationError('用户名或密码错误')
28         else:
29             self.cleaned_data['user'] = user
30 
31         return self.cleaned_data
forms.py
 1 '''
 2 用户登录函数模型
 3 views.py样子
 4 '''
 5 from django.shortcuts import redirect,render
 6 from django.contrib import auth #django标准的权限管理模型
 7 from django.urls import reverse #反向解析
 8 from .forms import  LoginForm
 9 def login_m(request):
10     '''
11     用户登录处理逻辑
12     :param request:
13     :return: 登录视图
14     '''
15     if request.method == 'POST':
16         login_form = LoginForm(request.POST)
17         user = login_form.cleaned_data['user']
18         auth.login(request,user)
19         referer = request.GET.get('from',reversed('blog:blog'))
20         return redirect(referer)
21     else:
22         login_form = LoginForm()
23 
24     context = {'login_form':login_form}
25     return render(request,'user/login.html',context)
views.py
 1 <div class="col-xs-11 col-sm-5 col-lg-4 col-sm-offset-4 blog-border side-info">
 2     <h4>用户登录h4>
 3 
 4      <form action="" method="POST">
 5          {% csrf_token %}
 6          {% for field in login_form %}
 7              <label for="{{ field.id_for_label }}">{{ field.label }}label>
 8              {{ field }}
 9              <p class="text-danger">{{ field.errors.as_text }}p>
10          {% endfor %}
11             {# 错误信息标红 #}
12             <span class="pull-left text-danger">{{ login_form.non_field_errors }}span>
13             {# <span>用户名:span> #}
14             {# <input type="text" name="username"> #}
15             {# <span>密码:span> #}
16             {# <input type="password" name="password"> #}
17             <span style="font-weight: bold;">没有帐号?<a style="color: #337ab7;" href="{% url 'user:register' %}">点击注册a>span>
18             <input class="btn btn-primary pull-right" style="margin-bottom: 0.5em" type="submit" value="登录">
19      form>
20 
21     {% if user.is_authenticated %}
22         <script type="text/javascript">
23             window.location.href = '/';
24         script>
25     {% else %}
26     {% endif %}
27 div>
View Code

 

转载于:https://www.cnblogs.com/cxys85/p/11282474.html

你可能感兴趣的:(Django用户注册、登录)