[英]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
而且我正在使用 jquery 插件将表单动态添加到表单集
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:只需要检查实例是否有 id,就像这样:
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.而不是将 readonly_field 放在 ModelForm.Meta.fields 中。
I used python long back.我很久以前使用过python。 Hope this helps .
希望这会有所帮助。 But if you wish to control fields display using jquery
但是如果您希望使用 jquery 控制字段显示
$('.class').attr('readonly', true);
or或者
$('#id').attr('readonly', true);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.