django Form和ModelForm

本文介绍了如何在Django项目中使用ModelForm构建用户注册和登录表单,包括自定义字段验证和ModelForm的应用。重点讲解了如何利用ModelForm简化表单创建,以及如何进行有效的数据校验。
摘要由CSDN通过智能技术生成

在应用目录下创建form.py文件,利用models.py的模型构建表单

import re

from captcha.fields import CaptchaField
from django import forms
from django.contrib.auth.forms import AuthenticationForm
from django.core.exceptions import ValidationError
from django.forms import Form, ModelForm  # 这个包内也有一个forms,但是不对
from .models import *


# 后端构建表单
# 方式1全部自定义
# class UserRegisterForm(Form):
#     username = forms.CharField(max_length=20, min_length=5, error_messages={'min_length': '太短'}, label='用户名:')
#     password = forms.CharField(max_length=10, min_length=5, error_messages={'min_length': '太短', 'max_length': '太长'},
#                                label='密码:', widget=forms.PasswordInput)
#     repassword = forms.CharField(max_length=10, min_length=5, error_messages={'min_length': '太短', 'max_length': '太长'},
#                                  label='确认密码:', widget=forms.PasswordInput)
#     phone = forms.CharField(required=True, error_messages={'required': '手机号必填'}, label='手机号:', widget=forms.NumberInput)
#     email = forms.CharField(required=True, error_messages={'required': '邮箱必填'}, label='邮箱:')
#     country = forms.ChoiceField(required=False, widget=forms.RadioSelect,
#                                 choices=(('中国', '中国'), ('美国', '美国'), ('俄国', '俄国')), label='国家')
#
#     def clean_email(self):
#         """
#         自定义正则验证
#         :return:
#         """
#         email = self.cleaned_data.get('email')
#         flag = re.match(r'[a-zA-Z1-9_]\w{4,}@(\w+)\.\w+$', email)
#         if not flag:
#             raise ValidationError('邮箱有误!')
#         return email


# 方式2 对模型内容添加或减少 ModelForm只能用于创建和编辑,不能由于验证
class UserRegisterForm(ModelForm):
    class Meta:
        model = User
        fields = '__all__'
        widgets = {'password': forms.PasswordInput}
        # 排除字段
        exclude = ['is_super', 'user_type']
        # 加入字段只能自定义


class UserLoginForm(Form):
    username = forms.CharField(max_length=20, min_length=5, error_messages={'min_length': '太短'}, label='用户名:')
    password = forms.CharField(max_length=10, min_length=5, error_messages={'min_length': '太短', 'max_length': '太长'},
                               label='密码:', widget=forms.PasswordInput)

    # captcha = CaptchaField(label='验证码')

    # 自定义验证
    def clean_username(self):
        username = self.cleaned_data.get('username')
        flag = re.match(r'[a-zA-Z1-9]\w{5,}$', username)
        if not flag:
            raise ValidationError('用户名格式有误')
        return username

在view.py接收请求

def register(request):
    if request.method == 'POST':
        # 获得表单值
        user_register_form = UserRegisterForm(request.POST)
        # 验证
        flag = user_register_form.is_valid()
        if flag:
            # 将数据接收形成一个字典
            data = user_register_form.cleaned_data
            password = make_password(data['password'])
            user = User.objects.create(username=data['username'], password=password, phone=data['phone'],
                                       email=data['email'], country=data['country'], usertype_id=1)
            if user:
                token = str(uuid.uuid4()).replace('-', '')
                # 存储到session中
                request.session['token'] = token
                # 启动异步任务
                sendmail.delay(user.id,data['email'],token)
                return redirect(reverse('myapp:login'))
        return render(request, 'register.html',locals())

    else:
        user_register_form = UserRegisterForm()
        return render(request, "register.html", locals())

def login(request):
    if request.method == 'POST':
        user_login_form = UserLoginForm(request.POST)

        if user_login_form.is_valid():
            data = user_login_form.cleaned_data
            username = data['username']
            password = data['password']
            user = User.objects.get(username=username)
            if check_password(password, user.password):
                request.session['username'] = username
                return HttpResponse('登录成功')
        else:
            print('不成功')
    user_login_form = UserLoginForm()
    return render(request, 'login.html', locals())

在html页面渲染

{{ user_register_form.as_ul }}

{{ user_login_form.as_p }}

还有很多种as_..

<form action="{% url 'myapp:register' %}" method="post">
    {% csrf_token %}
    {{ user_register_form.as_ul }}
    <input type="submit" value="注册">
{#    <p>#}
{#        {{ user_register_form.error }}#}
{#    </p>#}
</form>


<form action="{% url 'myapp:login' %}" method="post">
    {% csrf_token %}
    {{ user_login_form.as_p }}
    <p><label for="">验证码:</label><input type="text" name="code"><img id="generated_code" src="{% url 'myapp:draw' %}" alt=""></p>
    <p><span id="result"></span></p>
    <br>
    <input type="submit" value="登录">
</form>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值