Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Syntax for Disabling all form fields in Django [duplicate]

I'm trying to display a user's profile on a project. I'd like to render a form but make it disabled/unable to be changed (just displayed). I can't figure out the syntax for it. Help would be appreciated!

Here's the view.py:

@login_required
def profile(request):
    user_form = UserForm(instance=request.user)
    user_form.fields.disabled = True <------- HELP HERE
    return render(request, 'rentadevapp/profile.html', {'user_form': user_form})

I essentially want to just display a readonly/disabled form. User then has an edit button that takes them to a profile edit page.

Thanks for the help!

Here's the html just in case:

 <form method="GET" action="/profile_edit">{% csrf_token %}
                {{ user_form|crispy }}
                <button type="submit" class="edit btn btn-default btn-block btn-lg">Edit</button><br>
            </form>

Forms.py

class UserForm(forms.ModelForm):

    password = forms.CharField(label='Password', widget=forms.PasswordInput)
    password2 = forms.CharField(label='Repeat password', widget=forms.PasswordInput)

    class Meta:
        model = User
        fields = ('username', 'first_name', 'last_name', 'email')
like image 520
James Franco Avatar asked Oct 15 '25 07:10

James Franco


1 Answers

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})
like image 124
lmiguelvargasf Avatar answered Oct 17 '25 20:10

lmiguelvargasf