11

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

Asif
  • 1,775
  • 4
  • 25
  • 39

4 Answers4

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
  • 6,511
  • 2
  • 39
  • 56
  • My question is how i can make only queryset forms to readonly not extra forms. Your solution will convert all the form fields as readonly including extra fields also. Here how can i make extra form fields as non readonly and other should be readonly – Asif Jul 03 '12 at 15:07
  • check out the if statement in my edited answer. I'm not sure if it's the cleanest way of checking if the form has an instance associated with it, but it's working in my testing. – j_syk Jul 03 '12 at 15:14
  • I changed it again just now from `if 'id' in self.intitial` to `if self.instance.id` That really should be the proper way to check if the form has an instance – j_syk Jul 03 '12 at 15:18
  • But i observed this will affect jquery plugin which I'm using to add form dynamically – Asif Jul 03 '12 at 15:24
  • then you need to modify the script to look for any readonly attributes and remove them when copying the form. Also, with 'extra', the last 2 forms should not have an instance with an id, so if you copy one of them you should be ok. can you post your clone form script? – j_syk Jul 03 '12 at 15:26
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
  • 11
  • 1
0

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

before setting it as read-only

-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);
Community
  • 1
  • 1
stackex
  • 299
  • 1
  • 3
  • 7