Can anyone help using M2M and the template properly? - python

I need to show the name of menu and the quantity of it.
But this webpage doesn't show even when the client's address and their name is working out right.
I've got these models(client side) in my Django project:
class Order(models.Model):
client = models.ForeignKey(Client, on_delete=models.CASCADE)
address = models.CharField(
max_length=100,
)
created_at = models.DateTimeField(auto_now_add=True)
items = models.ManyToManyField(
Menu,
through='OrderItem',
through_fields=('order', 'menu'),
)
class OrderItem(models.Model):
order = models.ForeignKey(Order, on_delete=models.CASCADE)
menu = models.ForeignKey(Menu, on_delete=models.CASCADE)
count = models.PositiveSmallIntegerField()
and the template page like below.
{% for order in order_set %}
<tr>
<td>{{ order.client.name }}</td>
<td>{{ order.address }}</td>
<td>{% for item in order.items_set.all %}{{ item }}{% endfor %}</td>
<td>{{ order.item_set.all.count }}</td>
</tr>
{% endfor %}
</table>
Models(partner side) like below.
class Menu(models.Model):
partner = models.ForeignKey(
Partner,
on_delete=models.CASCADE,
)
image = models.ImageField(
verbose_name="메뉴 이미지"
)
name = models.CharField(
max_length=50,
verbose_name="메뉴 이름"
)
price = models.PositiveIntegerField(
verbose_name="가격"
)
Can anyone help?

Try this:
{% for order in order_set %}
<tr>
<td>{{ order.client.name }}</td>
<td>{{ order.address }}</td>
<td>{% for item in order.items.all %}{{ item }}{% endfor %}</td>
<td>{{ order.items.all.count }}</td>
</tr>
{% endfor %}
i.e., replace order.items_set.all with order.items.all. There is no relationship defined by items_set. The field you've defined on your Order model is items, so that is what you need to access.
The FOO_set approach is used for relationships in reverse on things like foreign keys. In this case you're following a relationship forward.

Related

Django - Problem with Model Manager - Query

I'm still a beginner and I'm stuck in a challenging spot for me.
I can't get data from a foreign key table to be inserted "correctly" into a column of a ListView.
I basically want to create a list view of a table (FeatureFilm). This also works. But in one column I get information from another table and here I get data, but not the one that belongs to the particular table row.
Here are my models. The table I want to show is "FeatureFilm" model. This model is inherited from my base Project class "ProjectBaseModel".
Then there is another table "CompanyInvolved Model". This is attached to the FeatureFilm table with a foreign key (feature_id).
So movies are stored (FeatureFilm) and different companies are involved in the creation process of the movies. (CompanyInvolved)
class ProjectBaseModel(models.Model):
title = models.CharField("Titel", max_length=100, blank=False, unique=True)
leading_postproduction_id = models.ForeignKey(
Company,
verbose_name="Federführende Postproduktion",
on_delete=models.SET_NULL,
blank=True,
null=True,
)
phase = models.CharField(choices=post_phase, max_length=30, blank=True, null=True)
former_title = models.CharField("Titel, ehemalig", max_length=100, blank=True)
title_international = models.CharField(
"Titel, international", max_length=100, blank=True, null=True, unique=True
)
class FeatureFilm(ProjectBaseModel):
class Meta:
verbose_name = "Kinofilm"
verbose_name_plural = "Kinofilme"
ordering = ["title"]
class ProductionManager(models.Manager):
def get_production(self):
return (
super()
.get_queryset()
.filter(company_role="Produktion", is_production_list=True)
.values_list("company_involved__name")
)
class CompanyInvolved(models.Model):
feature_id = models.ForeignKey(
FeatureFilm,
on_delete=models.CASCADE,
null=True,
blank=True,
)
tv_movie_id = models.ForeignKey(
TvMovie, on_delete=models.CASCADE, null=True, blank=True
)
company_role = models.CharField(
choices=company_role,
max_length=15,
blank=True,
help_text="Produktion, Co-Produktion, Kinoverleiher, Sender, Weltvertrieb",
)
company_involved = models.ForeignKey(
Company,
on_delete=models.SET_NULL,
null=True,
blank=True,
)
is_production_list = models.BooleanField(
default=False,
verbose_name="Produktion in Liste",
)
productionmanager = ProductionManager()
def __str__(self):
return "#" + str(self.pk)
class Meta:
verbose_name = "Produktion, Co-Produktion, Verleih, Sender, Weltvertrieb"
verbose_name_plural = "Produktion, Co-Produktion, Verleih, Sender, Weltvertrieb"
ordering = ["pk"]
I basically wanted to generate the output now via the template. I can iterate the lines with the template for loop. But I also learned that more complex queries don't work in the DjangoTemplate language, or simply don't belong there.
I don't need every row of data from the CompanyInvolved, but only the company_role = "Production" and is_production_list = True.
A combined "Where" clause in the template now nice, but doesn't exist, so I built myself a MODEL MANAGER (ProductionManager) that does this filtering in the model.
here is the View:
class FeatureListView(LoginRequiredMixin, PermissionRequiredMixin, ListView):
permission_required = "project.can_access_featurefilm_list"
model = FeatureFilm
template_name = "project/feature-list.html"
def handle_no_permission(self):
return redirect("access-denied")
ans here is the depending snippet in the template:
<tbody>
{% for project in object_list %}
<tr>
<td>{{ project.title }}</td>
<td>{{ project.companyinvolved_set.get_production }}
<br>
</td>
<td>{% if project.program_length_planned %}
{{ project.program_length_planned }}
{% endif %}
</td>
<td>{{ project.global_shooting_resolution }}</td>
<td>{{ project.global_resolution_theatrical }}</td>
<td>{% if project.hdr == 1%}
ja
{% else %}
nein
{% endif %}
</td>
<td>{{ project.stafflist.postproduction_supervisor_id.username }}</td>
<td>{% if project.phase %}
{{ project.phase }}
{% endif %}
</td>
</tr>
{% endfor %}
</tbody>
so I iterate over each movie project with {% for project in object_list %} and then I want to show in my "problem" column the company that has the role production and since there can be more than one, the one that was previously marked by the user for the lists view - > is_production_list = TRue and then the output should come: {{ project.companyinvolved_set.get_production }}.
The result is going in the right direction, but it is still not finally correct. I get the CompanyINvolved data and these are also filtered by company_role = "Production" and is_production_list = True , but these values are now displayed to me each time in each individual Row the same, I get so not per ROW the associated productions but simply each time ALL. I'm missing the reference to the FeatureFilm object, but I don't know how to get this now, or where to put this reference now?
changed my template:
<tbody>
{% for project in object_list %}
<tr>
<td>{{ project.title }}</td>
<td>
!! {{ project.production_companies.company_involved.name}}!!
<br>
</td>
<td>{% if project.program_length_planned %}
{{ project.program_length_planned }}
{% endif %}
</td>
<td>{{ project.global_shooting_resolution }}</td>
<td>{{ project.global_resolution_theatrical }}</td>
<td>{% if project.hdr == 1%}
ja
{% else %}
nein
{% endif %}
</td>
<td>{{ project.stafflist.postproduction_supervisor_id.username }}</td>
<td>{% if project.phase %}
{{ project.phase }}
{% endif %}
</td>
</tr>
{% endfor %}
</tbody>
I think your code is not working because get_production calls super().get_queryset(), which returns a new QuerySet, without any filters applied, not based on the Queryset in the reverse look up in companyinvolved_set
Your best bet is to add a #property annotation to access the filtered list through your FeatureFilm model
#property
def production_companies(self):
return [company for company in self.companyinvolved_set.all() if company.company_role == 'Produktion' and company.is_production_list]
Then add this to your template:
<td>{% for production in project.production_companies %}{{production.company_involved.name}}{% endfor %}</td>
And to prevent a lot of queries, change the get_queryset method in your view to this:
def get_queryset(self):
queryset = FeatureFilm.objects.prefetch_related('companyinvolved_set').all()
return queryset

Django modal popup on a list link

I would like to develop a popup on a list link (please see the screenshot) click. popup will be a list also.
So far this is my code below
Model class:
class PSCInscpection(models.Model):
vessel = models.ForeignKey(Vessel, on_delete=models.CASCADE, null=True)
inspection_id = models.CharField(max_length=100, null=False, unique=True)
followup_inspection = models.BooleanField(null=False, default=False)
date = models.DateTimeField(null=True, blank=True)
port = models.CharField(max_length=50, null=True, blank=True)
country = models.CharField(max_length=50, null=True, blank=True)
number_of_defects = models.PositiveIntegerField(null=True, blank=True)
days_detained = models.PositiveIntegerField(null=True, blank=True)
class PSCInscpectionDefects(models.Model):
pscinscpection = models.ForeignKey(PSCInscpection, on_delete=models.CASCADE, null=True)
inspection_id = models.CharField(max_length=100, null=False, blank=False)
defect_code = models.CharField(max_length=50, null=True, blank=True)
defect_text = models.CharField(max_length=255, null=True, blank=True)
class_is_responsible = models.CharField(max_length=50, null=True, blank=True)
defective_item_code = models.CharField(max_length=50, null=True, blank=True)
views.py
inspections = PSCInscpection.objects.filter(
vessel_id=self.kwargs['pk']).order_by('-date')
renderableInspections = []
for _insp in inspections:
item = {
"date": _insp.date.strftime("%Y-%m-%d"),
"port": _insp.port,
"country": _insp.country,
"defects": _insp.number_of_defects,
"detained": _insp.days_detained
}
renderableInspections.append(item)
context['inspections'] = renderableInspections
My list binding from this "PSCInscpection" object and popup will bind from "PSCInscpectionDefects" object. Any help regarding please ? Thanks !
view.html:
{% for inspection in inspections %}
<tr>
<td>{{ inspection.date }}</td>
<td>{{ inspection.country }}</td>
<td>{{ inspection.port }}</td>
<td>
{% if inspection.defects %}
{{ inspection.defects }}
{% else %}
{{ 0 }}
{% endif %}
</td>
<td>{{ inspection.detained|default:0 }} Days</td>
</tr>
{% endfor %}
You should be able to access the defects tied to each inspection through the reverse foreign key relationship, but currently you can't do that because the context you're sending to the template is not the queryset of objects itself. Instead, you constructed a data structure manually to handle this which isn't necessary.
You should send the context as your object queryset so you can access your reverse foreign key relationship directly in the template with inspections.pscinscpectiondefects_set.all. This is very verbose, so I recommend setting a related_name attribute to the pscinscpection field in your PSCInscpectionDefects model to defects or similar so you can instead access it with inspections.defects.all.
Simplify your view to return the filtered queryset instead.
# views.py
context['inspections'] = PSCInscpection.objects.filter(
vessel_id=self.kwargs['pk']).order_by('-date')
return context
I won't provide HTML/CSS/JS code for the modal because this question is Django related. But you should be able to launch one when the user clicks the link to the number of defects. Here's the template change assuming a related_name is set.
# view.html
{% for inspection in inspections %}
<tr>
<td>{{ inspection.date }}</td>
<td>{{ inspection.country }}</td>
<td>{{ inspection.port }}</td>
<td>
{% if inspection.defects %}
{{ inspection.defects.count }} <!-- link to modal here -->
{% for defect in inspection.defects.all %}
{{ defect }}
{% endfor %}
{% else %}
{{ 0 }}
{% endif %}
</td>
<td>{{ inspection.detained|default:0 }} Days</td>
</tr>
{% endfor %}

Django - Foreign Key not working

I'm trying to display some data on a webpage using a foreach loop and django.
I do not seem to understand how to use a lookup table that I have created in my Database.
These are the columns from the DB:
budget_audit_table:
-BudgetID
-BudgetTypeID <- Foreign Key
-ObjectAuditID
-CustomerID
-DateOfTransaction
-BudgetObject
-Amount
budget_type:
-BudgetTypeID
-BudgetType
As you can probably assume in the model.py, the BudgetTypeID is a foreign key.
In the budget_type table I currently have 2 rows:
- Expense: ID 1
- Income: ID 2
Now the problem I'm having is I have searched for a few days now trying to understand Django's API more and I'm struggling to understand how do I for each row that is displayed from the budget_audit_table, how do I instead of displaying the BudgetTypeID (eg 1), it displays the BudgetType (eg Expense)?
Here is my view & template
view.py
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from django.template import RequestContext, loader
from models import BudgetAuditTable
from models import BudgetType
#login_required
def index(request):
budgetauditlist = BudgetAuditTable.objects.order_by('-budgetid')
template = loader.get_template('budget/budget.html')
context = RequestContext(request, {
'budgetauditlist': budgetauditlist,
})
return HttpResponse(template.render(context))
Template
{% for budgetauditobject in budgetauditlist %}
<tr>
<td>{{ budgetauditobject.budgetid }}</td>
<td>{{ budgetauditobject.budgettypeid }}</td>
<td>{{ budgetauditobject.objectauditid }}{{ budgetauditobject.customerid }}</td>
<td>{{ budgetauditobject.amount }}</td>
</tr>
{% endfor %}
models.py
class BudgetAuditTable(models.Model):
budgetid = models.IntegerField(db_column='BudgetID', primary_key=True)
budgettypeid = models.ForeignKey('BudgetType', db_column='BudgetTypeID', blank=True, null=True)
objectauditid = models.IntegerField(db_column='ObjectAuditID', blank=True, null=True)
customerid = models.IntegerField(db_column='CustomerID', blank=True, null=True)
dateoftransaction = models.DateField(db_column='DateOfTransaction', blank=True, null=True)
budgetobject = models.CharField(db_column='BudgetObject', max_length=255, blank=True)
amount = models.DecimalField(db_column='Amount', max_digits=10, decimal_places=2, blank=True, null=True)
class Meta:
managed = False
db_table = 'budget_audit_table'
class BudgetType(models.Model):
budgettypeid = models.IntegerField(db_column='BudgetTypeID', primary_key=True)
budgettype = models.CharField(db_column='BudgetType', max_length=25, blank=True)
class Meta:
managed = False
db_table = 'budget_type'
In your template try:
{% for budgetauditobject in budgetauditlist %}
<tr>
<td>{{ budgetauditobject.budgetid }}</td>
<td>{{ budgetauditobject.budgettypeid.budgettype }}</td>
<td>{{ budgetauditobject.objectauditid }}{{ budgetauditobject.customerid }}</td>
<td>{{ budgetauditobject.amount }}</td>
</tr>
{% endfor %}
Furthermore you should rename your BudgetType ForeignKey field in your model simply to BudgetType since your ForeignKey relation represents another entity.
See this link for the relationship lookups.
budgetauditobject.budgettypeid specify a BudgetType object, you should use the attributes under BudgetType like this:
{{ budgetauditobject.budgettypeid.budgettype }}
{{ budgetauditobject.budgettypeid.budgettypeid }}
So, you need to modify the template like this:
{% for budgetauditobject in budgetauditlist %}
<tr>
<td>{{ budgetauditobject.budgetid }}</td>
<td>{{ budgetauditobject.budgettypeid }}</td>
<td>{{ budgetauditobject.objectauditid }}{{ budgetauditobject.customerid }}</td>
<td>{{ budgetauditobject.amount }}</td>
</tr>
{% endfor %}
{{ budgetauditobject.budgettypeid.budgettype }}
Its quite simple, just follow the relationship, like this:
{% for budgetauditobject in budgetauditlist %}
<tr>
<td>{{ budgetauditobject.budgetid }}</td>
<td>{{ budgetauditobject.budgettypeid.budgettype }}</td>
<td>{{ budgetauditobject.objectauditid }}{{ budgetauditobject.customerid }}</td>
<td>{{ budgetauditobject.amount }}</td>
</tr>
{% endfor %}
The . syntax will allow you to follow and query items from the linked table. budgetauditobject.bugettypeid.budgettype means "get the bugettype field's value of the bugettypid that corresponds to this budgetauditobject"
You can try changing
{{ budgetauditobject.budgettypeid }}
to
{{ budgetauditobject.budgettypeid.budgettype }}

Django select_related: How to display related table data in a template

I am having trouble displaying fields of related tables in my template when using select_related()
Here is my model:
class Customer(models.model):
customer_name = models.CharField(max_length=500)
class Orders(models.model):
cust_id = models.ForeignKey(Customers)
invoice_number = models.IntegerField()
invoice_creation_date = models.DateTimeField('Invoice Created Date')
class Products(models.Model):
name = models.CharField(max_length=500)
description = models.CharField(max_length=500)
price = models.DecimalField(max_digits=20, decimal_places=2)
class Orders_Products(models.Model):
order_id = models.ForeignKey(Orders)
product_id = models.ForeignKey(Products)
quantity = models.IntegerField(default=0)
Here is my view:
def home(request):
list_of_orders = Orders_Products.objects.select_related()
template = 'erp_app/home.html'
context = RequestContext(request, {'list_of_orders': list_of_orders})
return render(request, template, context)
How do I represent related fields from Orders and Products, and especially Customers in a template. E.g. I want to display Orders.invoice_number, Products.name and Customer.customer_name from the same related record.
For example:
{% for order in list_of_orders %}
<tr>
<td>{{ order.orders.invoice_number }}</td>
<td>{{ order.products.name }}</td>
<td>{{ order.customers.customer_name }}</td>
</tr>
{% endfor %}
I figured it out. I'm leaving this question and answer here for the next poor soul who has to nut his way through this conundrum.
{% for order in list_of_orders %}
<tr>
<td>{{ order.order_id.cust_id.customer_name }}</td>
<td>{{ order.order_id.invoice_number }}</td>
<td>{{ order.order_id.invoice_creation_date }}</td>
<td>{{ order.product_id.price }}</td>
</tr>
{% endfor %}

If-statement in Django Template does not work

I playing around with a simple addressbook application and I'd like to show the company of a contact in a DetailView of a contact.
In my template:
<table class="table table-bordered table-condensed" style="width:50%;">
{% for company in companies %}
{% if company.name == contact.company %}
<tr>
<td>{{ company.name }}</td>
<td>{{ company.street }}</td>
<td>{{ company.plz }}</td>
<td>{{ company.city }}</td>
</tr>
{% endif %}
{% endfor %}
</table>
My view:
class ContactView(DetailView):
model = Contact
template_name = 'contact.html'
def get_context_data(self, **kwargs):
context = super(DetailView, self).get_context_data(**kwargs)
# Companies
context['companies'] = Company.objects.all()
# Return
return context
In my models:
class Company(models.Model):
name = models.CharField(max_length=255,)
and
class Contact(models.Model):
first_name = models.CharField(max_length=255, blank=True, null=True)
last_name = models.CharField(max_length=255,)
company = models.ForeignKey(Company, blank=True, null=True)
What is wrong with the if statement in my template?
Thanks for your help in advance!
You should compare the company itself, not the name.
Change
{% if company.name == contact.company %}
to
{% if company == contact.company %}

Categories

Resources