Django ModelForm: accessing a field value in a view template

Q: Is it possible to pull out the value for one of the ModelForm fields in the template? If so, how?

Background: I have a search form that I use to allow users to filter query results. And the result table along with the form can be exported to an Excel sheet. When a page is displayed with new results, the input values ​​of the search form are still saved. However, they are also still contained in the field object for each form input field. Thus, during export to Excel, search form values ​​are not captured because the value is not in the table’s own cell. So, I want to add a column after a field column that contains the field value (but does not display this column).

I could parse the HTML string for the field and grab all the value attributes, but I would only do this as a last resort. So far, I have managed to access the data dictionary of my form and get the object depending on which field I want, but I did not understand which method I can use to actually capture the field value.

+4
source share
3 answers

Since you are trying to get this data from a completed form, I think the easiest way is to pass the .cleaned_data forms to the template and use this. Let's say you have a form with the name and specialty fields, it will look something like this:

 def my_view(request): form = my_form(request.GET) if form.is_valid(): ... do search stuff ... search_query = form.cleaned_data return render_to_response('my_template.html', {'search_query': search_query, 'search_results': ...,}, ...) 

Then in your template, you simply pull out the desired values:

 <tr> <th>Name</th> <th>Specialty</td> </tr> <tr> <td>{{ search_query.name }}</td> <td>{{ search_query.specialty }}</th> </tr> 

Or you format it for Excel.

+5
source

A form has a cleaned_data attribute only if it is valid. If you want to access the value for one of the form fields, you can simply write in the template:

{{ form.data.%field_name% }}

+8
source

try the following: {{ form.a.value }}

+5
source

All Articles