覆盖基于Django通用类的视图小部件 [英] Override a Django generic class-based view widget

查看:81
本文介绍了覆盖基于Django通用类的视图小部件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个基本的CreateView表单,允许新用户在网站上注册:

 来自django .contrib.auth从django导入get_user_model 
.http从django.views.generic导入HttpResponse
CreateView

User = get_user_model()


类Signup(CreateView):

模型=用户
字段= ['first_name','last_name','email','password']
解决方案

您可以覆盖 get_form(),然后修改表单以更改密码字段上的小部件:

 从Django导入表单

类Signup(CreateView):
模型=用户
字段= ['first_name','last_name' ,电子邮件,密码]

def get_form(self,form_class):
form = super(Signup,self).get_form(form_class)
form.fields [ 'password']。widget = form.PasswordInput()
返回表格

但是偶数更好的方法是只创建一个自定义表单类。在自定义类中,只需在 Meta 类上设置 widgets 。像这样:

 从Django导入表单

类SignupForm(forms.ModelForm):
类Meta:
模型=用户
字段= ['first_name','last_name','email','password']
小部件= {
'password':表格.PasswordInput()
}

class Signup(CreateView):
form_class = SignupForm
模型=用户

通常,您还将自定义表单类也放在forms.py文件中。


Say I have a basic CreateView form, like this, to allow new users to register on a site:

from django.contrib.auth import get_user_model
from django.http import HttpResponse
from django.views.generic import CreateView

User = get_user_model()


class Signup(CreateView):

    model = User
    fields = ['first_name', 'last_name', 'email', 'password']

I just tried this, and found that the password field is rendered in plain text; how would I go about overriding the view so that it uses forms.PasswordInput() instead? (I realise it's probably easiest to just define the form by hand, but I'm just curious about how you'd do that.)

解决方案

You could override get_form(), and modify the form to change the widget on the password field:

from django import forms

class Signup(CreateView):
    model = User
    fields = ['first_name', 'last_name', 'email', 'password']

    def get_form(self, form_class):
        form = super(Signup, self).get_form(form_class)
        form.fields['password'].widget = forms.PasswordInput()
        return form

But an even better way would be to just create a custom form class. In the custom class just set widgets on the Meta class. Like this:

from django import forms

class SignupForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ['first_name', 'last_name', 'email', 'password']
        widgets = {
            'password': forms.PasswordInput()
        }

class Signup(CreateView):
    form_class = SignupForm
    model = User

Usually you would put the custom form class in a forms.py file as well.

这篇关于覆盖基于Django通用类的视图小部件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆