Unable to iterate a dictionary in django templating language - django

I have not been able to iterate (key and values) in a nested dictionary generated from views.py where
context = { "orders_current": orders_current }
with
return render(request, "orders/cart.html", context)
orders_current is a result from a query in views.py:
orders_current = Orders.objects.values('def', 'abc', 'toppings')
'toppings' is stored in the database as JSON data but converted (loads) back to a dictionary in the class method:
def __str__(self)
in models.py. I did this since I read somewhere this is a recommend way of storing a dictionary in the postgresql.
Note that orders_current has multiple and nested dictionaries e.g.:
< QuerySet [{'category_name': 'Regular Pizza', 'size': 'small', 'item_name': 'Cheese', 'item_price': Decimal('12.70'), 'toppings_selected': True, 'toppings': '{"Mushrooms": 1.5, "Canadian Bacon": 1.5}'}] >
The dictionary {{ order.toppings }} passed to the html, cart.html is shown to have the value (in verbatim) e.g.:
{"Mushrooms": 1.5, "Canadian Bacon": 1.5}
So my latest attempt to extract the topping name and the corresponding price (key, value) from the dictionary is:
{% for order in orders_current %}
...
<table>
{% for name, price in order.toppings.items %}
<tr>
<td>{{ name }}:</td>
<td>${{ price }}</td>
</tr>
{% endfor %}
</table>
I got no values (name, price)from this code snippet.
Based on my web searches, I've tried almost all variations of the above and with different ways of setting up the context for transfer. Any help will be appreciated.

Based on your queryset:
< QuerySet [{'category_name': 'Regular Pizza', 'size': 'small', 'item_name': 'Cheese', 'item_price': Decimal('12.70'), 'toppings_selected': True, 'toppings': '{"Mushrooms": 1.5, "Canadian Bacon": 1.5}'}] >
order.toppings is a string, try to convert it to dictionary in the views:
import ast
for order in orders_current:
order["toppings"] = ast.literal_eval(order["toppings"])
Here are different ways to convert string dictionary to dictionary.
https://www.geeksforgeeks.org/python-convert-string-dictionary-to-dictionary/
After you convert it, it should work in the template.

Related

Flask jinja display date fields correctly

I've found a shorthand method to fetch the results from MongoDb and to pass to the jinja template.
#app.route('/home')
def home():
table = mongo.db.posts
result = table.find( { } ).sort([("postdate", 1)])
records = json.loads(json_util.dumps(result))
if result.count() > 0:
return render_template('users/index.html', posts=records)
else:
message = 'I couldn't find any post'
return render_template('users/index.html', message=message)
And in users/index.html I would like to display the results like this:
{% for post in posts %}
<tr>
<td>{{post._id}}</td>
<td>{{post.title}}</td>
<td>{{post.author}}</td>
<td class="date">{{post.postdate}}</td>
</tr>
{% endfor %}
Everything works as expected except date fields. Is there a way to display date fields correctly ?
{'$date': 1508227970796}
{'$date': 1508228089163}
{'$date': 1508241780398}
What you are seeing is the timestamp of this date, there are two possibilities to solve this issue:
you ca use this inside you view to convert the date into a readable format before sending the array to the Jinja template
from datetime import datetime
datetime.fromtimestamp(the_date_you_want_to_convert)
or you can create a simple Jinja filter which will convert a given timestamp into your readable date format.

How to auto-generate simple HTML with model fields? [duplicate]

I'm trying to create a basic template to display the selected instance's field values, along with their names. Think of it as just a standard output of the values of that instance in table format, with the field name (verbose_name specifically if specified on the field) in the first column and the value of that field in the second column.
For example, let's say we have the following model definition:
class Client(Model):
name = CharField(max_length=150)
email = EmailField(max_length=100, verbose_name="E-mail")
I would want it to be output in the template like so (assume an instance with the given values):
Field Name Field Value
---------- -----------
Name Wayne Koorts
E-mail waynes#email.com
What I'm trying to achieve is being able to pass an instance of the model to a template and be able to iterate over it dynamically in the template, something like this:
<table>
{% for field in fields %}
<tr>
<td>{{ field.name }}</td>
<td>{{ field.value }}</td>
</tr>
{% endfor %}
</table>
Is there a neat, "Django-approved" way to do this? It seems like a very common task, and I will need to do it often for this particular project.
model._meta.get_all_field_names() will give you all the model's field names, then you can use model._meta.get_field() to work your way to the verbose name, and getattr(model_instance, 'field_name') to get the value from the model.
NOTE: model._meta.get_all_field_names() is deprecated in django 1.9. Instead use model._meta.get_fields() to get the model's fields and field.name to get each field name.
You can use Django's to-python queryset serializer.
Just put the following code in your view:
from django.core import serializers
data = serializers.serialize( "python", SomeModel.objects.all() )
And then in the template:
{% for instance in data %}
{% for field, value in instance.fields.items %}
{{ field }}: {{ value }}
{% endfor %}
{% endfor %}
Its great advantage is the fact that it handles relation fields.
For the subset of fields try:
data = serializers.serialize('python', SomeModel.objects.all(), fields=('name','size'))
Finally found a good solution to this on the dev mailing list:
In the view add:
from django.forms.models import model_to_dict
def show(request, object_id):
object = FooForm(data=model_to_dict(Foo.objects.get(pk=object_id)))
return render_to_response('foo/foo_detail.html', {'object': object})
in the template add:
{% for field in object %}
<li><b>{{ field.label }}:</b> {{ field.data }}</li>
{% endfor %}
Here's another approach using a model method. This version resolves picklist/choice fields, skips empty fields, and lets you exclude specific fields.
def get_all_fields(self):
"""Returns a list of all field names on the instance."""
fields = []
for f in self._meta.fields:
fname = f.name
# resolve picklists/choices, with get_xyz_display() function
get_choice = 'get_'+fname+'_display'
if hasattr(self, get_choice):
value = getattr(self, get_choice)()
else:
try:
value = getattr(self, fname)
except AttributeError:
value = None
# only display fields with values and skip some fields entirely
if f.editable and value and f.name not in ('id', 'status', 'workshop', 'user', 'complete') :
fields.append(
{
'label':f.verbose_name,
'name':f.name,
'value':value,
}
)
return fields
Then in your template:
{% for f in app.get_all_fields %}
<dt>{{f.label|capfirst}}</dt>
<dd>
{{f.value|escape|urlize|linebreaks}}
</dd>
{% endfor %}
In light of Django 1.8's release (and the formalization of the Model _meta API, I figured I would update this with a more recent answer.
Assuming the same model:
class Client(Model):
name = CharField(max_length=150)
email = EmailField(max_length=100, verbose_name="E-mail")
Django <= 1.7
fields = [(f.verbose_name, f.name) for f in Client._meta.fields]
>>> fields
[(u'ID', u'id'), (u'name', u'name'), (u'E-mail', u'email')]
Django 1.8+ (formalized Model _meta API)
Changed in Django 1.8:
The Model _meta API has always existed as a Django internal, but wasn’t formally documented and supported. As part of the effort to make this API public, some of the already existing API entry points have changed slightly. A migration guide has been provided to assist in converting your code to use the new, official API.
In the below example, we will utilize the formalized method for retrieving all field instances of a model via Client._meta.get_fields():
fields = [(f.verbose_name, f.name) for f in Client._meta.get_fields()]
>>> fields
[(u'ID', u'id'), (u'name', u'name'), (u'E-mail', u'email')]
Actually, it has been brought to my attention that the above is slightly overboard for what was needed (I agree!). Simple is better than complex. I am leaving the above for reference. However, to display in the template, the best method would be to use a ModelForm and pass in an instance. You can iterate over the form (equivalent of iterating over each of the form's fields) and use the label attribute to retrieve the verbose_name of the model field, and use the value method to retrieve the value:
from django.forms import ModelForm
from django.shortcuts import get_object_or_404, render
from .models import Client
def my_view(request, pk):
instance = get_object_or_404(Client, pk=pk)
class ClientForm(ModelForm):
class Meta:
model = Client
fields = ('name', 'email')
form = ClientForm(instance=instance)
return render(
request,
template_name='template.html',
{'form': form}
)
Now, we render the fields in the template:
<table>
<thead>
{% for field in form %}
<th>{{ field.label }}</th>
{% endfor %}
</thead>
<tbody>
<tr>
{% for field in form %}
<td>{{ field.value|default_if_none:'' }}</td>
{% endfor %}
</tr>
</tbody>
</table>
Ok, I know this is a bit late, but since I stumbled upon this before finding the correct answer so might someone else.
From the django docs:
# This list contains a Blog object.
>>> Blog.objects.filter(name__startswith='Beatles')
[<Blog: Beatles Blog>]
# This list contains a dictionary.
>>> Blog.objects.filter(name__startswith='Beatles').values()
[{'id': 1, 'name': 'Beatles Blog', 'tagline': 'All the latest Beatles news.'}]
You can use the values() method of a queryset, which returns a dictionary. Further, this method accepts a list of fields to subset on. The values() method will not work with get(), so you must use filter() (refer to the QuerySet API).
In view...
def show(request, object_id):
object = Foo.objects.filter(id=object_id).values()[0]
return render_to_response('detail.html', {'object': object})
In detail.html...
<ul>
{% for key, value in object.items %}
<li><b>{{ key }}:</b> {{ value }}</li>
{% endfor %}
</ul>
For a collection of instances returned by filter:
object = Foo.objects.filter(id=object_id).values() # no [0]
In detail.html...
{% for instance in object %}
<h1>{{ instance.id }}</h1>
<ul>
{% for key, value in instance.items %}
<li><b>{{ key }}:</b> {{ value }}</li>
{% endfor %}
</ul>
{% endfor %}
I used https://stackoverflow.com/a/3431104/2022534 but replaced Django's model_to_dict() with this to be able to handle ForeignKey:
def model_to_dict(instance):
data = {}
for field in instance._meta.fields:
data[field.name] = field.value_from_object(instance)
if isinstance(field, ForeignKey):
data[field.name] = field.rel.to.objects.get(pk=data[field.name])
return data
Please note that I have simplified it quite a bit by removing the parts of the original I didn't need. You might want to put those back.
You can have a form do the work for you.
def my_model_view(request, mymodel_id):
class MyModelForm(forms.ModelForm):
class Meta:
model = MyModel
model = get_object_or_404(MyModel, pk=mymodel_id)
form = MyModelForm(instance=model)
return render(request, 'model.html', { 'form': form})
Then in the template:
<table>
{% for field in form %}
<tr>
<td>{{ field.name }}</td>
<td>{{ field.value }}</td>
</tr>
{% endfor %}
</table>
Below is mine, inspired by shacker's get_all_fields.
It gets a dict of one model instance, if encounter relation field, then asign the field value a dict recursively.
def to_dict(obj, exclude=[]):
"""生成一个 dict, 递归包含一个 model instance 数据.
"""
tree = {}
for field in obj._meta.fields + obj._meta.many_to_many:
if field.name in exclude or \
'%s.%s' % (type(obj).__name__, field.name) in exclude:
continue
try :
value = getattr(obj, field.name)
except obj.DoesNotExist:
value = None
if type(field) in [ForeignKey, OneToOneField]:
tree[field.name] = to_dict(value, exclude=exclude)
elif isinstance(field, ManyToManyField):
vs = []
for v in value.all():
vs.append(to_dict(v, exclude=exclude))
tree[field.name] = vs
elif isinstance(field, DateTimeField):
tree[field.name] = str(value)
elif isinstance(field, FileField):
tree[field.name] = {'url': value.url}
else:
tree[field.name] = value
return tree
This function is mainly used to dump a model instance to json data:
def to_json(self):
tree = to_dict(self, exclude=('id', 'User.password'))
return json.dumps(tree, ensure_ascii=False)
There should really be a built-in way to do this. I wrote this utility build_pretty_data_view that takes a model object and form instance (a form based on your model) and returns a SortedDict.
Benefits to this solution include:
It preserves order using Django's built-in SortedDict.
When tries to get the label/verbose_name, but falls back to the field name if one is not defined.
It will also optionally take an exclude() list of field names to exclude certain fields.
If your form class includes a Meta: exclude(), but you still want to return the values, then add those fields to the optional append() list.
To use this solution, first add this file/function somewhere, then import it into your views.py.
utils.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: ai ts=4 sts=4 et sw=4
from django.utils.datastructures import SortedDict
def build_pretty_data_view(form_instance, model_object, exclude=(), append=()):
i=0
sd=SortedDict()
for j in append:
try:
sdvalue={'label':j.capitalize(),
'fieldvalue':model_object.__getattribute__(j)}
sd.insert(i, j, sdvalue)
i+=1
except(AttributeError):
pass
for k,v in form_instance.fields.items():
sdvalue={'label':"", 'fieldvalue':""}
if not exclude.__contains__(k):
if v.label is not None:
sdvalue = {'label':v.label,
'fieldvalue': model_object.__getattribute__(k)}
else:
sdvalue = {'label':k,
'fieldvalue': model_object.__getattribute__(k)}
sd.insert(i, k, sdvalue)
i+=1
return sd
So now in your views.py you might do something like this
from django.shortcuts import render_to_response
from django.template import RequestContext
from utils import build_pretty_data_view
from models import Blog
from forms import BlogForm
.
.
def my_view(request):
b=Blog.objects.get(pk=1)
bf=BlogForm(instance=b)
data=build_pretty_data_view(form_instance=bf, model_object=b,
exclude=('number_of_comments', 'number_of_likes'),
append=('user',))
return render_to_response('my-template.html',
RequestContext(request,
{'data':data,}))
Now in your my-template.html template you can iterate over the data like so...
{% for field,value in data.items %}
<p>{{ field }} : {{value.label}}: {{value.fieldvalue}}</p>
{% endfor %}
Good Luck. Hope this helps someone!
Instead of editing every model I would recommend to write one template tag which will return all field of any model given.
Every object has list of fields ._meta.fields.
Every field object has attribute name that will return it's name and method value_to_string() that supplied with your model object will return its value.
The rest is as simple as it's said in Django documentation.
Here is my example how this templatetag might look like:
from django.conf import settings
from django import template
if not getattr(settings, 'DEBUG', False):
raise template.TemplateSyntaxError('get_fields is available only when DEBUG = True')
register = template.Library()
class GetFieldsNode(template.Node):
def __init__(self, object, context_name=None):
self.object = template.Variable(object)
self.context_name = context_name
def render(self, context):
object = self.object.resolve(context)
fields = [(field.name, field.value_to_string(object)) for field in object._meta.fields]
if self.context_name:
context[self.context_name] = fields
return ''
else:
return fields
#register.tag
def get_fields(parser, token):
bits = token.split_contents()
if len(bits) == 4 and bits[2] == 'as':
return GetFieldsNode(bits[1], context_name=bits[3])
elif len(bits) == 2:
return GetFieldsNode(bits[1])
else:
raise template.TemplateSyntaxError("get_fields expects a syntax of "
"{% get_fields <object> [as <context_name>] %}")
Yeah it's not pretty, you'll have to make your own wrapper. Take a look at builtin databrowse app, which has all the functionality you need really.
This may be considered a hack but I've done this before using modelform_factory to turn a model instance into a form.
The Form class has a lot more information inside that's super easy to iterate over and it will serve the same purpose at the expense of slightly more overhead. If your set sizes are relatively small I think the performance impact would be negligible.
The one advantage besides convenience of course is that you can easily turn the table into an editable datagrid at a later date.
I've come up with the following method, which works for me because in every case the model will have a ModelForm associated with it.
def GetModelData(form, fields):
"""
Extract data from the bound form model instance and return a
dictionary that is easily usable in templates with the actual
field verbose name as the label, e.g.
model_data{"Address line 1": "32 Memory lane",
"Address line 2": "Brainville",
"Phone": "0212378492"}
This way, the template has an ordered list that can be easily
presented in tabular form.
"""
model_data = {}
for field in fields:
model_data[form[field].label] = eval("form.data.%s" % form[field].name)
return model_data
#login_required
def clients_view(request, client_id):
client = Client.objects.get(id=client_id)
form = AddClientForm(client)
fields = ("address1", "address2", "address3", "address4",
"phone", "fax", "mobile", "email")
model_data = GetModelData(form, fields)
template_vars = RequestContext(request,
{
"client": client,
"model_data": model_data
}
)
return render_to_response("clients-view.html", template_vars)
Here is an extract from the template I am using for this particular view:
<table class="client-view">
<tbody>
{% for field, value in model_data.items %}
<tr>
<td class="field-name">{{ field }}</td><td>{{ value }}</td>
</tr>
{% endfor %}
</tbody>
</table>
The nice thing about this method is that I can choose on a template-by-template basis the order in which I would like to display the field labels, using the tuple passed in to GetModelData and specifying the field names. This also allows me to exclude certain fields (e.g. a User foreign key) as only the field names passed in via the tuple are built into the final dictionary.
I'm not going to accept this as the answer because I'm sure someone can come up with something more "Djangonic" :-)
Update: I'm choosing this as the final answer because it is the simplest out of those given that does what I need. Thanks to everyone who contributed answers.
Django 1.7 solution for me:
There variables are exact to the question, but you should definitely be able to dissect this example
The key here is to pretty much use the .__dict__ of the model
views.py:
def display_specific(request, key):
context = {
'question_id':question_id,
'client':Client.objects.get(pk=key).__dict__,
}
return render(request, "general_household/view_specific.html", context)
template:
{% for field in gen_house %}
{% if field != '_state' %}
{{ gen_house|getattribute:field }}
{% endif %}
{% endfor %}
in the template I used a filter to access the field in the dict
filters.py:
#register.filter(name='getattribute')
def getattribute(value, arg):
if value is None or arg is None:
return ""
try:
return value[arg]
except KeyError:
return ""
except TypeError:
return ""
I'm using this, https://github.com/miracle2k/django-tables.
<table>
<tr>
{% for column in table.columns %}
<th>{{ column }}</th>
{% endfor %}
</tr>
{% for row in table.rows %}
<tr>
{% for value in row %}
<td>{{ value }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
This approach shows how to use a class like django's ModelForm and a template tag like {{ form.as_table }}, but have all the table look like data output, not a form.
The first step was to subclass django's TextInput widget:
from django import forms
from django.utils.safestring import mark_safe
from django.forms.util import flatatt
class PlainText(forms.TextInput):
def render(self, name, value, attrs=None):
if value is None:
value = ''
final_attrs = self.build_attrs(attrs)
return mark_safe(u'<p %s>%s</p>' % (flatatt(final_attrs),value))
Then I subclassed django's ModelForm to swap out the default widgets for readonly versions:
from django.forms import ModelForm
class ReadOnlyModelForm(ModelForm):
def __init__(self,*args,**kwrds):
super(ReadOnlyModelForm,self).__init__(*args,**kwrds)
for field in self.fields:
if isinstance(self.fields[field].widget,forms.TextInput) or \
isinstance(self.fields[field].widget,forms.Textarea):
self.fields[field].widget=PlainText()
elif isinstance(self.fields[field].widget,forms.CheckboxInput):
self.fields[field].widget.attrs['disabled']="disabled"
Those were the only widgets I needed. But it should not be difficult to extend this idea to other widgets.
Just an edit of #wonder
def to_dict(obj, exclude=[]):
tree = {}
for field in obj._meta.fields + obj._meta.many_to_many:
if field.name in exclude or \
'%s.%s' % (type(obj).__name__, field.name) in exclude:
continue
try :
value = getattr(obj, field.name)
except obj.DoesNotExist as e:
value = None
except ObjectDoesNotExist as e:
value = None
continue
if type(field) in [ForeignKey, OneToOneField]:
tree[field.name] = to_dict(value, exclude=exclude)
elif isinstance(field, ManyToManyField):
vs = []
for v in value.all():
vs.append(to_dict(v, exclude=exclude))
tree[field.name] = vs
else:
tree[field.name] = obj.serializable_value(field.name)
return tree
Let Django handle all the other fields other than the related fields. I feel that is more stable
Take a look at django-etc application. It has model_field_verbose_name template tag to get field verbose name from templates: http://django-etc.rtfd.org/en/latest/models.html#model-field-template-tags
I just tested something like this in shell and seems to do it's job:
my_object_mapped = {attr.name: str(getattr(my_object, attr.name)) for attr in MyModel._meta.fields}
Note that if you want str() representation for foreign objects you should define it in their str method. From that you have dict of values for object. Then you can render some kind of template or whatever.
Django >= 2.0
Add get_fields() to your models.py:
class Client(Model):
name = CharField(max_length=150)
email = EmailField(max_length=100, verbose_name="E-mail")
def get_fields(self):
return [(field.verbose_name, field.value_from_object(self)) for field in self.__class__._meta.fields]
Then call it as object.get_fields on your template.html:
<table>
{% for label, value in object.get_fields %}
<tr>
<td>{{ label }}</td>
<td>{{ value }}</td>
</tr>
{% endfor %}
</table>
If you model name is Client and you are getting client object by id then proceed like this
client = Client.objects.get(id=id)
fields = Client._meta.get_fields()
for field in fields:
value = getattr(client, field.name)
print(field.name)
print(value)
<table border='1'>
<tr>
{% for mfild in fields%}
<td>{{mfild}}</td>
{% endfor%}
</tr>
{%for v in records%}
<tr>
<td>{{v.id}}</td>
<td>{{v.title}}</td>
<td class="">{{v.desc}}</td>
</tr>
{% endfor%}
</table>
enter code here

Custom template filter syntax in django

So i have created a custom filter:
#register.filter(name='field_values')
def field_values(model, field):
return model.objects.values_list(field, flat=True)
that takes model class value and a field for an argument and returns a list of model objects for that particular field. Here is the template where I try to call it.
<tr>
{% for field in fields %}
<td>{{ model_class|field_values: field }} </td>
{% endfor %}
</tr>
model_class is a dynamically created model in the views as such
views.py
...
if form.is_valid(): # All validation rules pass
model_classes_field = form.cleaned_data['model_classes_field']
model_class = get_model('Directories', model_classes_field)
I was expecting everything to run smoothly but instead I get a "*field_values requires 1 arguments, 0 provided*" error. Why does this happen when i have already inserted an argument?? is it a problem with the filter syntax?
You have a space after the colon which is confusing the parser. Use it like this instead:
{{ model_class|field_values:field }}
(Note that your code is pretty inefficient: it's querying the database over and over again, once for each field. Rather than doing this, you should probably query it once in the view and group the output by field.)

Calling values from a dictionary (Django)

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:
a = Generic.objects.get(pk=generic_id)
# a == {'field__name':'key1', 'value_char':'value1a', 'value_num':'value1'}
views.py
from django.shortcuts import render_to_response, get_object_or_404
def query_test(request, generic_id):
a = get_object_or_404(Generic, pk=generic_id)
return render_to_response("query_test.html", a,
context_instance=RequestContext(request))
query_test.html
Name: {{field__name}}
Char: {{value_char}}
Num : {{value_num}}
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:
def query_test(request, generic_id=None):
if generic_id is not None:
a = Generic.objects.filter(pk=generic_id)
else:
a = Generic.objects.all()
c = {'generic': a}
# add some extra values
c['value1'] = "I am value1"
# add a whole dictionary of other values
c.update({'value2': "yay val2", 'value3a': 3, 'value4': "I am 4"})
return render_to_response("query_test.html", c,
context_instance=RequestContext(request))
And your template something like:
<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>
{% for item in generic %}
<tr>
<td>Name: {{item.field__name}}</td>
<td>Char: {{item.value_char}}</td>
<td>Num : {{item.value_num}}</td>
</tr>
{% endfor %}
</table>
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.
not_a_generic_id = Generic.objects.get(pk=127)
not_a_dict = not_a_generic_id._get_dict()
dict_that_I_actually_want = not_a_dict[1]
return render_to_response("query_test.html", dict_that_I_actually_want)
2) Send that entire list to the template and loop over each item, and then access the values:
views.py
not_a_generic_id = Generic.objects.get(pk=127)
not_a_dict = not_a_generic_id._get_dict()
c = {"still_not_a_dict": not_a_dict}
return render_to_response("query_test.html", c)
template.html
<table>
{% for actual_dict in still_not_a_dict %}
<tr>
<td>Name: {{actual_dict.field__name}}</td>
<td>Char: {{actual_dict.value_char}}</td>
<td>Num : {{actual_dict.value_num}}</td>
</tr>
{% endfor %}
</table>
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
{% for actual_dict in still_not_a_dict %}
{% if forloop.counter == 1 %}
{{actual_dict.value_char}}
{% endif %}
{% endfor %}

Output Django Model as Table

I have a view definition that (attempts to) outputs a model as a table. This is what I have so far:
def output_table(request):
output = My_Model()
return render_to_response('outputtable.html', {'output': output})
Here's the HTML for outputtable.html:
<html>
<table>
{{ output.as_table }}
</table>
</html>
What am I doing wrong? It doesn't work. Now, it's passing the model correctly, because if I change My_Model() to My_Model.objects.all() and then output it as simply {{ output }} then it shows me what I would see in the Django shell.
So what you need to do is the following:
1) add
from django.forms import ModelForm to your models.py
2) add
class My_Model_Form(ModelForm):
class Meta:
model = My_Model
3) in your views.py, change output = My_Model() to output = My_Model_Form()
Now you are all set. So the trick is to inherit your Form from your original model.
If you're just looking to output one specific model, change your template to something like
<tr>
<td>Name:</td>
<td>{{ output.name}}</td>
</tr>
for all the fields you care about. If this is something you want to be able to do for any arbitrary model in your app, take a look at this snippet. That would provide you with a fields collection to loop over.
The models.Model class doesn't have a method as_table() like the forms.ModelForm class does.
My solution was to also use template tags. I went with an inclusion tag.
myapp/templatetags/model_helpers.py
from django import template
register = template.Library()
#register.inclusion_tag('myapp/model_table.html', takes_context=True)
def model_as_table(context, model_key=None, model_table_attrs_key=None):
if model_key is None:
model_key = 'object'
if model_table_attrs_key is None:
model_table_attrs_key = 'model_table_attrs'
try:
attrs = context[model_table_attrs_key]
except KeyError:
attrs = context[model_key]._meta.get_all_field_names()
table_context = {'rows': []}
for attr in attrs:
try:
value = str(getattr(context[model_key], attr))
if value:
table_context['rows'].append({'attr': attr,
'value': context[model_key][attr]})
except AttributeError:
pass
# Needs a way to display many_to_many fields.
except StopIteration:
pass
return table_context
myapp/templates/myapp/model_table.html
{% for row in rows %}
<tr>
<td class="name">{{ row.attr }}</td>
<td class="field">{{ row.value }}</td>
</tr>
{% endfor %}
myapp/templates/myapp/outputtable.html
{% load model_helpers %}
<table>
{% model_as_table %}
</table>
With this implementation you can pass which model's attributes you want to display and in which order.
myapp/views.py
def output_table(request):
output = My_Model()
return render_to_response('outputtable.html',
{'output': output, 'model_table_attrs': ['attr1', 'attr2']})
I also like this cleanly separate html and python code.
There is no method as_table on a model instance (MyModel())or on Querysets (MyModel.objects.all()). You may have seen as_table as the forms method as_table. You don't have a form there.
If you want to print a model instance/ a queryset as a table, you will have to design it yourself.
OMG this is old but Generic Views seem to be a good fit for this problem, for me at least. A List detail view should help me get running faster. :)
I came up with a solution that worked for my specific need which renders any simple model's data into table rows. Add the following filter into templatetags/your_tags_file.py (don't forget the __init__.py file in the templatetags folder):
from django import template
register = template.Library()
#register.filter()
def as_table(model):
ret = ""
for name in model._meta.get_all_field_names():
try:
field = str(getattr(model, name))
if field:
ret += '<tr><td class="name">'+name+'</td><td class="field">'+field+'</td></td>'
except AttributeError:
pass
return ret
In the template now you can just do:
{% load your_tags_file %}
<table>
{{output|as_table|safe}}
</table>
This will render the model in a simple table for you. You can easily add any desired thead and tbody logic as you see fit by modifying the logic of how ret is generated. Hope this helps someone.