I have 2 models Category and Spending where Category is one of the Spending fields.
User can create custom categories and add spending on the webpage.
The question is, how to filter spendings by categories in Template?
I have:
{% for category in categories %}
{% for spending in spendings %} 'I want this FOR have only spendings from this category.'
I know how to filter objects with Object.objects.filter() but I am not sure it applies here, because categories are dynamic here
Use the reverse relation. You haven't shown your models, but presumably there is a foreign key from Spending to Category. If so:
{% for spending in category.spending_set.all %}
You can do this way.
{% for category in categories %}
{% for spending in category.spending_set.all %}
{{spending}}
{% endfor %}
{% endfor %}
Related
I have a question.
In my view, I return a dataset which includes:
Category
Product
Price
I want to say something like the below, where I show UI elements related to a category as a whole.
is it possible?
{% for item.category in products %}
Not directly. You would do
{% for item in products %}
...
{{ item.category}}
Or if item.category is itself an iterable you can nest loops. If it's the set of related objects you need a .all (c.f. python obj.foo_set.all() )
{% for item in products %}
...
{% for category in item.category.all %}
{% for item in products %}
{{item.Category}}
{{item.Product}}
{{item.Price}}
{% endfor %}
I have a model from which I need to list all the objects from a given time period.
For example: 10-05-2014 to 10-12-2014
And then I need to display the objects date wise. Meaning first display objects created on the start_date(10-05-2014) up until end_date(10-12-2014)
For example:
10-05-2014:
objects list for that day
11-05-2014:
objects list for that day
and so on until end_date
Query:
MyModel.objects.unsettled.filter(
created_on__range=[start_date, end_date]
)
But my problem is how do I list the query set in increasing order by date wise in my template. So that all the objects created on same date will be shown under that date. In short I want to display the list in sections divided by date.
MyModel.objects.unsettled.filter(created_on__range=[start_date, end_date]).order_by("created_on"). But it will just sort the list. How do I group the results.??
Use the {% ifchanged %} template tag:
{% for obj in obj_list %}
{% ifchanged %}
<h2>{{ obj.created_on|date }}</h2>
{% endifchanged %}
<div>{{ obj.name }}</div>
{% endfor %}
Another (slightly more complex) option is to use the {% regroup %} tag.
I have several models in my application, and as I will have some views doing the same thing (form + tables showing existing records in my model), but implemented dfferently because of the model, which will be different in each case, I was wondering if it was possible to make it generic.
I googled a bit and was not able to find anything relevant to my case.
What I would like to achieve:
In my view, I want to go through each object from the model that I passed to the template, for example:
return render_template('addstatus.html', form=form, statuses=Status.query.all(),
target_model="Status", fields=Status.__mapper__.c.keys())
But I want to have only one view, whatever the model will be, so I am not able to know in advance the fields of my model, the number of columns and so on.
I want to have something like that in my view:
{% for obj in objects %}
{% for field in obj.fields %} (not existing)
<h1> {{ field }} :: {{ obj.fields.field.value }}
{% endfor %}
{% endfor %}
Is it something possible? How can I achieve that?
You can add this method to your db.Model class (either by subclassing or by monkeypatching):
from sqlalchemy.orm import class_mapper, ColumnProperty
def columns(self):
"""Return the actual columns of a SQLAlchemy-mapped object"""
return [prop.key for prop in class_mapper(self.__class__).iterate_properties
if isinstance(prop, ColumnProperty)]
Then you can use {% for col in obj.columns() %} to iterate over the column names.
I had a similar issue, and wanted something purely Jinja2 based. This will return all of the keys/fields in your "obj" table, and worked well for me:
obj.__table__.columns._data.keys()
Here it is implemented in your sample code
{% for obj in objects %}
{% for field in obj.__table__.columns._data.keys() %}
<h1> {{ field }} :: {{ obj[field] }} </h1>
{% endfor %}
{% endfor %}
I'm using django-haystack for a search page on my site, and I want to order all the results by their content type. Is there a way I can do that?
To make it simpler, suppose I have a single application and several classes.
Thanks in advance
Not sure what you mean by content type, but if you are talking about group by models, I have this working
{% with page.object_list as results %}
{% regroup results|dictsort:"verbose_name_plural" by verbose_name_plural as grouped_objects %}
{% for ct in grouped_objects %}
{{ ct.grouper }}
{% for result in ct.list %}
<p>
{{ result.object }}
</p>
{% endfor %}
{% empty %}
<p>No results found.</p>
{% endfor %}
{% endwith %}
from How to order search results by Model:
You can do
SearchQuerySet().order_by('django_ct').
As a warning, this throws out
relevancy. The only way to keep
relevancy & group by model is either
to run many queries (one per model -
usually performant thanks to query
caching) or to run the query and
post-process the results, regrouping
them as you go.
from searchindex api:
Haystack reserves the following field
names for internal use: id, django_ct,
django_id & content. The name & type
names used to be reserved but no
longer are.
You can override these field names
using the HAYSTACK_ID_FIELD,
HAYSTACK_DJANGO_CT_FIELD &
HAYSTACK_DJANGO_ID_FIELD if needed.
Hay, i have a field in one of my models which saves the creation date of an object
created_on = models.DateTimeField(blank=False, auto_now_add=True)
This works as expected.
In my templates i want to list objects like this
June 15
{{ objects here which was created on June 15 }}
June 14
{{ objects here which was created on June 14 }}
etc
Any idea how i would go about doing this?
Thanks in advance.
First in the view, make sure your objects are ordered by the 'created_on' field.
object_list = MyObjs.objects.all().order_by('created_on')
I believe you should then be able to use the following code in your template:
{% regroup object_list by created_on|date:"Y-m-d" as objects_by_day %}
{% for day in objects_by_day %}
{{day.list.0.created_on|date:"M d"}}
{% for obj in day.list %}
{{obj}}
{% endfor %}
{% endfor %}
This makes use of the regroup template tag, grouping the items by day, creating a list of objects per day. The date itself is output by using the 'date' template filter to reformat the created_on field of the first item in that date's list.
[Note: I have not tested this!]
The place for this is in the template, not the view.
You want the ifchanged template filter, which you use like this:
<h1>Archive for {{ year }}</h1>
{% for entry in entries %}
{% ifchanged %}<h3>{{ entry.date|date:"F" }}</h3>{% endifchanged %}
<p>{{ entry.date|date:"j" }} - {{ entry.title }}</p>
{% endfor %}
In this example, every time the month changes, a heading showing the month will be printed.
ifchanged can do some relatively complex things (e.g. checking if multiple variables have all changed), and can have an optional else block - see the docs for more.
you can for example generate list of dates(by day on given interval) in your view ordered from min to max, and get all objects in this interval. Then create templatetag that takes 2 arguments queryset and date,
and filter records which created(or something else) by your date.