Django UpdateView 禁用某些字段 [英] Django UpdateView disable some fields
本文介绍了Django UpdateView 禁用某些字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我创建了一个继承 UpdateView 的类视图.我已经指定了构建表单的字段和模型.现在说如果我有一个字段电子邮件,那么我想在表单中禁用它.我不知道如何做到这一点.
I have made a class view inheriting UpdateView. I have specified the fields and models from which the forms should be built. Now say if i have a field email, then I want to disable it in the form. I have no clues as to how it can be done.
class UserUpdate(UpdateView):
model = Users
fields = ['email', 'first_name', 'last_name', 'birth_date']
template_name = 'users_update_form.html'
success_url = '/index/'
推荐答案
要隐藏:
class UserUpdate(UpdateView):
model = Users
fields = ['first_name', 'last_name', 'birth_date']
template_name = 'users_update_form.html'
在这种情况下,无需创建单独的 Form
类 - 因为这是由 UpdateView
处理的.
In this case there is no need to create a separate Form
class - as this is handled by the UpdateView
.
使字段只读:
class UserForm(forms.ModelForm):
class Meta:
model = Users
fields = ['email', 'first_name', 'last_name', 'birth_date']
email = forms.CharField(widget=forms.TextInput(attrs={'readonly':'readonly'}))
def clean_email(self):
return self.initial['email']
class UserUpdate(UpdateView):
model = Users
form_class = UserForm
Django 1.9 的注意事项
Django 1.9 内置了 禁用 选项.使用它可以让你跳过额外的 clean
方法.
Note for Django 1.9
Django 1.9 has a disabled option built in. Using this allows you to skip the additional clean
method.
class UserForm(forms.ModelForm):
class Meta:
model = Users
fields = ['email', 'first_name', 'last_name', 'birth_date']
email = forms.CharField(disabled=True)
这篇关于Django UpdateView 禁用某些字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文