views:

877

answers:

2

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.

+1  A: 

Since you're trying to get this data from a filled out form, I think the easiest way would be to pass the forms .cleaned_data to the template and use that. Let's say you have a form with fields name and specialty, it would 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 just pull out the values you want:

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

Or however you format it for Excel.

tghw
Thanks. That's an option I had considered (it'd be easier than parsing HTML :P), but I was hoping that Django provided a class function/property to actually get a field's value.
kchau
If the query had a model with it, you could use form.instance, but it sounds like since it's a query, there probably isn't one.Thinking about it now, it you really don't want to pass it in the view, you can always access form.cleaned_data.foo_bar in the template. That might be more what you're looking for.
tghw
Thanks tghw. I actually ended up using the model instance approach.
kchau
+1  A: 

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% }}

Alex