本文實例為大家分享了Django實現表單驗證的具體代碼,供大家參考,具體內容如下
models.py
class Users(models.Model): nickname = models.CharField(max_length=16, null=False, blank=False, unique=True) email = models.EmailField(max_length=32, null=False, blank=False, unique=True) password = models.CharField(max_length=64, null=False, blank=False) head = models.ImageField(default="decault.png") age = models.CharField(max_length=3,blank=True,null=True) sex = models.CharField(max_length=2, blank=True, null=True) isactivate = models.BooleanField(default=False) def save(self): if not self.password.startswith('pbkdf2_'): self.password = make_password(self.password) super().save()
form.py
from django import formsfrom django.core.exceptions import ValidationErrorfrom user.models import Users#定義驗證器def nickname_validate(nickname): u = Users.objects.filter(nickname=nickname) if len(u): print(len(u)) raise ValidationError('用戶名已存在')#定義表單class RegisterForm(forms.Form): nickname = forms.CharField(validators=[nickname_validate], label='用戶名', max_length=16, min_length=4, required=True, widget= forms.TextInput(), ) password = forms.CharField(label='密碼', max_length=64, min_length=6, required=True, widget=forms.PasswordInput()) email = forms.EmailField(label='郵箱', max_length=32, required=True) age = forms.CharField(label='年齡', max_length=3, required=False) sex = forms.ChoiceField(label='性別', choices = ((0,'男'),(1,'女'),), required=False)
view.py
from user.forms import RegisterFormfrom user.models import Usersdef register(request): if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid(): u = Users() u.nickname = form.cleaned_data['nickname'] u.email = form.cleaned_data['email'] u.password = form.cleaned_data['password'] u.age = form.cleaned_data['age'] u.sex = form.cleaned_data['sex'] u.save() return render(request,'user_info.html') else: return render(request, 'register.html',context={'form':form,'errors': form.errors}) else: form = RegisterForm() return render(request,'register.html',context={'form':form})
register.html
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>注冊</title></head><body> <form class="form" action="{% url 'user:register' %}" method="post"> {% csrf_token %} <table> {{ form.as_p }} </table> <button type="submit" class="btn btn-primary btn-block">注冊 </button> <input type="hidden" name="next" value="{{ next }}"/> </form></body></html>
新聞熱點
疑難解答