Django UpdateView disable some fields

南笙酒味 提交于 2020-11-27 04:04:38

问题


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/'

回答1:


To hide it:

class UserUpdate(UpdateView):
    model = Users
    fields = ['first_name', 'last_name', 'birth_date']
    template_name = 'users_update_form.html'

In this case there is no need to create a separate Form class - as this is handled by the UpdateView.

To make the fiel readonly:

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

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)



回答2:


Define a UserForm with exclude fields which you don't want to show in the form

class UserForm(forms.ModelForm):
    class Meta:
        model = Users
        exclude = ('email',) # add fields to disable it in the form

If you want to make field readonly in > django 1.9 use disabled

class UserForm(forms.ModelForm):
    email =  forms.CharField(disabled=True)
    class Meta:
        model = Users
        fields = ['email', 'first_name', 'last_name', 'birth_date']

Then specify form in view.

class UserUpdate(UpdateView):
    model = Users
    form_class = UserForm
    ....


来源:https://stackoverflow.com/questions/37959866/django-updateview-disable-some-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!