Django的form組件應用登錄或者註冊

from django import forms
from django.forms import Form
from django.forms import widgets
from django.forms import fields
from django.core.exceptions import ValidationError
from blog.models import *


class RegisterForm(Form):
    # 自定義form組件
    username = fields.CharField(
        label='用戶名',
        widget=widgets.TextInput(attrs={'class': 'form-control', 'placeholder': "請輸入用戶名"}),
        required=True,
        max_length=32,
        strip=True,
        error_messages={
            'required':'用戶名不能爲空',
            'max_length':'用戶名最大長度爲32',
        }
    )
    email = fields.EmailField(
        label='郵箱',
        widget=widgets.TextInput(attrs={'class': 'form-control', 'placeholder': "請輸入郵箱"}),
        required=True,
        error_messages={
            'required': '郵箱不能爲空',
            'invalid': '郵箱格式錯誤',
        }
    )
    password = forms.RegexField(
        label='密碼',
        # regex='^(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[!@#$\%\^\&\*\(\)])[0-9a-zA-Z!@#$\%\^\&\*\(\)]{8,32}$',
        # regex='^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,32}$',
        regex='^[0-9A-Za-z]{6,32}$',
        min_length=6,
        max_length=32,
        required=True,
        widget=widgets.PasswordInput(attrs={'class': 'form-control', 'placeholder': "請輸入密碼"}),
        error_messages={'required': '密碼不能爲空.',
                        'invalid': '密碼必須包含數字,字母、特殊字符',
                        'min_length': '密碼長度不能小於6個字符',
                        'max_length': '密碼長度不能大於32個字符',
                        }
    )
    confirm_pwd = fields.CharField(
        label='確認密碼',
        widget=widgets.PasswordInput(attrs={'class': 'form-control', 'placeholder': "請再次輸入密碼"}),
        required=True,
        min_length=6,
        max_length=32,
        error_messages={'required': '密碼不能爲空.',
                        'min_length': "密碼長度不能小於6個字符",
                        'max_length': "密碼長度不能大於32個字符"}
    )
    # check_code = fields.CharField(
    #     widget=widgets.TextInput(attrs={'class': 'form-control', 'placeholder': "請輸入驗證碼"}),
    #     required=True,
    #     error_messages={'required': '驗證碼不能爲空.', }
    # )

    def clean_username(self):
        v = self.cleaned_data.get('username')
        if UserInfo.objects.filter(username=v).count():
            raise ValidationError('用戶名已存在')
        else:
            return v

    def clean_email(self):
        v = self.cleaned_data.get('email')
        if UserInfo.objects.filter(email=v).count():
            raise ValidationError('郵箱已存在')
        else:
            return v

    def clean(self):
        v1 = self.cleaned_data.get('password')
        v2 = self.cleaned_data.get('confirm_pwd')
        if v1 == v2:
            pass
        else:
            raise ValidationError('密碼輸入不一致')
相關文章
相關標籤/搜索