I am building menu items for Irvine class and want to categorize them by Category
models.py
class Irvine(models.Model):
objects = None
name = models.CharField(max_length=50, verbose_name='Irvine Item')
description = models.TextField(null=True, blank=True)
size = models.FloatField(null=True, blank=True)
price = models.FloatField(null=True, blank=True)
published = models.DateTimeField(auto_now_add=True, db_index=True)
category = models.ForeignKey('Category', null=True, on_delete=models.PROTECT, verbose_name='Category')
def __str__(self):
return self.name
class Meta:
verbose_name_plural = 'Irvine'
verbose_name = 'Irvine Item'
ordering = ['-published']
class Category(models.Model):
objects = None
name = models.CharField(max_length=30, db_index=True, verbose_name="Category")
published = models.DateTimeField(auto_now_add=True, db_index=True)
def __str__(self):
return self.name
class Meta:
verbose_name_plural = '* Categories'
verbose_name = 'Category'
ordering = ['name']
view.py
def irvine(request):
irvine = Irvine.objects.all()
context = {'irvine': irvine}
return render(request, 'cafe/irvine.html', context)
def by_category(request, category_id):
santaanna = SantaAnna.objects.filter(category=category_id)
costamesa = CostaMesa.objects.filter(category=category_id)
irvine = Irvine.objects.filter(category=category_id)
categories = Category.objects.all()
current_category = Category.objects.get(pk=category_id)
context = {'santaanna': santaanna, 'categories': categories, 'costamesa': costamesa, 'irvine': irvine, 'current_category': current_category}
return render(request, 'cafe/by_category.html', context)
urls.py
urlpatterns = [
path('add/', ItemsCreateView.as_view(), name='add'),
path('<int:category_id>/', by_category, name='by_category'),
path('', index, name='index'),
path('irvine', irvine),
with
{% for i in irvine %}
{}
<tr class="danger">
<th scope="row" width="20%">{{ i.name }}</th>
<td width="60%">{{ i.description }}</td>
<td width="10%">{{ i.size }}</td>
<td width="10%">{{ i.price }}</td>
</tr>
{% endfor %}
I can grab all items from class Irvine, but how do i get items from this class by category
You can't directly check using i.category because it has list of values.
Try using i.category.name.
If you have serializer, please update the full code.
{% for i in irvine %} {% if i.category.name == 'Appetizers' %}, it will work
Related
I'm trying to get cart total sum of products in the html template, while the the total sum of particular products works fine, the cart total price/quantity shows blank spaces.
Models:
from django.db import models
import Accounts.models as accounts_models
import Products.models as products_models
class Order(models.Model):
customer = models.ForeignKey(accounts_models.Customer, on_delete=models.SET_NULL, blank=True, null=True)
date_ordered = models.DateTimeField(auto_now_add=True)
complete = models.BooleanField(default=False)
transaction_id = models.CharField(max_length=100, null=True)
def __str__(self):
return str(self.id)
#property
def get_cart_total(self):
orderproducts = self.orderproduct_set.all()
total = sum([product.get_total for product in orderproducts])
return total
#property
def get_cart_products(self):
orderproducts = self.orderproduct_set.all()
total = sum([product.quantity for product in orderproducts])
return total
class OrderProduct(models.Model):
product = models.ForeignKey(products_models.Products, on_delete=models.SET_NULL, blank=True, null=True)
order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True)
quantity = models.IntegerField(default=0, null=True, blank=True)
date_added = models.DateTimeField(auto_now_add=True)
#property
def get_total(self):
total = self.product.price * self.quantity
return total
views:
def cart(request):
if request.user.is_authenticated:
customer = request.user.customer
order, created = Order.objects.get_or_create(customer=customer, complete=False)
items = order.orderproduct_set.all()
else:
items = []
context = {'items': items}
return render(request, 'cart.html', context)
html template:
{% for item in items %}
<tr>
<td>{{ item.product.name }}</td>
<td>{{ item.quantity }}</td>
<td>${{ item.product.price }}</td>
<td>${{ item.get_total }}</td>
</tr>
{% endfor %}
<tr>
<td colspan="3"><strong>Total:</strong></td>
<td>${{ order.get_cart_total }}</td>
</tr>
How can I start showing the total numbers in the html template?
You didn't pass order in your cart view, here is updated view:
def cart(request):
if request.user.is_authenticated:
customer = request.user.customer
order, created = Order.objects.get_or_create(customer=customer, complete=False)
items = order.orderproduct_set.all()
else:
items = []
order = None # Add this line to handle the case when there is no order
context = {'items': items, 'order': order} # Add the order object to the context dictionary
return render(request, 'cart.html', context)
I have two classes in django:
class MovementsGyn(models.Model):
gyn_name = models.CharField('Name', max_length=70)
gyn_desc = models.TextField('Description', blank=True, null=True)
owner = models.ForeignKey(User, on_delete=models.CASCADE)
class Meta:
ordering = ['id']
class Rod(models.Model):
Rod_name = models.CharField('Rod Name', max_length=70)
movements_gym = models.ManyToManyField(MovementsGyn)
owner = models.ForeignKey(User, on_delete=models.CASCADE)
class Meta:
ordering = ['id']
And a view to show the result grouped:
def estatistica(request):
template = 'moviment.html'
estatic_movem_gyn = Rod.objects.filter(owner=request.user) \
.values('movements_gym__gyn_name').order_by('movements_gym__gyn_name') \
.annotate(qtde=Count('id'))
context = {
'estatic_movem_gyn' : estatic_movem_gyn
}
return render(request, template_name, context)
The result, in Postgress, is gyn_name grouped and, in qtde, the quantity of register that we have in database.
But i'm havving problema to show it in HTML:
{% for estatic_movem_gyn in estatic_movem_gyn %}
<tr>
<td>{{ estatic_movem_gyn.gyn_name }}</td>
<td>{{ estatic_movem_gyn.qtde }}</td>
</tr>
{% endfor %}
The qtde appears but HTML doesn't show gyn_name.
I have a problem in django reverse many to many. Basically, I think I am missing something that I couldn't understand properly yet.
I have these models and views.
models.py
class TheorySyllabus(models.Model):
name = models.CharField(max_length=100, null=True, blank=True)
subject_duration = models.ManyToManyField(
SubjectDuration, related_name='subject_durations')
course_type = models.ForeignKey(
CourseType, on_delete=models.DO_NOTHING, null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.name
class Meta:
verbose_name_plural = 'Theory Syllabus'
class TheoryCourse(models.Model):
name = models.CharField(max_length=100)
student = models.ManyToManyField(Student, related_name='theory_courses')
theory_syllabus = models.ForeignKey(
TheorySyllabus, on_delete=models.DO_NOTHING, null=True, blank=True)
is_active = models.BooleanField(default=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.name
class Student(models.Model):
user = models.OneToOneField(CustomUser, on_delete=models.CASCADE)
first_name = models.CharField(max_length=200)
last_name = models.CharField(max_length=200)
date_of_birth = models.DateField()
fiscal_code = models.CharField(max_length=50)
phone = models.CharField(max_length=50)
license = models.ForeignKey(
License, on_delete=models.PROTECT, blank=True, null=True)
picture = models.ImageField(
blank=True, null=True, default='default.png')
id_card = models.ForeignKey(
IDCard, on_delete=models.PROTECT, blank=True, null=True)
address = models.CharField(max_length=100)
cap = models.CharField(max_length=10)
city = models.CharField(max_length=100)
province = models.CharField(max_length=100)
country = models.CharField(max_length=100)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
is_active = models.BooleanField(default=True)
def __str__(self):
return self.user.first_name + ' ' + self.user.last_name
views.py
class CourseListView(ListView):
model = TheoryCourse
queryset = TheoryCourse.objects.filter(
is_active=True).order_by('-created_at')
template_name = 'theory/course_list.html'
context_object_name = 'theory_courses'
paginate_by = 10
template
<div class="card-body table-responsive p-0">
<table class="table table-hover text-nowrap table-bordered">
<thead>
<tr>
<th>Course Type</th>
<th>Course Name</th>
</tr>
</thead>
<tbody>
{% for course in theory_courses %}
<tr>
<td>{{course.theory_syllabus.name}}</td>
<td>{{course.name}}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
What I need to do, is to retrieve the total number of students that are in each TheoryCourse model. But I really have no idea how to use the reverse relationship.
I tried to use that in the template with something like:
{% for student in theory_courses.students.all %}
{% endfor %}
But, it's not working. I read all the django documentation but either I didn't understand something or I am doing something wrong.
Any help would be appreciated
So, you have student in your model, not students. Thus for will look something like this
{% for student in theory_courses.student.all %}
{% endfor%}
Furthermore, if you want to get only count, you can just use
{% for student_count in theory_courses.student.count %}
{% endfor %}
P.S. That has nothing to do with reverse (related_name) in many to many. related name just means that you can access your TheoryCourse model from Student with Student.theory_courses
I have an app for a shopping list, and I want to display values from my ingredients ManyToManyField but what I am getting instead is the name of the recipe that I created.
Could you please advise me on how to correctly do it?
models.py
class Ingredients(models.Model):
name=models.CharField(max_length=100, default='-', blank=True, unique=True)
class Meta:
ordering = ('name',)
verbose_name = 'składnik'
verbose_name_plural = 'składniki'
def __str__(self):
return str(self.name)
class Category(models.Model):
name=models.CharField(max_length=250, default='-', blank=True, unique=True)
slug = models.SlugField(unique=True, blank=True)
class Meta:
ordering = ('name',)
verbose_name = 'kategoria'
verbose_name_plural = 'kategorie'
def get_absolute_url(self):
return reverse("kategoria", kwargs={"slug": self.slug})
def __str__(self):
return str(self.name)
class Recipe(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE, default='-')
name = models.CharField(max_length=400, blank=False, unique=False)
body = models.TextField(blank=True, default='')
ingredients = models.ManyToManyField(Ingredients)
category = models.ForeignKey(Category, on_delete=models.CASCADE, blank=True)
date_created = models.DateTimeField('Utworzono', default=timezone.now)
last_updated = models.DateTimeField('Ostatnia zmiana',auto_now=True)
when_to_eat = models.DateField('Kalendarz', default=timezone.now)
tags = TaggableManager()
slug = models.SlugField(unique=True, blank=True)
class Meta:
ordering = ('name',)
verbose_name = 'przepis'
verbose_name_plural = 'przepisy'
def get_absolute_url(self):
return reverse("przepis", kwargs={"slug": self.slug})
def __str__(self):
return str(self.name)
views.py
class RecipeListView(ListView):
model = Recipe
template_name ='recipe_list.html'
queryset = Recipe.objects.all()
urls.py
urlpatterns = [
path('przepisy/', views.RecipeListView.as_view(), name='recipe_list'),
path('przepis/<slug:slug>/', views.RecipeDetailView.as_view(), name='przepis'),
]
recipe_list.html
<p class="card-text">Składniki:<br>
{% for ingredient in object_list %}
<li>{{ingredient.name}}</li>
{% endfor %}
</p>
you should try something like this:
{% for ingredients in object_list %}
{% for ingredient in ingredients.name.all %}
<li>{{ingredient.name}}</li>
{% endfor %}
{% endfor %}
Try this:
<p class="card-text">Składniki:<br>
{% for recipe in object_list %}
{% for ingredient in recipe.ingredients.all %}
<li>{{ingredient.name}}</li>
{% endfor %}
{% endfor %}
</p>
As you want to get all name from your Ingredients model but you are using {{ingredient.name}} which will show you all name from your Recipe Model. You need to be write {{ingredient.ingredients.name}} So the code will be looke like this
<p class="card-text">Składniki:<br>
{% for ingredient in object_list %}
<li>{{ingredient.ingredients.name}}</li>
{% endfor %}
</p>
As you are using Recipe model in your ListView so when you are writing {{ingredient.name}} it's similar to like this Recipe Model > name when we are writing {{ingredient.ingredients.name}} it's similar to Recipe Model > ManyToManyField of ingredients > garbing name from Ingredients model
I'm building a shopping cart. In my shopping cart an item can be composed of other items. I need to display a set of items with their corresponding associated parts in a single template. I know how to show a single item with its corresponding parts in a template, but I can't seem to figure out how to show more than one item, each with its own list of included parts.
I have fiddled with every permutation of tags in the template file:
# checkout.html
{% for item in cart_items %}
<tr>
<td class="left">
{{ item.name }}
<ul>
{% for part in item.product.buildpart.part_set.all %}
<li>{{ part.name }}
{% endfor %}
</ul>
</td>
<td>${{ item.price }}</td>
<td>{{ item.quantity }}</td>
<td class="right">${{ item.lineItemTotal }}</td>
</tr>
{% endfor %}
Here is the vew that generates the template:
# views.py
def checkout(request):
cart_items = get_cart_items(request)
<snip>
return render(request, 'checkout.html', locals())
And here's the get_cart_items() function that returns all the items in the user's shopping cart:
# cart.py
def get_cart_items(request):
""" return all items from the current user's cart """
return CartItem.objects.filter(cart_id=get_cart_id(request))
Here's the CartItem model:
# models.py
class Item(models.Model):
cart_id = models.CharField(max_length=50)
quantity = models.IntegerField(default=1)
product = models.ForeignKey(PartModel, unique=False)
class Meta:
abstract = True
<snip>
class CartItem(Item):
date_added = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ['date_added']
verbose_name = "Cart Item"
<snip>
The 'product' field is a ForeignKey to the PartModel model:
# models.py
class PartModel(models.Model):
family = models.ForeignKey(PartFamily)
name = models.CharField("Model Name", max_length=50, unique=True)
slug = models.SlugField(help_text="http://www.Knowele.com/<b>*slug*</b>",
unique=True)
<snip>
buildpart = models.ManyToManyField('self', through='BuildPart',
symmetrical=False, related_name='+')
class Meta:
ordering = ['name']
verbose_name = "Product Model"
<snip>
The PartModel model has a ManyToMany relationship with itself through the buildpart field and the BuildPart model to facilitate the notion of catalog items that can be composed of other catalog items:
# models.py
class Build(models.Model):
build = models.ForeignKey(PartModel, related_name='+')
part = models.ForeignKey(PartModel, related_name='+')
quantity = models.PositiveSmallIntegerField(default=1)
class Meta:
abstract = True
unique_together = ('build', 'part')
def __unicode__(self):
return self.build.name + ' with ' + str(self.quantity) + ' * ' + \
self.part.family.make.name + ' ' + self.part.name
class BuildPart(Build):
pass
class Meta:
verbose_name = "Build Part"
I can't seem to make the necessary ForeignKey traversals in the template (listed above) in order to get all the parts associated with the user's items in the CartItem model. Is it something I'm not doing right in the template or am I not packaging up the right QuerySets in my view?
The second part of this issue is that once I get those parts, I need them to show up in the order specified in the 'order' integer field of the PartType model:
# models.py
class PartType(models.Model):
name = models.CharField("Part Type", max_length=30, unique=True)
slug = models.SlugField(unique=True)
order = models.PositiveSmallIntegerField()
description = models.TextField(blank=True, null=True)
class Meta:
ordering = ['name']
verbose_name = "Product Type"
def __unicode__(self):
return self.name
class PartFamily(models.Model):
make = models.ForeignKey(PartMake)
type = models.ForeignKey(PartType)
name = models.CharField("Family Name", max_length=30,
unique=True)
slug = models.SlugField(unique=True)
url = models.URLField("URL", blank=True, null=True)
description = models.TextField(blank=True, null=True)
class Meta:
ordering = ['name']
verbose_name = "Product Family"
verbose_name_plural = "Product Families"
def __unicode__(self):
return self.name
So as you can see, in the PartModel model, the 'family' field is a ForeignKey to the PartFamily model, and in the PartFamily model the 'type' field is a ForeignKey to the PartType model, within which is the all-important 'order' field that the parts need to be ordered by.
I hope this makes sense and you can see why this is so complicated for a noob like me.
Just iterate on item.product.buildpart.all:
{% for item in cart_items %}
[...]
{% for part in item.product.buildpart.all %}
{{ part.name }}[...]
{% endfor %}
{% endfor %}