开发者

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,开发者_如何学C 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.


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


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜