nlr25
nlr25

Reputation: 1635

Rendering individual fields in template in a custom form

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"

Upvotes: 17

Views: 39912

Answers (2)

caot
caot

Reputation: 3328

The following code could be helpful to someone. Here is a way to get a rendering field with fieldname from a form:

form.fields[fieldname].get_bound_field(form, fieldname)

Upvotes: 6

augustomen
augustomen

Reputation: 9759

{{ form.fieldname }} will render only the field widget by its name.

Check out Customizing the form template.

Upvotes: 29

Related Questions