简体   繁体   中英

Using modelformset_factory and access attributes of an object

I have some Container s and they have a number of Box es I want to edit. So, naturally, I use modelformset_factory .

It works very good:

container = get_object_or_404(Container, id=container_id)
BoxFormSet = modelformset_factory(Box, fields=('a', 'b', 'c'))
formset = BoxFormSet(queryset=container.box_set.all())

In my template I iterate over formset to show the boxes I want to modify.

This works very well and I can edit the attributes a , b and c of each Box . But each box has also a label . I want to access the value to show it in the label but it should not be editable, like an input -field. I just need the value. How can I achieve that?

You can pass a widgets parameter to the factory. There you can specify the appropriate attribute for the label input:

BoxFormSet = modelformset_factory(
    Box, 
    fields=('a', 'b', 'c', 'label'),
    widgets={'label': forms.TextInput(attrs={'readonly': True})}
)

Alternatively, if you don't want a auto-rendered, yet disabled input, you can just access the label in the template via the form's instance:

{% for form in box_formset %}
    # form stuff
    {{ form.instance.label }}
{% endfor %}

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 BoxForm(forms.ModelForm):
    class Meta:
        model = Box
        fields=('a', 'b', 'c', 'label')

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

#views.py
BoxFormSet = modelformset_factory(Box, form=BoxForm)

An alternative would be to set those fields as read-only using javascript

$('input[name="label"]').attr('readonly', true);

Personally, I would prefer the first

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