the app is working this way. That i have a simple news adding model as below:
class News(models.Model):
title = models.CharField(max_length=100)
publication_date = models.DateField(auto_now_add=True)
content = models.TextField()
the view
def homepage(request):
posts= News.objects.all() #.get(title="aaa")
return render_to_response('homepage.html', {'a':posts})
and finally the tamplate:
{% for b in a.object_list %}
<li> title:{{ b.title }}</li>
{%empty %}
EMPTY
{% endfor %}
Unfortunately it always sais 'EMPTY'. However if i take the '.get(title="aaa")' option instead of '.all()' (the commented part) I got the right title and content of the message with title 'aaa'.
Can anyone explain what am I doing wrong?
Thanks in advance for Your expertise.
EDIT
I'm sorry I didn't have written the template for the get option Well off course the 'get' verion of template differs. It looks like this:
{{a.title}} {{a.content}
And it works printing the expected title and message content So the 'get' works with the template and the 'for' didn't iterate over the QuerySet returned by all(). I am beginner but object_list is supposed to be the representation for querySet passed in render_on_request as a element of dictionary?
When you use get, the variable posts contains an instance of News. On the other hand, if you use .all(), posts will contain a queryset. So first I would suggest you use filter instead of get, so posts would always be a queryset, and therefore you wouldn't have such an inconsistent behaviour ...
When you want to iterate over something like this:
for object in object_list:
print object
object_list needs to support iterating. list, tuple, dict, and other types support that. You can define your own iterator class by giving it a iter method. See the docs for that.
Now, in your example
return render_to_response('homepage.html', {'a':posts})
posts is a Queryset instance that supports iterating. Think of it this way:
{% for b in News.objects.all %}
this is what you would like to have, but what you actually did is this:
{% for b in News.objects.all.object_list %}
But News.objects.all does not have an object_list attribute!
News.objects.all is what your object_list should be, so just write:
{% for b in a %}
Please post the exact code you are running. There is no way that either of your alternatives would work with a.object_list, because there is no definition of object_list anywhere and it's not a built-in Django property.
And assuming you actually mean that for b in a doesn't work in the first code but does in the second, this is not true either, because with .get you won't have anything to iterate through with for.
However, let's assume what you actually did was pass the results of .all() to the template, and the template didn't have the for loop. That wouldn't work, because all() - like filter() - returns a QuerySet, which must be iterated through. For the same reason, get() wouldn't work with a for loop.
Edited after comment "object_list is supposed to be the representation for querySet passed in render_on_request " - no, it isn't. Where did you get that idea? If you pass a queryset called a to the template, then you iterate through a, nothing else. object_list is the name that is used by default in generic views for the queryset itself - ie what you have called a - but in your own views you call it what you like, and use it with the name you have given it.
Edited after second comment I don't know why this should be confusing. You've invented a need for object_list where there is no such variable, and no need for one. Just do as I said originally - {% for b in a %}.
Related
I have a Model with numerous attributes; in the template rendered by my DetailView I want to show only the attributes that are not None.
This can be easily done with an if template tag that checks if the value of the attribute is not None, tho I should add an if condition for every attribute in my model, and there's a lot of them.
I would like to iterate through all the attributes and if not None display them.
In pseudo code it would look like this:
{% for attribute in my_instance.all_attributes %}
{% if attribute.value is not None %}
{{attribute.value}}
I can get a tuple of concrete attributes both through the class or the instance:
cls._meta.concrete_fields
or
self._meta.concrete_fields
Now that I have the my_instance.all_attributes in my pseudo code example, I can iterate it but I don't know how to get the actual value of the instance's attribute.
EDIT:
.concrete_values returns an array of Field instances, it looks like this:
(<django.db.models.fields.BooleanField: gov>, <django.db.models.fields.BooleanField: in_group>, <django.db.models.fields.CharField: legal_class>,)
I can access the value of the name attribute of the Field instance using .name. Calling .name on the example above would return 'gov', 'in_group', 'legal_class'
The authors of Django went out of their way to make sure that the template language isn't used to do things like this! Their opinion as I understand it is that templates should do formatting, and Python should do program logic.
There are two ways around it. One is to create a structure that the template can iterate through, and pass it to the DetailView context. Something like
def get_context_data(self):
data = super().get_context_data(**kwargs)
fieldnames = [
x.name for x in self.object._meta.concrete_fields ]
display_fields = [
(name, getattr( self.object, name, None)) for name in fieldnames ]
display_fields = [ x for x in display_fields if x[1] is not None ]
data['display_fields'] = display_fields
return data
and in the template you can now do
{% for name,value in display_fields %}
You might prefer to code a list of names instead of using ._meta.concrete_fields because that lets you choose the order in which they appear. Or you could start with an ordered list and append anything that's in the _meta but not yet in your list (and delete anything that's in your list but not in _meta)
The other way is to use Jinja as the template engine for this view.
I have a model which is defined as shown which is acted upon a query and gets a list of objects that have to placed in appropriate cells of a table. Here is the relevant part of the code.
class Location(models.Model):
x=models.IntegerField(null=True)
y=models.IntegerField(null=True)
z=models.CharField(max_length=5,null=True)
def __unicode__(self):
return self.z
From this db i want retrieve all the objects and place them in a 2d-table with row and column defined by x,y of that object.If there is no object for certain (x,y) then that particular slot should be shown empty in the table.This is the view I wrote to meet those ends.
def gettable(request):
events=[]
for xdim in xrange(3):
xe=[]
for ydim in xrange(3):
object=[0]
object.append(Location.objects.filter(x=xdim,y=ydim))
xe.append(object[-1])
events.append(xe)
return render(request, 'scheduler/table.html', {'events':events})
Here is the html part of the code
<table border="1">
<th>Header 0</th>
<th>Header 1</th>
<th>Header 2</th>
{% for event in events %}
<tr>
{% for x in event %} <td>{{ x }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
I have to tackle multiple issues here.
1.My code for views is not at all elegant (which is bad since I know django offers lots of stuff to tackle such tasks) as I am defining variables specifically to loop through instead of taking those from the (x,y) values of database objects.
2.I get output in [<Location: 21>] format but I want it as '21'.
3.How do I introduce empty cells where there doesnot exist any object for given (x,y).
4.Please suggest any other way possible which can make my code simpler and general.
If you want to make your code simpler, I would like to recommend to use application django-tables2. This approach can solve all your issues about generating tables.
As the documentation says:
django-tables2 simplifies the task of turning sets of data into HTML
tables. It has native support for pagination and sorting. It does for
HTML tables what django.forms does for HTML forms. e.g.
Its features include:
Any iterable can be a data-source, but special support for Django querysets is included.
The builtin UI does not rely on JavaScript.
Support for automatic table generation based on a Django model.
Supports custom column functionality via subclassing.
Pagination.
Column based table sorting.
Template tag to enable trivial rendering to HTML.
Generic view mixin for use in Django 1.3.
Creating a table is as simple as:
import django_tables2 as tables
class SimpleTable(tables.Table):
class Meta:
model = Simple
This would then be used in a view:
def simple_list(request):
queryset = Simple.objects.all()
table = SimpleTable(queryset)
return render_to_response("simple_list.html", {"table": table},
context_instance=RequestContext(request))
And finally in the template:
{% load django_tables2 %}
{% render_table table %}
This example shows
one of the simplest cases, but django-tables2 can do a lot more! Check
out the documentation for more details.
It is also possible to use a dictionary instead of a queryset.
Per point:
IMO you can get away with creating a custom filter or a tag and using the queryset.
You need to define a __unicode__ (or __string__) method to return your desired item.
If the value is empty or the item doesn't exist, the rendered result will be empty too.
HTH
For point 2, you're giving each cell a list rather than a single object, {{ x.0 }} should give you the right value, but it also suggests you're approaching it wrong in your view logic.
When passing an object called widget as part of the context to rendering a django template, I may have a method which is a bit expensive, but I want to display the result of it more than once.
Python:
class Widget:
def work(self):
# Do something expensive
Template
This is a widget, the result of whose work is {{widget.work}}. Do
you want to save {{widget.work}} or discard {{widget.work}}?
Clearly I could work around this by evaluating the method once in the view code, and then passing the result in, but this seems to couple the view and the template too much. Is there a way for the template author to stash values for re-use later in the template? I would like to do something like this:
{% work_result = widget.work %}
This is a widget, the result of whose
work is {{work_result}}. Do you want to save {{work_result}} or discard {{work_result}}?
Does such a construct exist in the django template language?
{% with %}
{% with work_result=widget.work %}
Look Django docs for more information
I've got a django model that contains a manytomany relationship, of the type,
class MyModel(models.Model):
name = ..
refby = models.ManyToManyField(MyModel2)
..
class MyModel2(..):
name = ..
date = ..
I need to render it in my template such that I am able to render all the mymodel2 objects that refer to mymodel. Currently, I do something like the following,
{% for i in mymodel_obj_list %}
{{i.name}}
{% for m in i.refby.all|dictsortreversed:"date"|slice:"3" %}
{{.. }}
{% endfor %}
<div> <!--This div toggles hidden/visible, shows next 12-->
{% for n in i.refby.all|dictsortreversed:"date"|slice:"3:15" %}
{{.. }}
{% endfor %}
</div>
{% endfor %}
As the code suggests, I only want to show the latest 3 mymodel2 objects, sorted in reverse order by date, although the next 12 do get loaded.
Is this a very inefficient method of doing so? (Given that results for the refby.all could be a few 100s, and the total no of results in "mymodel_obj_list" is also in 100s - I use a paginator there).
In which case, whats the best method to pre-compute these refby's and render them to the template? Should I do the sorting and computation in the view, and then pass it? I wasn't sure how to do this in order to maintain my pagination.
View code looks something like,
obj_list = Table.objects.filter(..) # Few 100 records
pl = CustomPaginatorClass(obj_list...)
And I pass the pl to the page as mymodel_obj_list.
Thanks!
I assume mymodel_obj_list is a QuerySet. You're accessing a foreign key field inside the loop, which means, by default, Django will look up each object's refby one at a time, when you access it. If you're displaying a lot of rows, this is extremely slow.
Call select_related on the QuerySet, to pull in all of these foreign key fields in advance.
https://docs.djangoproject.com/en/dev/ref/models/querysets/#select-related
Should I do the sorting and
computation in the view, and then pass
it?
Yes, definitely.
It is not really a matter of performance (as Django's querysets are lazily evaluated, I suspect the final performance could be very similar in both cases) but of code organization.
Templates should not contain any business logic, only presentation. Of course, sometimes this model breaks down, but in general you should try as much as possible to keep into that direction.
I am currently working on an app that uses custom annotate querysets. Currently i have 2 urls setup, but i would need one for each field that the users would like to summarize data for. This could be configured manually, but it would violate DRY! I would basically have +-8 urls that basically do the same thing.
So here is what i did,
I have a created custom model manager
I have a view
I have the URLS configured
All of the above works.
So basically the URL config passes to the view the name of the field to annotate by (group by for SQL folks), the view does some additional processing and runs the custom model manager based on the field that was passed to it.
The URL looks like this:
url('^(?P<field>[\w-]+)/(?P<year>\d{4})/(?P<month>\d+)/(?P<day>\d+)/$','by_subtype', name='chart_link'),
The field is the column in db the that is used when the queryset is actually run. It is passed from the view, to my custom manager. Below is an example of the code from the manager:
return self.filter(start_date_time__year=year).filter(start_date_time__month=month).filter(start_date_time__day=day).values(field).annotate(Count(field))
In addition, i pass the value of field as context variable. This is used to dynamically build the links. However the problem is actually looping through the query set and displaying the data.
So your typical template code looks like this:
{% for object in object_list %}
{{ object.sub_type }} : {{ object.sub_type__count|intcomma }}
{% endfor %}
Basically you have to hard code the field to diplay (i.e object.x), is there anyway to dynamically assign this? i.e
if field = business
then in the template it should automatically process:
{{ object.business }}
Can this be done? Or would i need to create several URLS? Or is there a better way to achieve the same result, a single view and url handling queries dynamically.
You can find the code over at github, the template part is now working using this snippet: http://www.djangosnippets.org/snippets/1412/ So if you come across this later and want to do something similar have a look at the code snippet at github. : http://gist.github.com/233262
It sounds like you want to do something along the lines of:
# in the views.py:
field = 'business'
{# in the template: #}
{{ object.field }}
and have the value of object.business appear in the output. This isn't possible with the Django template language out of the box.
There are snippets that define template filters you can use to accomplish this though: http://www.djangosnippets.org/snippets/1412/
As mentioned above, you can do this with a custom template filter.
For example:
#register.filter(name='get_attr')
def get_attr(obj, field_name):
if isinstance(obj, dict):
return obj.get(field_name)
return getattr(obj, field_name)
Then, using it in your template:
{{ obj|get_attr:'business' }}