• Django 使用Form组件完成登录注册


    urls.py

    from django.conf.urls import url
    from web import views
    
    urlpatterns = [
        url(r'login/', views.login),
        url(r'rest/', views.rest)
    ]

    views.py

    from __future__ import unicode_literals
    from django.contrib.auth.models import User
    from django.shortcuts import render
    from django.shortcuts import redirect
    from django.shortcuts import HttpResponse
    from my_form import RestForm, LoginForm
    
    
    # 注册
    def rest(request):
        if request.method == "GET":
            form = RestForm()  # 初始化form对象
            return render(request, "web/rest.html", {"form": form})
        else:
            form = RestForm(request.POST)  # 将数据传给form对象
            if form.is_valid():  # 进行校验
                data = form.cleaned_data
                username = data.get("name")
                email = data.get("email")
                password = data.get("password")
                User.objects.create(username=username, email=email, password=password) #使用auth自带的用户数据库
                return redirect("/web/login/")
            else:  # 校验失败
                clear_errors = form.errors.get("__all__")  # 获取全局钩子错误信息
                return render(request, "web/rest.html", {"form": form, "clear_errors": clear_errors})
    
    
    # 登录
    def login(request):
        if request.method == "GET":
            form = LoginForm()
            return render(request, "web/login.html", {"form": form})
        else:
            form = LoginForm(request.POST)
            if form.is_valid():
                return HttpResponse("登陆成功!")
            else:
                clear_errors = form.errors.get("__all__")
                return render(request, "web/login.html", {"form": form, "clear_errors": clear_errors})

    my_form.py

    # -*- coding: utf-8 -*-
    from django.core.exceptions import ValidationError
    from django import forms
    from django.contrib.auth.models import User
    
    
    # 注册表单
    class RestForm(forms.Form):
        name = forms.CharField(min_length=2, label="姓名", error_messages={"required": "该字段不能为空!", "min_length": "用户名太短。"})
        email = forms.EmailField(label="邮箱")
        password = forms.CharField(label="密码", widget=forms.PasswordInput)
        r_password = forms.CharField(label="确认密码", widget=forms.PasswordInput)
    
        def clean_name(self):  # 局部钩子
            val = self.cleaned_data.get("name")
            if val.isdigit():
                raise ValidationError("用户名不能是纯数字")
            elif User.objects.filter(username=val):
                raise ValidationError("用户名已存在!")
            else:
                return val
    
        def clean(self):  # 全局钩子 确认两次输入的工资是否一致。
            val = self.cleaned_data.get("password")
            r_val = self.cleaned_data.get("r_password")
    
            if val == r_val:
                return self.cleaned_data
            else:
                raise ValidationError("密码不一致,请重新输入")
    
    
    # 登陆表单
    class LoginForm(forms.Form):
        name = forms.CharField(max_length=32, label="姓名", error_messages={"required": "该字段不能为空!"})
        password = forms.CharField(label="密码", widget=forms.PasswordInput)
    
        def clean_name(self):
            val = self.cleaned_data.get("name")
            user_list = User.objects.filter(username=val)
            if not user_list:
                raise ValidationError("用户名不存在!")
            else:
                return val
    
        def clean_password(self):
            val = self.cleaned_data.get("name")
            pwd = self.cleaned_data.get("password")
            if User.objects.filter(username=val):
                pwd_list = User.objects.filter(username=val, password=pwd)
                if pwd_list:
                    return self.cleaned_data
                else:
                    raise ValidationError("密码错误!")

    base.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>
            {% block title %}
                title
            {% endblock %}
        </title>
    </head>
    <body>
    <h3>
        {% block h3 %}
            标题
        {% endblock %}
    </h3>
    
    <form action="" method="post" novalidate>
        {% csrf_token %}
        <div>
            <label for="id_{{ form.name.name }}">姓名</label>
            {{ form.name }} <span>{{ form.name.errors.0 }}</span>
        </div>
        <div>
            <label for="id_password">密码</label>
            {{ form.password }} <span>{{ form.password.errors.0 }}{{ clear_errors.0 }}</span>
        </div>
        {% block imp %}
        <div>
            <label for="id_r_password">确认密码</label>
            {{ form.r_password }} <span>{{ form.r_password.errors.0 }}{{ clear_errors.0 }}</span>
        </div>
        <div>
            <label for="id_{{ form.email.name }}">邮箱</label>
            {{ form.email }} <span>{{ form.email.errors.0 }}</span>
        </div>
        {% endblock %}
        <input type="submit">
    </form>
    
    </body>
    </html>

    rest.html

    {% extends 'base.html' %}
    
    {% block title %}
        注册
    {% endblock %}
    
    {% block h3 %}
        用户注册
    {% endblock %}

    login.html

    {% extends 'base.html' %}
    
    {% block title %}
        登录
    {% endblock %}
    
    {% block h3 %}
        用户登录
    {% endblock %}
    
    {% block imp %}
    {% endblock %}
  • 相关阅读:
    后缀数组-另辟蹊径
    Project Euler 不定期更新
    Educational Codeforces Round 93 (Rated for Div. 2)
    Codeforces Round #664 (Div. 2)
    lower_bound和upper_bound的用法
    Codeforces Round #663 (Div. 2)
    Codeforces Round #661 (Div. 3)
    质数笔记
    C++运算符的优先级
    图的构建
  • 原文地址:https://www.cnblogs.com/chunqiu666/p/13723982.html
Copyright © 2020-2023  润新知