简体   繁体   English

使用modelformset_factory和访问对象的属性

[英]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. 我有一些Container ,它们有许多Box我想编辑。 So, naturally, I use modelformset_factory . 因此,自然地,我使用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. 在我的模板中,我遍历formset以显示要修改的框。

This works very well and I can edit the attributes a , b and c of each Box . 这很好用,我可以编辑每个Box的属性abc But each box has also a label . 但是每个盒子上也有一个label I want to access the value to show it in the label but it should not be editable, like an input -field. 我想访问该值以在标签中显示它,但它不应像input -field一样可编辑。 I just need the value. 我只需要价值。 How can I achieve that? 我该如何实现?

You can pass a widgets parameter to the factory. 您可以将widgets参数传递给工厂。 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 一种替代方法是使用javascript将这些字段设置为只读

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

Personally, I would prefer the first 就个人而言,我希望第一个

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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