簡體   English   中英

如何對我的字段進行表單和字段驗證?

[英]How can i give form and field validation to my fields?

如果用戶嘗試注冊或登錄,我想添加一些驗證,他必須經過一些限制。 請幫助我,因為我是 django models.py 的新手

class RegisterData(models.Model):
    first_name = models.CharField(max_length=20)
    last_name = models.CharField(max_length=20)
    GENDER_CHOICE =(
        ('Male','Male'),
        ('Female', 'Female')
    )
    gender = models.CharField(max_length=10, choices=GENDER_CHOICE)
    username = models.CharField(max_length=20)
    password1 = models.CharField(max_length=20)
    password2 = models.CharField(max_length=20)
    email = models.EmailField(max_length=40)
    mobile = models.BigIntegerField()
    dob = models.DateField()

表格.py

我曾經寫過這樣的表單而不是模型表單。 如果有人嘗試注冊,那么他必須遵守一些規則,例如密碼字符和長度,用戶名應該是這樣的。

報名表格

class RegisterForm(forms.Form):
first_name =  forms.CharField(
    label='First name ',
    widget=forms.TextInput(
        attrs={
            'class':'form-control',
            'placeholder':'Enter your first name'
        }
    )
)

last_name = forms.CharField(
    label='Last name ',
    widget=forms.TextInput(
        attrs={
            'class': 'form-control',
            'placeholder': 'Enter your last name'
        }
    )
)

GENDER_CHOICE = (
    ('male', 'Male'),
    ('female', 'Female')
)

gender = forms.ChoiceField(
    widget=forms.RadioSelect(),
    choices=GENDER_CHOICE
)

username = forms.CharField(
    label='User name ',
    widget=forms.TextInput(
        attrs={
            'class':'form-control',
            'placeholder':'Enter your user name'
        }
    )
)
password1 = forms.CharField(
    label='Password ',
    widget=forms.PasswordInput(
        attrs={
            'class':'form-control',
            'placeholder':'Enter your password'
        }
    )
)
password2 = forms.CharField(
    label='Password',
    widget=forms.PasswordInput(
        attrs={
            'class':'form-control',
            'placeholder':'Re-enter your password'
        }
    )
)

email = forms.EmailField(
    label='Email-id',
    widget=forms.EmailInput(
        attrs={
            'class':'form-control',
            'placeholder':'Enter your email id'
        }
    )
)
mobile = forms.IntegerField(
    label='Mobile ',
    widget=forms.NumberInput(
        attrs={
            'class':'form-control',
            'placeholder':'Enter your mobile number'
        }
    )
)
dob = forms.CharField(
    label='DOB ',
    widget=forms.DateInput(
        attrs={
            'class':'form-control',
            'placeholder':'Enter your date of birth'
        }
    )
)

登錄表格

class LoginForm(forms.Form):
    username = forms.CharField(
        label='User name ',
        widget=forms.TextInput(
            attrs={
                'class': 'form-control',
                'placeholder': 'Enter your user name'
            }
        )
    )
    password1 = forms.CharField(
        label='Password ',
        widget=forms.PasswordInput(
            attrs={
                'class': 'form-control',
                'placeholder': 'Enter your password'
            }
        )
    )

視圖.py

def regview(request):
if request.method == 'POST':
    rform = RegisterForm(request.POST)
    if rform.is_valid():
        first_name = request.POST.get('first_name','')
        last_name = request.POST.get('last_name', '')
        gender = rform.cleaned_data.get('gender', '')
        username = request.POST.get('username', '')
        password1 = request.POST.get('password1', '')
        password2 = request.POST.get('password2', '')
        email = request.POST.get('email', '')
        mobile = request.POST.get('mobile', '')
        dob = rform.cleaned_data.get('dob', '')

        data = RegisterData(
            first_name=first_name,
            last_name=last_name,
            gender=gender,
            username=username,
            password1=password1,
            password2=password2,
            email=email,
            mobile=mobile,
            dob=dob
        )
        data.save()
        rform = RegisterForm()
        lform = LoginForm()
        return render(request, 'reg.html', {'rform':rform, 'lform': lform})

    if request.method == 'POST':
        lform = LoginForm(request.POST)
        if lform.is_valid():
            username = request.POST.get('username','')
            password1 = request.POST.get('password1','')
            user = RegisterData.objects.filter(username=username)
            pwd = RegisterData.objects.filter(password1=password1)

            if user and pwd:
                return redirect('/ask')
            else:
                return HttpResponse('Invalid credentials')
    # lform = LoginForm()
    # return render(request,'reg.html',{'lform':lform})
else:
    rform = RegisterForm()
    lform = LoginForm()
    return render(request,'reg.html',{'rform':rform ,'lform':lform})
# you can use clean function in your forms.py class

For Example

def clean(self):
    cleaned_data = super().clean()
    username = cleaned_data.get("username")
    password = cleaned_data.get("password")

    if len(username)<=8:
        raise forms.ValidationError(
            "Username field length should be more than 8 characters"
        )

    return cleaned_data

如果您想使用 Django 密碼驗證中的默認用戶表單,則另一種選擇:

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
        'OPTIONS': {
            'min_length': 8,
        }
    },
]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM