Django验证错误未显示在表单上

时间:2019-07-16 09:23:34

标签: django python-3.x validation django-forms django-views

我要检查用户注册。

如果用户名已经注册,请给用户一个验证错误。

在我的终端环境中,还会打印data_user词典 但是在我的表单注册中,用户名验证错误不适用于help.html 这是相同的表格。 ---> https://imgur.com/a/osAv0xn

models.py

JsonBatchCallback<PagespeedApiPagespeedResponseV5> callback = new JsonBatchCallback<PagespeedApiPagespeedResponseV5>() {

    public void onSuccess(PagespeedApiPagespeedResponseV5 response, HttpHeaders responseHeaders) {
        //ON SUCCESS
    }
    public void onFailure(GoogleJsonError e, HttpHeaders responseHeaders) {
        //ON FAILURE
    }
};

views.py

from django.db import models

class SignUpModel(models.Model):
    name = models.CharField(max_length=20,null=True)
    family = models.CharField(max_length=30,null=True)
    username = models.CharField(max_length=10)
    email = models.EmailField(null=True,unique=True)
    password = models.CharField(max_length=20,null=True)

# Create your models here.
class LoginModel(models.Model):
    username = models.CharField(max_length=15)
    password = models.CharField(max_length=20)

forms.py

from django.shortcuts import render
from .forms import *
from django.contrib.admin.views.decorators import staff_member_required

@staff_member_required()
def blogPostSignUpView(request):

    form = BlogPostSignUpModelForm(request.POST or None)
    if form.is_valid():
        form.save()
        print(form.cleaned_data)
        form = BlogPostSignUpModelForm()
    template_name = "help.html"
    context = {"title":"register","form":form}
    return render(request,template_name,context)
@staff_member_required
def blogPostLoginView(request):
    form = BlogPostLoginModelForm(request.POST or None)
    if form.is_valid():
        obj = form.save(commit=False)
        obj.save()

    template_name = 'help.html'
    context = {"title":"login","form":form}
    return render(request,template_name , context)

urls.py

from django import forms
from .models import SignUpModel,LoginModel

#Sign UP Form
class BlogPostSignUpForm(forms.Form):
    name = forms.CharField()
    family = forms.CharField()
    username = forms.CharField()
    email = forms.CharField(widget=forms.EmailField)
    password = forms.CharField()

class BlogPostSignUpModelForm(forms.ModelForm):
    class Meta:
        model = SignUpModel
        fields = ['name','family','username','email' , 'password']
    def check_password(self, *args, **kwargs):
        uname = self.cleaned_data.get('username')
        data_user = SignUpModel.objects.filter(username=uname)
        print(data_user)
        if data_user:
            if uname == data_user['username']:
                raise forms.ValidationError("This user has exist !!!")
        return uname


#Login Form
class BlogPostLoginForm(forms.Form):
    username = forms.CharField()
    password = forms.CharField()

class BlogPostLoginModelForm(forms.ModelForm):
    class Meta:
        model = LoginModel
        fields = ['username','password']

help.html

from django.urls import path
from .views import (
blogPostSignUpView,
blogPostLoginView
)
urlpatterns = [
    path('signup/',blogPostSignUpView),
    path('login/',blogPostLoginView),
    ]

我想念什么?

1 个答案:

答案 0 :(得分:0)

在Django表单和字段验证中,在表单子类上调用clean_<fieldname>()方法-在其中用表单字段属性的名称替换,因此

我们不应在BlogPostSignUpModelForm类中使用任何喜欢的方法的名称。

替换此项目后,项目将运行:)

因此,应该相应地更改代码。

更改表格。py

from django import forms
from .models import SignUpModel,LoginModel

#Sign UP Form
class BlogPostSignUpForm(forms.Form):
    name = forms.CharField()
    family = forms.CharField()
    username = forms.CharField()
    email = forms.CharField(widget=forms.EmailField)
    password = forms.CharField()

class BlogPostSignUpModelForm(forms.ModelForm):
    class Meta:
        model = SignUpModel
        fields = ['name','family','username','email' , 'password']
    def clean_username(self, *args, **kwargs):
        uname = self.cleaned_data.get('username')
        data_user = SignUpModel.objects.filter(username=uname)
        print(data_user)
        if data_user:
            raise forms.ValidationError("username or email has been exist !!!")
        return uname

#Login Form
class BlogPostLoginForm(forms.Form):
    username = forms.CharField()
    password = forms.CharField()

class BlogPostLoginModelForm(forms.ModelForm):
    class Meta:
        model = LoginModel
        fields = ['username','password']