I am trying to access a Django related field value in a Django template:
{% for item in order %}
<tr>
<td>{{ item.id }}</td>
<td class="text-left">{{ item.created }}</td>
<td class="text-left">{{ item.payments__charge_status }}</td>
<td class="text-left">{{ item.shipping_method_name }}</td>
<td class="text-right">£{{ item.total_gross_amount }}</td>
</tr>
{% endfor %}
Actual queryset defined in views.py:
orders = Order.objects.values().filter(created__range=(start_date, end_date)).filter(Q(payments__charge_status="fully-charged") | Q(payments__charge_status="not-charged"))
Payment is in a different table and I can access using payments__charge_status in the view but not in the actual template.
Any help is appreciated.
Updated with models.py for Payment Model:
....
class Payment(models.Model):
order = models.ForeignKey(
Order, null=True, related_name="payments", on_delete=models.PROTECT
)
From your database modeling order can have multiple payments ( Many-to-One )so payments is a QuerySet you should iterate through
{% for payment in item.payments.all %}
{{ payment.charge_status }
{% endfor %}
Related
I have a project and a task model and I want to make a table in a detail html that displays the tasks in the project.
I've tried doing
<table>
<tr>
<th>Name</th>
<th>Assignee</th>
<th>Start Date</th>
<th>Due Date</th>
<th>Is compeleted</th>
</tr>
<tr>
<td>{{ task.name }} </td>
<td>{{ task.assignee }}</td>
<td>{{ task.start_date }}</td>
<td>{{ task.due_date }}</td>
<td>{{ task.is_completed }}</d>
</tr>
</table>
but it just shows the table headers and not its content
here is my task model
from django.db import models
from django.conf import settings
from django.urls import reverse
# Create your models here.
class Task(models.Model):
name = models.CharField(max_length=200)
start_date = models.DateTimeField()
due_date = models.DateTimeField()
is_completed = models.BooleanField(default=False)
project = models.ForeignKey(
"projects.Project",
related_name="tasks",
on_delete=models.CASCADE,
)
assignee = models.ForeignKey(
settings.AUTH_USER_MODEL,
null=True,
related_name="tasks",
on_delete=models.SET_NULL,
)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse("show_my_tasks")
An answer to your previous question had something like:
{% for project in projects_list %}
...
{% if project.tasks.count > 0 %}
# Displaying the table in here with the project's task info...
{% else %}
<p> no tasks for this project </p>
{% endif %}
...
{% endfor %}
You should loop over all the project's tasks set within the table. For example:
# Within the true portion of the if statement...
{% if project.tasks.count > 0 %}
# Displaying the table in here with the project's task info...
<table>
<thead>
<tr>
<th>Name</th>
<th>Assignee</th>
<th>Start Date</th>
<th>Due Date</th>
<th>Is compeleted</th>
</tr>
</thead>
<tbody>
# The set of related tasks for the current project -> project.tasks.all
{% for task in project.tasks.all %}
<tr>
<td>{{ task.name }} </td>
<td>{{ task.assignee }}</td>
<td>{{ task.start_date }}</td>
<td>{{ task.due_date }}</td>
<td>{{ task.is_completed }}</d>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<p> no tasks for this project </p>
{% endif %}
Im currently trying to figure out how to autonumber my tables in my html template.
I can't seem to use the id in the database as it is not autoincrementing as it it is user dependant what they see, so the user would see not a correct ordering. Instead of seeing the table numbering go 1. 2. 3. it is 4. 8. 9. for example.
Originally i have tried this, which gave me the wrong outcome as described above:
template.html
{% for item in x%}
<tr>
<td>{{ item.id }}</td>
<td>{{ item.a}}</td>
<td>{{ item.b}}</td>
<td>{{ item.c}}</td>
</tr>
I have tried something with a while loop:
template.html
{% for item in x %}
{% while z<= item %}
{% z=z+1 %}
<tr>
<td>{{ z }}</td>
<td>{{ item.a}}</td>
<td>{{ item.b}}</td>
<td>{{ item.c }}</td>
</tr>
{% endwhile %}
{% endfor %}
For your reference the model that these templates refer to:
models.py
from django.db import models
from django.conf import settings
class x(models.Model):
creation_date = models.DateTimeField(auto_now = True)
a = models.CharField(max_length=50)
b = models.CharField(max_length=50)
c = models.CharField(max_length=50)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
Thanks in advance for your help!
You can use forloop.counter to count the iterations of a loop. Try this:
{% for item in x %}
<tr>
<td>{{ forloop.counter }}</td>
<td>{{ item.a}}</td>
<td>{{ item.b}}</td>
<td>{{ item.c}}</td>
</tr>
{% endfor %}
Reference: for template tag - Django Docs
I have two models shown below
class Services(models.Model):
name = models.CharField(max_length=200, null=True)
price = models.FloatField(null=True)
service_sku = models.CharField(max_length=200, null=True)
class Order(models.Model):
customer = models.ForeignKey(Customer, null=True, on_delete = models.SET_NULL)
service = models.ForeignKey(Service, null=True, on_delete = models.SET_NULL)
I have created a function-based view based on the service model where I want to render a template displaying a list of field information from each instance from the service model.
See below for my views and template
views.py
def service_list(request):
service_list = Service.objects.all().order_by('service_sku')
context = {'service_list':service_list}
return render(request, 'accounts/service_list.html',context)
template
<div class="card card-body">
<table class="table">
<tr>
<th>SKU</th>
<th>Service Name</th>
<th>Number of Ordered</th>
</tr>
{% for i in service_list %}
<tr>
<td>{{i.service_sku}}</td>
<td>{{i.name}} </td>
<td></td>
</tr>
{% endfor %}
I want to display the number of orders of each instance, considering that the order model has a foreign key from the service model.
The query set would have to be like the below shown.
Order.objects.all().filter(service__id =3).count()
Problem is that I must specify which id of that model would be for that queryset to work.
I’ve tried to put the queryset format below within the template
{{Order.objects.all().filter(service__id=i.id).count()}
In the template it would look like how it does below
template
<div class="card card-body">
<table class="table">
<tr>
<th>SKU</th>
<th>Service Name</th>
<th>Number of Ordered</th>
</tr>
{% for i in service_list %}
<tr>
<td>{{i.service_sku}}</td>
<td>{{i.name}} </td>
<td>{{Order.objects.all().filter(service__id=i.id).count()}}</td>
</tr>
{% endfor %}
The above implementation does not work.
Which method is ideal for this situation?
You can not call methods (with parameters) in a Django template. The templates are deliberately restricted to prevent people from writing business logic in the templates.
You can .annotate(…) [Django-doc] the queryset to fetch the number of related Orders:
from django.db.models import Count
def service_list(request):
service_list = Service.objects.annotate(
norders=Count('order')
).order_by('service_sku')
context = {'service_list':service_list}
return render(request, 'accounts/service_list.html',context)
In the template you can then render this with:
{% for i in service_list %}
<tr>
<td>{{ i.service_sku }}</td>
<td>{{ i.name }} </td>
<td>{{ i.norders }}</td>
</tr>
{% endfor %}
I am using Django v1.11. Here are 2 models:
class Task(models.Model):
title = models.CharField()
class TaskUser(models.Model):
task = models.ForeignKey(Task, related_name='task_user')
user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='+')
So, I want to get list of tasks and print in one column list of users that are related to this task. How to do that? The problem is tried a lot: select_related, prefetch_related('task_user') and so on.. but nothing works. In some cases there are no sql error, but it prints task.User.None
tasks = Task.objects.all()
View must be:
<table>
<tr>
<td>Title</td>
<td>Users</td>
</tr>
{% for task in tasks %}
<tr>
<td>{{ task.title }}</td>
<td>
{% for user in task.users %}
{{ user.id }}
{% endfor %}
</td>
</tr>
{% endfor %}
</table>
Add a many-to-many field to Task, using the through model you already have:
class Task(models.Model):
users = models.ManyToManyField(settings.AUTH_USER_MODEL, through='TaskUser')
and use .all when iterating:
{% for user in task.users.all %}
{{ user.id }}
{% endfor %}
(Note, you should remove the related_name='+' from the TaskUser.user field.)
Just wondering if Sessions can be used to create a quick compare view of two products on my Django app. I'm listing items for sale and would like a user to be able to 'like' multiple items then have a new view to compare the selected products. Any thoughts?
Thanks
Sure, just assign the list products to a session variable.
Then assign the products list to the template, which could look something like that:
<table>
<tr>
<td></td>
{% for product in products %}
<th>{{ product.title }}</th>
{% endfor %}
</tr>
<tr>
<th>Feature 1</th>
{% for product in products %}
<td>{{ product.feature1 }}</td>
{% endfor %}
</tr>
<tr>
<th>Feature 2</th>
{% for product in products %}
<td>{{ product.feature2 }}</td>
{% endfor %}
</tr>
</table>