简体   繁体   中英

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

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)

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

before setting it as read-only

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM