I have a UserForm
in forms.py which is common between Register
and Edit Profile
features, its Views are also common, as 90% of the functionalities are similar in both the views.
I want to disable
the EMailField
from UserForm
only in Edit Profile
page but should be editable in Register
page. Here is my code:
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')
Same Form is being rendered both the times in register
and edit
views. Here are my urls.py.
path('register/', StudentView.as_view(), name='addview'),
path('<int:pk>/edit/', StudentView.as_view(), name='editview'),
in the views.py (For detailed views.py, check the accepted answer)
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>
In your update_views you can set:
form.fields['email'].disabled = True