I am fairly new to Django and I am having trouble getting values to load into the HTML from the dictionary generated in the models.py that looks like this:
>>> generic_id = Generic.objects.get(pk=127)
>>> dict = generic_id._get_dict()
>>> dict
[{'field__name':'key1', 'value_char':'value1a', 'value_num':'value1'},{'field__name':'key2', 'value_char':'value2a', 'value_num':'value2'},{'field__name':'key3', 'value_char':'value3a', 'value_num':'value3'},{'field__name':'key4', 'value_char':'value4a', 'value_num':'value4'}]
>>> dict[2]['value_num']
Decimal('value2')
>>> dict[3]['value_char']
'value3a'
The HTML table looks like this:
<table>
<tr>
<td>Description1</td><td>{{value1}}</td>
<td>Description2</td><td>{{value2}}</td>
<td>Description3</td><td>{{value3a}}</td>
<td>Description4</td><td>{{value4}}</td>
</tr>
<tr>
<td>Name: {{ generic.name }}</td>
<td>E-mail: {{ generic.email }}</td>
<td>State: {{ generic.state }}
</table>
The code in the views.py right now looks like this:
def query_test(request, generic_id):
try:
a = Generic_table.objects.get(pk=generic_id)
except Generic_table.DoesNotExist:
raise Http404
t = loader.get_template('query_test.html')
c = RequestContext(request, {
'generic' : a, })
return HttpResponse(t.render(c))
Can someone give me some suggestions as to how to (and efficiently) get the appropriate values from the dictionary into the generated HTML?
Based on what your objects look like from your model, and your template, I would suggest trying this:
assuming:
views.py
query_test.html
Your view doesn’t show that you are expecting more than one object, since you look for an id, so your template would end up formatting just one object.
Edit: In case you are trying to display a list of results
views.py might look something like this:
And your template something like:
Edit2: Addressing the strange object you are sending to your template
Based on your updated question… That is not a dictionary. Its a list of dictionaries, and Its really strange the way you are pulling that data from the single model instance. But assuming that is what you really really want, you have a number of options..
1) Fix that data object BEFORE sending it to the template. I have no idea if you want all the elements in that list, or just a specific item.
2) Send that entire list to the template and loop over each item, and then access the values:
views.py
template.html
3) Even though the template does not let you actually access numeric indexes of lists because you are suppost to sort that data out yourself in the view…if you insist on accessing a specific index of that list in the template, do the same as #2 for the views.py, but:
template.html