我有一个modelform_factory,它非常适合我需要的东西。
我称之为:
dep_formset = modelformset_factory( Dependent, fields=('has_medical', 'med_group_id'), max_num = dep_count )正如您可能猜到的,Dependent有其他字段,我只想用于显示目的(分别是first_name和last_name )我想显示依赖人的first_name和last_name - 但它只是用于显示,而不是编辑。
如果我将'first_name'和'last_name'添加到上面的字段中,我可以在我的模板中访问它们 - 但是表单对.is_valid()失败了,因为我只是将它们显示为文本而不是输入,所以他们没有被POST
是否有一些聪明的方法来访问依赖对象的first_name和last_name而不将它们添加到formset_factory的字段?
模板看起来像这样(部分片段,因此您可以看到我正在尝试使用first_name,last_name):
{% for form in dep_formset %} {{ form.id }} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} <div class="g"> <h4>{{ form.first_name.value }} {{form.last_name.value}}</h4> </div> <div class="g dependent-option"> <div class="g-1-4 dependent-option-check"> {% if form.has_medical %}I've got a modelform_factory which works perfect for what I need.
I call it like this:
dep_formset = modelformset_factory( Dependent, fields=('has_medical', 'med_group_id'), max_num = dep_count )As you might guess, Dependent has additional fields that I want to use simply for display purposes (first_name and last_name respectively) I want to show the first_name and last_name of the dependent person - but have it be simply for display, not edit.
If I add 'first_name' and 'last_name' to the fields in the above, I can then access them in my template - but the form fails against .is_valid() because I'm displaying them simply as text and not as an input, so they're not being POST'ed
Is there some clever way to get access to the first_name and last_name of the dependent objects without adding them to fields for the formset_factory?
The template looks like this (partial snippet so you can see what I'm trying to do with the first_name, last_name):
{% for form in dep_formset %} {{ form.id }} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} <div class="g"> <h4>{{ form.first_name.value }} {{form.last_name.value}}</h4> </div> <div class="g dependent-option"> <div class="g-1-4 dependent-option-check"> {% if form.has_medical %}最满意答案
根据提供的信息,它看起来像formset绑定到您可以在模板中访问的实例:
{{ form.instance.first_name }}Based on provided information it looks like the formset is tied to an instance which you can access in template:
{{ form.instance.first_name }}更多推荐
发布评论