tjati
tjati

Reputation: 6079

Using modelformset_factory and access attributes of an object

I have some Containers and they have a number of Boxes 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?

Upvotes: 0

Views: 1039

Answers (2)

user2390182
user2390182

Reputation: 73460

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 %}

Upvotes: 1

Resley Rodrigues
Resley Rodrigues

Reputation: 2288

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

Upvotes: 0

Related Questions