4
Because it seems you are using django-crispy-forms, I would use the following:
class UserForm(forms.ModelForm):
password = forms.CharField(label='Password', widget=forms.PasswordInput)
password2 = forms.CharField(label='Repeat password', widget=forms.PasswordInput)
def __init__(self,disable_fields=False, *args, **kwargs):
super().__init__(*args, **kwargs)
if disable_fields:
self.fields['password'].disabled = True
self.fields['password2'].disabled = True
class Meta:
model = User
fields = ('username', 'first_name', 'last_name', 'email')
So when you are going to create the form, this should make it work:
@login_required
def profile(request):
user_form = UserForm(instance=request.user, disable=True)
return render(request, 'rentadevapp/profile.html', {'user_form': user_form})
2
Django 1.9 added the Field.disabled
attribute: https://docs.djangoproject.com/en/stable/ref/forms/fields/#disabled
The disabled boolean argument, when set to True, disables a form field using the disabled HTML attribute so that it won’t be editable by users. Even if a user tampers with the field’s value submitted to the server, it will be ignored in favor of the value from the form’s initial data.
You can do this to disable the fields you want in your view:
@login_required
def profile(request):
user_form = UserForm(instance=request.user)
for fieldname in user_form.fields:
user_form.fields[fieldname].disabled = True
return render(request, 'rentadevapp/profile.html', {'user_form': user_form})
Source:stackexchange.com