表单验证如GenericView

时间:2017-03-08 00:28:49

标签: django django-forms django-class-based-views

使用Generic视图时,您会得到django在模板中发布错误消息的简洁功能,例如"此字段是必需的!"。

根据我的理解,CreateView继承了一个名为form_invalid的方法,该方法返回self.render_to_response(self.get_context_data(form=form))而我只是在猜测是什么做了魔术?

现在我正在撰写表格,并想知道是否可以使用该功能?

我创建了一个custom_user模型,并尝试创建一个简单的创建功能。到目前为止,我已经:

Models.py

class Custom_User(AbstractBaseUser):

    email = models.EmailField(max_length=250, unique=True)
    password = models.CharField(max_length=100)

    USERNAME_FIELD = 'email'

forms.py

class create_User_Form(forms.ModelForm):

    confirm_password = forms.CharField(widget = forms.PasswordInput(attrs={'class' :'form-control'}))

    class Meta:
        model = Custom_User
        fields = ['email', 'password']

        widgets = {
                   'email' : forms.TextInput(attrs={'class' :'form-control'}),
                   'password' : forms.PasswordInput(attrs={'class' :'form-control'}),
        }

    def clean(self):
        cleaned_data = super(create_User_Form, self).clean()
        password = cleaned_data.get("password")
        confirm_password = cleaned_data.get("confirm_password")

        if password != confirm_password:
            raise forms.ValidationError(
                "password and confirm_password does not match"
            )

        return self.cleaned_data

urls.py

urlpatterns = [
            url(r'^$', views.index, name='index'),    

            url(r'^create_user/$', views.create_user, name='create_user'),  
]

views.py

def create_user(request):

    form = create_User_Form(request.POST)

    if form.is_valid():
        print('valid')
    else:
        print('error')        

    return redirect('Eapp:index')

def index(request):

    create_user_form_ = create_User_Form()

    context = {
               'create_user_form' : create_user_form_,
    }

    return render(request, 'index.html', context)

1 个答案:

答案 0 :(得分:2)

您似乎混淆了基于功能的视图和基于类的视图。您尝试的是功能基础视图。要完成它需要看起来像这样

def create_user(request):
    if request.method == 'POST':
        create_user_form_ = create_User_Form(request.POST)
        if form.is_valid():
            print('valid')
            return redirect('Eapp:index')
        else:
            print('error')        

    else:
        create_user_form_ = create_User_Form()

    context = {
               'create_user_form' : create_user_form_,
    }

    return render(request, 'index.html', context)

请注意,这会结合您的索引和创建用户方法,因为它们包含需要一起使用的功能。

另一方面,如果你想使用CreateView,你的代码会变得更短

class UserCreate(CreateView):
    model = Custom_User
    form_class = create_User_Form

真的。但是你可以添加改进。

作为旁注。在python中命名类的标准方法是 CreateUserForm