问题描述
我正在使用modelformset factory从模型字段中生成formset。在这里,我只想将查询对象作为只读方式和其他(额外的形式)作为非readonly字段
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
我如何实现?
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?
如果我使用,
for form in formset.forms:
form.fields['weight'].widget.attrs['readonly'] = True
这将把所有的表单(包括额外的)字段转换为只读,我不想要的。
我也使用jquery插件将形式动态地添加到formset
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)
这篇关于在django formset中只读字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!