Django之Form表单

        在Django中有一个验证神器,那就是Form表单,它会自动生成你所需要的表单内容,并自动为你验证是否正确,并可以返回错误的详细信息(前提是你写的详细)。

Django中的Form使用时一般有两种功能:

          1、生成html标签

          2、验证输入内容

接下来我介绍下Django模板中的表单和form表单的区别、

1. Django模板中的表单

       项目DjangoExercise的url.py

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('myform/', include('MyForm.urls', namespace='myform'))
]

        app MyForm的url.py

from django.urls import path
app_name = 'MyForm'

from MyForm.views import Login
urlpatterns = [
    path('login/', Login, name= 'login'),
]

       app MyForm的model.py

from django.db import models

# Create your models here.
class MyFormModel(models.Model):
    username = models.CharField(max_length=10, verbose_name='用户名')
    password = models.CharField(max_length=10, verbose_name='密码')
    email = models.EmailField(verbose_name='邮箱')

       app MyForm的views.py

from django.shortcuts import render, HttpResponse
from MyForm.models import MyFormModel

# Create your views here.
def Login(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        email = request.POST.get('email')
        if not all([id, username, password, email]):
            return HttpResponse('参数不全')
        else:
            user = MyFormModel.objects.filter(username=username, password=password)
            if len(user):
                context = {
                    'username': username,
                }
                return render(request, 'MyForm/index.html', context)
    else:
        return render(request, 'MyForm/login.html')

       app MyForm的admin.py

from django.contrib import admin
from MyForm.models import MyFormModel
# Register your models here.

class MyFormAdmin(admin.ModelAdmin):
    list_display = ['username', 'password', 'email']

admin.site.register(MyFormModel, MyFormAdmin)

        templates/MyForm/login.html




    
    Title


{% csrf_token %}


         templates/MyForm/index.html




    
    Title


欢迎

{{ username }}

登陆!

我们首先生成SQL语句,然后在执行SQL语句

       python manage.py makemigrations

       python manage.py migrate

然后就会在数据库中看到我们的表了,因为我把model注册到admin中去了,而且我views.py中并没有写关于model的注册,我直接在admin中注册用户,想用进入admin需要创建superuser

      python manage.py createsuperuser

然后根据提示一步步填写用户名密码

启动项目

        python manage.py runserver

进入到admin中

Django之Form表单_第1张图片

根据箭头提示增加用户名、密码、邮箱

Django之Form表单_第2张图片

然后就会在表中看到我们新增的数据

Django之Form表单_第3张图片

接着输入路由规则,进入到我们的login视图中,输入前面创建的用户名、密码、邮箱,点击登录

Django之Form表单_第4张图片

点击登录会跳转到我们指定的视图中

Django之Form表单_第5张图片

一套简单的流程下来就是Django基于模板的用户登录过程

 

2. Django的form表单

1. 在app  MyForm目录下创建formas.py文件

from django import forms
from django.contrib import auth
from django.contrib.auth.models import User

class LoginForm(forms.Form):
    username = forms.CharField()
    password = forms.CharField()

    def clean(self):
        username = self.cleaned_data['username']
        password = self.cleaned_data['password']

        user = auth.authenticate(username=username, password=password)
        if user is None:
            raise forms.ValidationError('用户名或密码不正确')
        else:
            self.cleaned_data['user'] = user
        return self.cleaned_data


# 注册
class RegForm(forms.Form):
    username = forms.CharField(label='用户名',
                               max_length=30,
                               min_length=3,
                               widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'请输入3-30位用户名'}))
    email = forms.EmailField(label='邮箱',
                             widget=forms.EmailInput(attrs={'class':'form-control', 'placeholder':'请输入邮箱'}))
    password = forms.CharField(label='密码',
                               min_length=6,
                               widget=forms.PasswordInput(attrs={'class':'form-control', 'placeholder':'请输入密码'}))
    password_again = forms.CharField(label='再输入一次密码',
                                     min_length=6,
                                     widget=forms.PasswordInput(attrs={'class':'form-control', 'placeholder':'再输入一次密码'}))

    def clean_username(self):
        username = self.cleaned_data['username']
        if User.objects.filter(username=username).exists():
            raise forms.ValidationError('用户名已存在')
        return username

    def clean_email(self):
        email = self.cleaned_data['email']
        if User.objects.filter(email=email).exists():
            raise forms.ValidationError('邮箱已存在')
        return email

    def clean_password_again(self):
        password = self.cleaned_data['password']
        password_again = self.cleaned_data['password_again']
        if password != password_again:
            raise forms.ValidationError('两次输入的密码不一致')
        return password_again

接着在views.py文件里面加入我们的视图,这里我把前面写的也加入了进来

from django.shortcuts import render, HttpResponse, redirect, reverse
from MyForm.models import MyFormModel
from .forms import LoginForm, RegForm
from django.contrib.auth import authenticate, login
from django.contrib.auth.models import User

# Create your views here.
def Login(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        email = request.POST.get('email')
        if not all([id, username, password, email]):
            return HttpResponse('参数不全')
        else:
            user = MyFormModel.objects.filter(username=username, password=password)
            if len(user):
                context = {
                    'username': username,
                }
                return render(request, 'MyForm/index.html', context)
    else:
        return render(request, 'MyForm/login.html')


def loginForm(request):
    if request.method == 'POST':
        login_form = LoginForm(request.POST)
        # 判断是否验证登录通过
        if login_form.is_valid():
            # 验证过程写在了forms.py文件中了,所以这里可以不用写
            # #清洗后的数据, 包含了我们所需要的字段信息 cleaned_data是我们forms中清洗后验证通过的数据
            # username = login_from.cleaned_data['username']
            # password = login_from.cleaned_data['password']
            # # 验证用户数据是否存在
            # user = authenticate(request, username=username, password=password)
            # if user is not None:
            #     # 将登录后的数据存在session中
            #     login(request, user)
            #     return render(request, 'MyForm/index.html', {'username': username})
            user = login_form.cleaned_data['user']
            login(request, user)
            return render(request, 'MyForm/index.html', {'username': user.username})
    else:
        login_from = LoginForm()
        context = {
            'login_form': login_from
        }
        return render(request, 'MyForm/login_form.html', context)

# 注册
def register(request):
    if request.method == 'POST':
        reg_form = RegForm(request.POST)
        if reg_form.is_valid():
            username = reg_form.cleaned_data['username']
            email = reg_form.cleaned_data['email']
            password = reg_form.cleaned_data['password']
            # 创建用户
            user = User.objects.create_user(username, email, password)
            user.save()
            # 登录用户
            user = authenticate(username=username, password=password)
            login(request, user)
            return render(request, 'MyForm/index.html', {'username': user.username})
    else:
        reg_form = RegForm()
    context = {}
    context['reg_form'] = reg_form
    return render(request, 'MyForm/register.html', context)

接着在urls.py文件中加入我们的路由规则

from django.urls import path
app_name = 'MyForm'

from MyForm.views import Login, loginForm, register
urlpatterns = [
    path('login/', Login, name= 'login'),
    path('form/', loginForm, name= 'login_form'),
    path('register/', register, name= 'register')
]

html模板

我们新增了两个HTML文件 login_form.html 和 register.html

login_form.html




    
    Title


{% csrf_token %} {{ login_form }} {# 用户名:#} {# #} {# 密 码:#} {# #}

 register.html




    
    Title


    
{% csrf_token %} {% for field in reg_form %} {{ field }}

{{ field.errors.as_text }}

{% endfor %} {{ reg_form.non_field_errors }}

根据路由规则来注册我们的用户信息,这个用户数据在auth_user表中,因为我们在views.py中用的是Django的auth表

Django之Form表单_第6张图片

接着会跳转到我们制定的界面中去

Django之Form表单_第7张图片

你可能感兴趣的:(Django,from,Django)