註冊的form

# 註冊的form
class RegForm(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput, label='密碼', min_length=6)  # 重寫默認字段
    re_password = forms.CharField(widget=forms.PasswordInput, label='確認密碼', min_length=6)  # 新增字段

    class Meta:
        model = models.UserProfile  # 指定model
        fields = '__all__'  # ['username','password']  # 指定字段
        exclude = ['is_active']

        labels = {
            'username': '用戶名'
        }

        widgets = {
            'username': forms.TextInput(attrs={'class': 'form-control', 'placeholder': '用戶名'}),
            # 'password': forms.PasswordInput(attrs={'class': 'form-control'})

        }
        error_messages = {

            'min_length': '不能少於6位'
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 自定義操做
        for field in self.fields.values():
            # field.widget.attrs['class'] = 'form-control'
            field.widget.attrs.update({'class': 'form-control'})

    def clean(self):
        pwd = self.cleaned_data.get('password', '')
        re_pwd = self.cleaned_data.get('re_password', '')

        if pwd == re_pwd:
            # 密碼加密
            md5 = hashlib.md5()
            md5.update(pwd.encode('utf-8'))
            pwd = md5.hexdigest()

            self.cleaned_data['password'] = pwd
            return self.cleaned_data
        # 兩次密碼不一致
        self.add_error('re_password', '兩次密碼不一致!!')
        raise ValidationError('兩次密碼不一致')
相關文章
相關標籤/搜索