[Solved]-Readonly fields in django formset

15๐Ÿ‘

โœ…

Iโ€™d recommend specifying a form to use for the model, and in that form you can set whatever attributes you want to read only.

#forms.py
class AuthorForm(forms.ModelForm):
    class Meta:
        model = Author

    def __init__(self, *args, **kwargs):
        super(AuthorForm, self).__init__(*args, **kwargs)
        if self.instance.id:
            self.fields['weight'].widget.attrs['readonly'] = True

#views.py
AuthorFormSet = modelformset_factory(Author, extra=2, form=AuthorForm)
๐Ÿ‘คj_syk

1๐Ÿ‘

You can also put in your template :

{{form.management_form}}
{% for i in form %}
<p>{{ i.instance.readonly_field }}</p>
{{i.as_p}}
{% endfor %}

and not put the readonly_field in ModelForm.Meta.fields.

๐Ÿ‘คmy_pseudo

0๐Ÿ‘

just need to check if the instance has id, like this:
if self.instance.id

before setting it as read-only

๐Ÿ‘คCauane Andrade

-2๐Ÿ‘

I used python long back. Hope this helps . But if you wish to control fields display using jquery

$('.class').attr('readonly', true);

or

$('#id').attr('readonly', true);
๐Ÿ‘คstackex

Leave a comment