Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"
like image 587
nlr25 Avatar asked Sep 05 '13 16:09

nlr25


People also ask

What is formset in django?

A formset is a layer of abstraction to work with multiple forms on the same page. It can be best compared to a data grid. Let's say you have the following form: >>> from django import forms >>> class ArticleForm(forms.

What is get and post method in django?

GET and POSTDjango's login form is returned using the POST method, in which the browser bundles up the form data, encodes it for transmission, sends it to the server, and then receives back its response. GET , by contrast, bundles the submitted data into a string, and uses this to compose a URL.


2 Answers

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

Check out Customizing the form template.

like image 181
augustomen Avatar answered Sep 28 '22 01:09

augustomen


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)
like image 20
caot Avatar answered Sep 28 '22 02:09

caot