仅在 UpdateView 中禁用 Django 表单字段
Disable Django Form Field only in UpdateView
我在forms.py中有一个UserForm
,它在Register
和Edit Profile
特征之间很常见,它的视图也很常见,因为90%的功能都是相似的在两个视图中。
我想 disable
来自 UserForm
的 EMailField
仅在 Edit Profile
页面中,但应该可以在 Register
页面中编辑。这是我的代码:
forms.py
class UserForm(forms.ModelForm):
password = None
email = forms.EmailField(required=False, disabled=True) #-- This will disable all the times
salutation = forms.ChoiceField(choices=Choices.SALUTATIONS)
blood_group = forms.ChoiceField(choices=Choices.BLOOD_GROUPS)
class Meta:
model = User
fields = ('salutation', 'blood_group', 'email', 'first_name', 'middle_name', 'last_name',
'gender', 'birth_date', 'profile')
同一表单在 register
和 edit
视图中同时呈现。这是我的 urls.py.
path('register/', StudentView.as_view(), name='addview'),
path('<int:pk>/edit/', StudentView.as_view(), name='editview'),
中views.py(详细views.py,查看)
userform = UserForm(request.POST or None, instance=self.object)
admission.html
<form class="form" name="admissionForm" id="admissionForm" method="post"
enctype="multipart/form-data" action="{% url 'editview' form.instance.id %}">
{% csrf_token %}
<div class="pages">
<h4 class="mt-2 mb-3">Personal Information</h4>
{% include "student_errors.html" %}
{{userform|crispy}}
....
<div class="btn_container">
<button type="submit" class="btn btn-info float-right btn-next">Submit</button>
</div>
</div>
在您的update_views中您可以设置:
form.fields['email'].disabled = True
我在forms.py中有一个UserForm
,它在Register
和Edit Profile
特征之间很常见,它的视图也很常见,因为90%的功能都是相似的在两个视图中。
我想 disable
来自 UserForm
的 EMailField
仅在 Edit Profile
页面中,但应该可以在 Register
页面中编辑。这是我的代码:
forms.py
class UserForm(forms.ModelForm):
password = None
email = forms.EmailField(required=False, disabled=True) #-- This will disable all the times
salutation = forms.ChoiceField(choices=Choices.SALUTATIONS)
blood_group = forms.ChoiceField(choices=Choices.BLOOD_GROUPS)
class Meta:
model = User
fields = ('salutation', 'blood_group', 'email', 'first_name', 'middle_name', 'last_name',
'gender', 'birth_date', 'profile')
同一表单在 register
和 edit
视图中同时呈现。这是我的 urls.py.
path('register/', StudentView.as_view(), name='addview'),
path('<int:pk>/edit/', StudentView.as_view(), name='editview'),
中views.py(详细views.py,查看
userform = UserForm(request.POST or None, instance=self.object)
admission.html
<form class="form" name="admissionForm" id="admissionForm" method="post"
enctype="multipart/form-data" action="{% url 'editview' form.instance.id %}">
{% csrf_token %}
<div class="pages">
<h4 class="mt-2 mb-3">Personal Information</h4>
{% include "student_errors.html" %}
{{userform|crispy}}
....
<div class="btn_container">
<button type="submit" class="btn btn-info float-right btn-next">Submit</button>
</div>
</div>
在您的update_views中您可以设置:
form.fields['email'].disabled = True