Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django ModelForm: accessing a field's value in the view template

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

Background: I have a search form that I'm using to allow users to filter down query results. And, the table of results, along with the form can, be exported to an Excel sheet. When the page is rendered w/ the new results, the input values of the search form are still persisted. However, they're also still contained in the field object for each input field of the form. So, during the export to Excel, the search form's values aren't being grabbed because the value isn't in a table cell of its own. So, I want to add a column after the field's column that contains the field's value (but not display this column).

I could parse the HTML string for the field and grab whatever's in the value attribute, but I'd only do that as a last resort. So far, I've been able to access the data dictionary of my form and get the object of whichever field I want, but I haven't figured out which method I can use to actually grab the field's value.

like image 473
kafuchau Avatar asked Oct 29 '09 17:10

kafuchau


1 Answers

Form has attribute cleaned_data only if is it valid. If you want to access to value for one of Form's fields you can just write in template:

{{ form.data.%field_name% }}

like image 123
Alex Avatar answered Oct 25 '22 18:10

Alex