Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Readonly fields in django formset

I'm using modelformset factory to generate formset from model fields. Here i want to make only the queryset objects as readonly and other (extra forms) as non readonly fields

How can i achieve this?

  AuthotFormSet = modelformset_factory(Author, extra=2,)
  formset = AuthorFormSet(queryset=Author.objects.all())

In Above formset i wanted to display all the queryset objects as readonly, and remaining extra forms as non readonly fields. How can i achive this?

if i used,

      for form in formset.forms:
          form.fields['weight'].widget.attrs['readonly'] = True

This will convert all the forms (including extra) fields to readonly which i dont want. And also i'm using jquery plugin to add form dynamically to the formset

like image 856
Asif Avatar asked Jul 03 '12 14:07

Asif


1 Answers

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)
like image 58
j_syk Avatar answered Sep 19 '22 11:09

j_syk