django表单

一、Form表单

settings.py

INSTALLED_APPS = [
    'practise.apps.PractiseConfig',
]

urls.py

urlpatterns = [
    path('practise/', include(('practise.urls', 'practise'), namespace='practise')),
]

practise/forms.py

#!/usr/bin/env python3
# coding=utf-8
# Version:python3.6.1
# Project:mysite
# File:forms.py
# Data:2020/12/25 15:27
# Author:LGSP_Harold
import re

from django import forms

from weibo.models import WeiboUser


class UserLoginForm(forms.Form):
    username = forms.CharField(label='用户名', max_length=64)
    password = forms.CharField(label='密码', max_length=64, widget=forms.PasswordInput)
    verify_code = forms.CharField(label='验证码', max_length=4)

    def clean_username(self):
        username = self.cleaned_data['username']
        username = username.strip()
        pattern = r'^[0]{0,1}[1][0-9]{10}$'
        if not username:
            raise forms.ValidationError('用户名不能为空')
        if not re.search(pattern, username):
            raise forms.ValidationError('请输入正确的手机号码')
        return username

    def clean_password(self):
        password = self.cleaned_data['password']
        password = password.strip()
        if not password:
            raise forms.ValidationError('密码不能为空')
        return password

    def clean_verify_code(self):
        verify_code = self.cleaned_data['verify_code']
        verify_code = verify_code.strip()
        if not verify_code:
            raise forms.ValidationError('验证码不能为空')
        return verify_code

    def clean(self):
        cleaned_data = super().clean()
        username = cleaned_data.get('username', None)
        username = username.strip()
        password = cleaned_data.get('password', None)
        password = password.strip()

        if username and password:
            user_list = WeiboUser.objects.filter(username=username)
            if user_list.count() == 0:
                raise forms.ValidationError('用户名不存在!')
            if not user_list.filter(password=password).exists():
                raise forms.ValidationError('用户密码错误!')

        return cleaned_data


class UserRegisterForm(forms.Form):
    username = forms.CharField(label='用户名', max_length=64)
    nickname = forms.CharField(label='昵称', max_length=64)
    verify_code = forms.CharField(label='验证码', max_length=4)
    password = forms.CharField(label='密码', max_length=64, widget=forms.PasswordInput)
    password_repeat = forms.CharField(label='确认密码', max_length=64, widget=forms.PasswordInput)

    def clean_username(self):
        username = self.cleaned_data['username']
        username = username.strip()
        pattern = r'^[0]{0,1}[1][0-9]{10}$'
        if not username:
            raise forms.ValidationError('用户名不能为空')
        if not re.search(pattern, username):
            raise forms.ValidationError('请输入正确的手机号码')
        user_list = WeiboUser.objects.filter(username=username)
        if user_list.count() != 0:
            raise forms.ValidationError('该手机号已注册')
        return username

    def clean_password(self):
        password = self.cleaned_data['password']
        password = password.strip()
        if not password:
            raise forms.ValidationError('密码不能为空')
        return password

    def clean_password_repeat(self):
        password_repeat = self.cleaned_data['password_repeat']
        password_repeat = password_repeat.strip()
        if not password_repeat:
            raise forms.ValidationError('确认密码不能为空')
        return password_repeat

    def clean_verify_code(self):
        verify_code = self.cleaned_data['verify_code']
        verify_code = verify_code.strip()
        if not verify_code:
            raise forms.ValidationError('验证码不能为空')
        return verify_code

    def clean(self):
        cleaned_data = super().clean()
        password = cleaned_data.get('password', None)
        password = password.strip()
        password_repeat = cleaned_data.get('password_repeat', None)
        password_repeat = password_repeat.strip()
        if password != password_repeat:
            raise forms.ValidationError('两次密码不一样')

        return cleaned_data

practise/urls.py

#!/usr/bin/env python3
# coding=utf-8
# Version:python3.6.1
# Project:mysite
# File:urls.py
# Data:2020/12/25 16:14
# Author:LGSP_Harold
from django.urls import path

from practise import views

urlpatterns = [
    path('forms/pf1/', views.user_login, name='pf1'),
    path('forms/pf2/', views.user_register, name='pf2'),
]

practise/views.py

from django.shortcuts import render

from practise.forms import UserLoginForm, UserRegisterForm


def user_login(request):
    if request.method == 'POST':
        form = UserLoginForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            print('登录成功', data)
        else:
            print(form.errors)
    else:
        form = UserLoginForm()
    return render(request, 'practise_form_login.html', {
        'form': form
    })


def user_register(request):
    if request.method == 'POST':
        form = UserRegisterForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data
    else:
        form = UserRegisterForm()
    return render(request, 'practise_form_register.html', {
        'form': form
    })

practise/templates/practise_form_register.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>注册表单</title>
</head>
<body>
<form action="." method="post">
    <div>
        <p>{{ form.username.label }}</p>
        <p>
            {{ form.username }}
            <span>{{ form.username.errors.as_text }}</span>
        </p>
    </div>
    <div>
        <p>{{ form.nickname.label }}</p>
        <p>
            {{ form.nickname }}
            <span>{{ form.nickname.errors.as_text }}</span>
        </p>
    </div>
    <div>
        <p>{{ form.password.label }}</p>
        <p>
            {{ form.password }}
            <span>{{ form.password.errors.as_text }}</span>
        </p>
    </div>
    <div>
        <p>{{ form.password_repeat.label }}</p>
        <p>
            {{ form.password_repeat }}
            <span>{{ form.password_repeat.errors.as_text }}</span>
        </p>
    </div>
    <div>
        <p>{{ form.verify_code.label }}</p>
        <p>
            {{ form.verify_code }}
            <span>{{ form.verify_code.errors.as_text }}</span>
        </p>
    </div>
    <p><input type="submit" value="注册并登录"></p>
    <p>{{ form.non_field_errors.as_text }}</p>
</form>
</body>
</html>

practise/templates/practise_form_login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录表单</title>
</head>
<body>
<form action="." method="post">
    <div>
        <p>{{ form.username.label }}</p>
        <p>
            {{ form.username }}
            <span>{{ form.username.errors.as_text }}</span>
        </p>
    </div>
    <div>
        <p>{{ form.password.label }}</p>
        <p>{{ form.password }}</p>
    </div>
    <div>
        <p>{{ form.verify_code.label }}</p>
        <p>
            {{ form.verify_code }}
            <span>{{ form.verify_code.errors.as_text }}</span>
        </p>
    </div>
    <p><input type="submit" value="提交"></p>
    <p>{{ form.non_field_errors.as_text }}</p>
</form>
</body>
</html>

 

二、Model表单

practise/model_forms.py

#!/usr/bin/env python3
# coding=utf-8
# Version:python3.6.1
# Project:mysite
# File:model_forms.py
# Data:2020/12/26 16:17
# Author:LGSP_Harold
import re

from django import forms

from weibo.models import WeiboUser


class UserForm(forms.ModelForm):
    class Meta:
        model = WeiboUser
        fields = ['username', 'password', 'nickname', 'remark']
        widgets = {
            'password': forms.PasswordInput,
            'remark': forms.Textarea(attrs={
                'class': 'text-error',
            }),
        }
        labels = {
            'username': '手机号码',
        }
        error_messages = {
            'username': {
                'required': '请输入手机号',
            }
        }
        help_texts = {
            'remark': '字数不超过256'
        }

    def clean_username(self):
        username = self.cleaned_data['username']
        username = username.strip()
        pattern = r'^[0]{0,1}[1][0-9]{10}$'
        if not username:
            raise forms.ValidationError('用户名不能为空')
        if not re.search(pattern, username):
            raise forms.ValidationError('请输入正确的手机号码')
        user_list = WeiboUser.objects.filter(username=username)
        if user_list.count() != 0:
            raise forms.ValidationError('该手机号已绑定')
        return username

practise/urls.py

#!/usr/bin/env python3
# coding=utf-8
# Version:python3.6.1
# Project:mysite
# File:urls.py
# Data:2020/12/25 16:14
# Author:LGSP_Harold
from django.urls import path

from practise import views

urlpatterns = [
    path('model_forms/pmf1/', views.user_edit, name='pmf1'),
]

practise/views.py

from django.shortcuts import render

from practise.model_forms import UserForm


def user_edit(request):
    if request.method == 'POST':
        form = UserForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            print('修改成功', data)
        else:
            print(form.errors)
    else:
        form = UserForm()
    return render(request, 'practise_model_form_edit.html', {
        'form': form
    })

practise/templates/practise_model_form_edit.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>用户信息编辑</title>
    <style type="text/css">
        .text-error {
            color: red;
        }
    </style>
</head>
<body>
<form action="." method="post">
    <div>
{#        {{ form.as_p }}#}
        <p>{{ form.username.label }}</p>
        <p>
            {{ form.username }}
            <span>{{ form.username.errors.as_text }}</span>
        </p>
    </div>
    <div>
        <P>{{ form.password.label }}</P>
        <P>
            {{ form.password }}
            <span>{{ form.password.error.as_text }}</span>
        </P>
    </div>
    <div>
        <p>{{ form.nickname.label }}</p>
        <p>
            {{ form.nickname }}
            <span>{{ form.nickname.error.as_text }}</span>
        </p>
    </div>
    <div>
        <p>{{ form.remark.label }}</p>
        <div>
            {{ form.remark }}
            <span>{{ form.remark.help_text }}</span>
            <span>{{ form.remark.error.as_text }}</span>
        </div>
    </div>
    <p><input type="submit" value="更新用户数据"></p>
    <p></p>
</form>
</body>
</html>

 

posted @ 2020-12-29 12:07  嘆世殘者——華帥  阅读(95)  评论(0编辑  收藏  举报