我在模板中渲染单个字段时遇到问题。我有一个自定义表单,呈现多重小部件和Charfield。我想单独渲染小部件和Charfield,所以我可以将Charfield放在小部件的右边而不是底部(这是Django默认做的)。有没有办法在模板中调用表单中的各个字段?
forms.py
class UpdateStateOptionWithOutcomesForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
disease=kwargs.pop('disease', None)
super(UpdateStateOptionWithOutcomesForm, self).__init__(*args, **kwargs)
self.fields['relevantoutcome']=forms.ModelMultipleChoiceField(queryset=Outcome.objects.filter(relevantdisease_id=disease),required=True, widget=forms.CheckboxSelectMultiple)
self.fields['relevantoutcome'].label="Treatment Outcomes"
outcome_qs=Outcome.objects.filter(relevantdisease_id=disease)
for outcome in outcome_qs:
self.fields['outcomevalue_%s' % outcome.pk] = forms.CharField(required=False)
self.fields['outcomevalue_%s' % outcome.pk].label = "Outcome Value"
答案 0 :(得分:22)
{{ form.fieldname }}
将仅按名称呈现字段小部件。
答案 1 :(得分:1)
以下代码可能对某人有所帮助。这是从fieldname
中使用form
获取渲染字段的一种方法:
form.fields[fieldname].get_bound_field(form, fieldname)