[Answered ]-Django: Render a form field as editable text field only once and a readonly there after

1👍

You may try using two htmls, One for create profile and one for editing profile. Render the complete form in create profile and for editing profile if you use same django you may disable the #id_name and #id_domain filed by using either css or javascript. An implementation using js:

    <script type="text/javascript"> 
        var domain = document.getElementById("id_domain");
        var name = document.getElementById("id_name");
        domain.value = "{{ domain }}";
        name.value = "{{ name }}";
        domain.readOnly = true;        
    </script>

1👍

This looks tricky, you can read some of the following for some ideas:

In a Django form, how do I make a field readonly (or disabled) so that it cannot be edited?

http://lazypython.blogspot.com/2008/12/building-read-only-field-in-django.html

None of those are particularly simple though, so I’d suggest (as did @dcrodjer):

Creating two forms, one for creating, one for editing. On the editing form, remove the Domain field so it’s not required/won’t be saved:

# forms.py

class AddForm(ModelForm):
    class Meta:
        model = UserProfile
        fields = ('name','domain',)  

class EditForm(ModelForm):
    class Meta:
        model = UserProfile
        fields = ('name',)  

In your view, creating the appropriate form, and in your template, rendering different HTML depending on which form you’ve been given:

{% if form.domain %}
    {{form.domain.label_tag}}: {{form.domain}} {{form.domain.errors}}
{% else %}
    Domain: <input type="text" disabled="disabled" value="{{userprofile.domain}}"/>
{% endif %}
👤Tom

Leave a comment