16

I am having trouble rendering individual fields in my template. I have a custom form that renders a multichoice widget and Charfield. I want to render the widget and Charfield individually, so I can place the Charfield on the right of the widget rather than on the bottom (which is what Django does by default). Is there a way to call individual fields in my form in the template?

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"
4

2 回答 2

27

{{ form.fieldname }}将仅按其名称呈现字段小部件。

查看自定义表单模板

于 2013-09-05T17:32:27.170 回答
4

以下代码可能对某人有所帮助。这是一种fieldname从 a获取渲染字段的方法form

form.fields[fieldname].get_bound_field(form, fieldname)
于 2019-05-10T17:11:52.150 回答