problem with displaying ManyToMany Field in Dango templates - python

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

Related

prefetch_related in Django displaying all objects instad of related ones

I am trying to get a list of all categories and below each category the list of all related articles.
The problem is that I am getting the list of all articles under each category. I read documentation and few answers but nothing seems to be working and I am not sure where I am making the mistake.
models.py
class Category(models.Model):
title = models.CharField(max_length=75, default='', blank=False, null=False)
body = CharField(max_length=2000, default='', null=True, blank=True)
slug = models.SlugField(unique=True, blank=True)
publish = models.DateTimeField('publish', default=timezone.now)
class Meta:
ordering = ('-publish',)
verbose_name = 'category'
verbose_name_plural = 'categories'
get_latest_by = 'publish'
class Article(models.Model):
id = models.AutoField(primary_key=True)
author = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL) #settings INSTALLED_APPS
title = models.CharField('title', max_length=200)
body = CKEditor5Field('Body', config_name='extends')
last_updated = models.DateTimeField(auto_now=True)
publish = models.DateTimeField('publish', default=timezone.now)
#tags = TagField(required=False, widget=LabelWidget)
category = models.ForeignKey(Category, on_delete = models.CASCADE, blank=True, related_name='category')
slug = models.SlugField(unique=True, blank=True)
views.py
#login_required
def hal_home(request):
top_categories = Category.objects.all()[:3]
category_related_articles = Article.objects.prefetch_related('category').all()
context = {
'category_related_articles': category_related_articles
}
return render(request, 'hal/homepage.html', context)
homepage.html
{% for category in top_categories %}
<div class="btn btn-light text-center text-justify">
<div>{{ category.title }}</div>
</div>
<br>
<p>{% for article in category_related_articles %}
{{article.title}}<br>
{% endfor %}</p>
{% empty %}
<div>No categories</div>
{% endfor %}
You should use prefetch_related with your category queryset.
And also I would suggest you to change the related_name to articles since category.articles.all() seems more readable and easier than category.category.all() .
category = models.ForeignKey(Category, on_delete = models.CASCADE, blank=True, related_name='articles')
Now you can change some code in your views and templates.
top_categories = Category.objects.prefetch_related("articles").all()[:3]
context = {'top_categories': top_categories}
Now you can get articles by category in template with:
{% for category in top_categories %}
{{category.title}}
# articles of each category
{% for article in category.articles.all %}
{{article}}
{% endfor %}
{% endfor %}

Django: ValidationError ['ManagementForm data is missing or has been tampered with']

Django: ValidationError ['ManagementForm data is missing or has been tampered with'] i have been getting this error when i use the forminline factory module, im sorry if my question isnt placed properly, this is my first time here.
my form template is this:
{% extends 'accounts/main-form.html'%}
{% load static %}
{% block title %}
<title>CRM | Form</title>
{% endblock %}
{% block link %}
<link rel="stylesheet" type="text/css" href="{% static 'css/style1.css'%}">
{% endblock %}
{% block content %}
<div class="container">
<form action="" method="POST">
{{formset.management_form}}
{% for i in formset %}
{{i}}
{% endfor %}
<input type="submit" class="btn" value="submit">
</form>
</div>
{% endblock%}
this is the form code in views.py
def order_form(request, pk):
customers = Customer.objects.get(id=pk)
OrderFormSet = inlineformset_factory(Customer, Order, fields=('product', 'status',))
formset = OrderFormSet(request.POST)
if request.method == 'POST':
formset = OrderFormSet(request.POST, instance=customers)
if formset.is_valid():
formset.save()
return redirect('/')
context = {'formset': formset}
return render(request, 'accounts/order_form.html', context)
my models
from django.db import models
# Create your models here.
class Customer(models.Model):
name = models.CharField(max_length=200, null=True)
phone = models.CharField(max_length=200, null=True)
email = models.CharField(max_length=200, null=True)
date_created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.name
class Tag(models.Model):
name = models.CharField(max_length=200, null=True)
def __str__(self):
return self.name
class Product(models.Model):
CATEGORY = (
('Indoor', 'Indoor'),
('OutDoor', 'Outdoor')
)
name = models.CharField(max_length=200, null=True)
price = models.FloatField(null=True)
category = models.CharField(max_length=200, null=True, choices=CATEGORY)
description = models.CharField(max_length=200, null=True)
date_created = models.DateTimeField(auto_now_add=True)
tag = models.ManyToManyField(Tag)
def __str__(self):
return self.name
class Order(models.Model):
STATUS = (
('Pending', 'Pending'),
('Out for delivery', 'Out for delivery'),
('Delivered', 'Delivered')
)
customer = models.ForeignKey(Customer, null=True, on_delete= models.DO_NOTHING)
product = models.ForeignKey(Product, null=True, on_delete= models.DO_NOTHING)
date_created = models.DateTimeField(auto_now_add=True)
status = models.CharField(max_length=200, null=True, choices=STATUS)
def __str__(self):
return self.product.name
my form.py
from django.forms import ModelForm
from .models import Order
class Order_form(ModelForm):
class Meta:
model = Order
fields = ['product', 'status']

Uable to get the product name from the model

I've create 3 models for the Order processing. However, I couldn't show the product name on template for every single order. Does my for loop logic or 'get' method go wrong?
models.py:
class Product(models.Model):
product_name = models.CharField(max_length=200)
price = models.DecimalField(decimal_places=2, max_digits=10, blank=True)
created = models.DateTimeField(auto_now=True)
slug = models.SlugField(max_length=255, unique=True)
def __str__(self):
return self.product_name
class OrderItem(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True)
item = models.ForeignKey(Product, on_delete=models.CASCADE)
quantity = models.IntegerField(default=1)
ordered = models.BooleanField(default=False)
def __str__(self):
return f"{self.quantity} of {self.item.product_name}"
class Order(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True)
items = models.ManyToManyField(OrderItem)
start_date = models.DateTimeField(auto_now_add=True)
ordered = models.BooleanField(default=False)
def __str__(self):
return self.user.username
view.py:
def user_info(request):
orders = Order.objects.filter(user=request.user, ordered=True).order_by('-start_date')
context = {
'orders': orders,
}
return render(request, 'home.html', context)
home.html:
{% for order_item in orders.items.all %}
<p>{{ order_item.item.product_name }}</p>
{% endfor %}
You are passing orders from your view which is a queryset so you can't do orders.items.all. You should do a for loop to loop over orders and then get the items:
{% for order_item in orders %}
<p>product names for order id {{order_itme.id}}:</p>
{% for item in order_item.items.all %}
<p>{{ item.item.product_name }}</p>
{% endfor %}
{% endfor %}
Note that this will renders all items for all orders. You should filter the result if you just need one or some of them.

Finding the Cross-Section of two List views in one Django template

I have two models that feed one view.
models.py
class Item(models.Model):
item_name = models.CharField(max_length=100)
item_type = models.ForeignKey(Item_type, on_delete=models.SET_NULL, null=True)
owned_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True)****
added_at = models.DateTimeField('date item added')
updated_at = models.DateTimeField('last update')
def __str__(self):
return self.item_name
class Item_status(models.Model):
item = models.ForeignKey(Item, on_delete=models.SET_NULL, null=True)
borrower = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True)
loaned_at = models.DateTimeField(default=None, blank=True, null=True)
due_back = models.DateTimeField(default=None, blank=True, null=True)
def __time__(self):
return self.loaned_at
def itemname(self):
return (self.item.item_name)
I have the following view
views.py
class LoanedItemsByUserListView(LoginRequiredMixin,generic.ListView):
model = Item_status
template_name ='catalog/item_status_list_borrowed_user.html'
paginate_by = 10
def get_queryset(self):
return Item_status.objects.filter(borrower=self.request.user).order_by('due_back')
def get_context_data(self, **kwargs):
context = super(LoanedItemsByUserListView, self).get_context_data(**kwargs)
context['Owned_list'] = Item.objects.filter(owned_by=self.request.user, item_type = 1)
context['Loaned_list'] = Item_status.objects.exclude(borrower=self.request.user).exclude(borrower__isnull=True)
return context
I would like to find the cross section of the 'Owned_list' and the 'Loaned_list' in a single template
Something like
<h2>Loaned Books</h2>
{% if Owned_list %}
<ul>
{% for thing in Owned_list.item_name and in Loned_list.item.item_name %}
<li>
{{thing}}
</li>
{% endfor %}
</ul
{% else %}
<p>There are no books in the library.</p>
{% endif %}
I have take a look at the django documentation here https://docs.djangoproject.com/en/1.11/topics/class-based-views/generic-display/, and around SO but not found exactly what I am looking for.
Thanks!

Django Multiple ForeignKey Navigation

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 %}

Categories