i want to fetch the item of related subcategories but i am unable to fetch the items from that subcategories it is showing me the error
AttributeError: 'Subcategories' object has no attribute 'item'
so here is my code
my models
class Subcategories(models.Model):
categories = models.ForeignKey(Categories, on_delete=models.CASCADE, related_name='our_categories')
name = models.CharField(max_length=200, blank=False)
joined_date = models.DateTimeField(default=timezone.now,editable=False)
update_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.name
class Item(models.Model):
categories = models.ForeignKey(Categories, on_delete=models.CASCADE,)
subcategories = models.ForeignKey(Subcategories, on_delete=models.CASCADE, related_name='products')
can_buy = models.ForeignKey(For, on_delete=models.CASCADE,)
name = models.CharField(max_length=200, blank=False)
contain_size = models.CharField(max_length=10, blank=True)
first = models.ImageField(upload_to='items', blank=False)
second = models.ImageField(upload_to='items', blank=True)
third = models.ImageField(upload_to='items', blank=True)
fourth = models.ImageField(upload_to='items', blank=True)
fifth = models.ImageField(upload_to='items', blank=True)
item_vedio = models.FileField(upload_to='item_vedio', blank=True)
offered_price = models.FloatField(blank=False,)
actual_price = models.FloatField(blank=False)
about = models.TextField(blank=False, default="about" )
offer = models.CharField(max_length=4, blank=True)
def __str__(self):
return self.name
my urls.py
urlpatterns = [
path('<int:subcategory_id>/products/',Product.as_view(),name='product' ),
]
my views.py
class Product(View):
def get(self, request,):
category_list = Categories.objects.all()
return render (request, 'products.html', {'category_list': category_list })
def get(self, request, subcategory_id):
subcategory = get_object_or_404(Subcategories, pk=subcategory_id)
products = subcategory.item.all()
return render (request, 'products.html',{"subcategory_list" : products })
any idea what causing the issue and thank you for your time
The related name is products for subcategories Foreign key in Item model.
subcategory.products.all()
Related
I have a listview where I'm trying to filter out products by category. Some products have a subcategory. When a product has a subcategory I want the listview to display them by subcategory.
Problem is: The listview works perfect for items with a subcategory, but does not work for items who do not have a subcategory. Where am I taking a wrong turn here?
Models:
class Category(models.Model):
category_name = models.CharField(max_length=200)
sub_category = models.CharField(max_length=200,blank=True,null=True)
category_picture = ResizedImageField(upload_to='category/', null=True, blank=True)
category_info = models.TextField(blank=True, null=True)
category_video = models.CharField(max_length=250,blank=True, null=True)
def __str__(self):
if self.sub_category is None:
return self.category_name
else:
return f" {self.sub_category}"
class Meta:
ordering = ['category_name']
class Bottle(models.Model):
category_name = models.ForeignKey('Category', on_delete=models.SET_NULL,null=True,blank=True)
brand = models.ForeignKey('Brand', on_delete=models.CASCADE)
bottle_name = models.CharField(max_length=255)
bottle_info = models.TextField()
bottle_tasting_notes = models.TextField()
bottle_barcode = models.IntegerField()
bottle_image = ResizedImageField(upload_to='bottles/',null=True, blank=True)
bottle_shop_link = models.CharField(max_length=250, null=True, blank=True)
def __str__(self):
return f"{self.brand}, {self.bottle_name}"
class Meta:
ordering = ['bottle_name']
View:
class BottlesByCategoryView(ListView):
model = Bottle
context_object_name = 'bottles'
#Filter bij subcategory in the category model. If no subcategory exists, load by category_name
def get_queryset(self):
if Bottle.objects.filter(category_name__sub_category=self.kwargs['category']) is None:
return Bottle.objects.filter(category_name__category_name=self.kwargs['category'])
else:
return Bottle.objects.filter(category_name__sub_category=self.kwargs['category'])
def get_context_data(self, **kwargs):
context = super(BottlesByCategoryView, self).get_context_data(**kwargs)
if Bottle.objects.filter(category_name__sub_category=self.kwargs['category']) is None:
context['category_info'] = Category.objects.filter(category_name=self.kwargs['category'])
else:
context['category_info'] = Category.objects.filter(sub_category=self.kwargs['category'])
return context
URLS:
path('BottlesByCategory/<str:category>/',BottlesByCategoryView.as_view(template_name='academy/bottlesByCat_list.html'),name='bottlesByCat_list'),
Can i not use if statements in the get_context_data and get_query_set?
I am creating ecommerce website. There are multiple categories. For example, phones, computers and others. I created a model for each of them. In OrderItems I want to foreign key each of them. So, I want to use multiple models in ForeignKey.
models.py
class Telefon(models.Model):
name = models.CharField(max_length=200)
category = models.CharField(max_length=300, choices=TELEFON, default="xiaomi")
price = models.FloatField()
image = models.ImageField(null=True, blank=True)
def __str__(self):
return self.name
#property
def imageURL(self):
try:
url = self.image.url
except:
url = ''
return url
class TV(models.Model):
name = models.CharField(max_length=200)
category = models.CharField(max_length=300, choices=TELEFON, default="xiaomi")
price = models.FloatField()
image = models.ImageField(null=True, blank=True)
def __str__(self):
return self.name
#property
def imageURL(self):
try:
url = self.image.url
except:
url = ''
return url
Product={'Telefon', 'TV'}
class OrderItem(models.Model):
product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True)
order = models.ForeignKey(Order, on_delete=models.SET_NULL, 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
So, how can I use multiple models in Foreign Key field in my OrderItems model.
Meanwhile using "view count" in my ecommerce project showing this error ('QuerySet' object has no attribute 'view_count')
views.py
class ProductDetailView(TemplateView):
template_name = 'product-detail-view.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
slug_url = self.kwargs['slug']
product = Product.objects.filter(slug=slug_url)
product.view_count += 1
product.save()
context["products"] = product
return context
models.py
class Product(models.Model):
title = models.CharField(max_length=200)
slug = models.SlugField(unique=True)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
image = models.ImageField(upload_to='products_img')
wholesale_rate = models.PositiveIntegerField()
amazon_rate = models.PositiveIntegerField()
description = models.TextField()
warranty = models.CharField(max_length=200, null=True, blank=True)
return_policy = models.CharField(max_length=200, null=True, blank=True)
view_count = models.PositiveIntegerField(default=0)
product = Product.objects.filter(slug=slug_url)
This return a queryset, not an object so you cannot access object field like this. Either use .first() to get an object or if you want to update all objects in queryset, then use
product.update(view_count = F('view_count') + 1)
I need to filter a model by two values that none of them is the PK of the model.
I want to filter the payments for an specific car and week, this means that I can have more than one payment for a car and in a week.
I'm using Django-Tables2 to display the results.
views.py
class PagosDetailView(SingleTableMixin, DetailView):
template_name = "AC/paymentsbycarandweek.html"
context_table_name = 'table'
model = Pagos
table_class = PagosTable
slug_url_kwarg = 'carro_id'
def get_queryset(self):
qs = super(PagosDetailView, self).get_queryset()
return qs.filter(carro=self.kwargs['carro'], semana=self.kwargs['semana'])
models.py
class Pagos(models.Model):
carro = models.ForeignKey(
Carros, on_delete=models.CASCADE, blank=False, null=False)
pago = models.DecimalField(max_digits=6, decimal_places=2)
fecha = models.DateField(
auto_now=False, auto_now_add=False, blank=True, null=True)
semana = models.CharField(max_length=20)
startweek = models.DateField(
auto_now=False, auto_now_add=False, blank=True, null=True)
endweek = models.DateField(
auto_now=False, auto_now_add=False, blank=True, null=True)
renta = models.ForeignKey(
Renta, on_delete=models.PROTECT, blank=False, null=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
verbose_name_plural = "Pagos"
def get_absolute_url(self):
return reverse('pagos')
def __str__(self):
return self.semana
urls.py
path('paymentsbycarandweek/<int:carro>/<slug:semana>',
views.PagosDetailView.as_view(), name='pagos_bycar')
This last time that I have tried several options, I'm getting the following error message:
Generic detail view PagosDetailView must be called with either an object pk or a slug in the URLconf.
How exactly can I pass these two parameters?
After searching a lot, this is how I finally resolved it:
class PagosDetailView(SingleTableMixin, ListView):
model = Pagos
table_class = PagosDetailTable
template_name = 'AC/paymentsbycarandweek.html'
paginate_by = 10
def get(self, request, *args, **kwargs):
self.object_list = self.get_queryset()
self.object_list = self.object_list.filter(
carro=kwargs['carro'], semana=kwargs['semana'])
context = self.get_context_data()
return self.render_to_response(context)
I'm trying to build a basic ecommerce website, as a mean to learning django. I'm trying to build my models, so that there is a Category, a Product and Product Image class to store my data in. This is my models.py:
class Category(models.Model):
name = models.CharField(max_length=200, db_index=True)
slug = models.SlugField(max_length=200, db_index=True, unique=True)
class Meta:
ordering = ('name', )
verbose_name = 'category'
verbose_name_plural = 'categories'
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('products:product_list_by_category', args=[self.slug])
class Product(models.Model):
category = models.ForeignKey(Category, related_name='products')
name = models.CharField(max_length=200, db_index=True)
slug = models.SlugField(max_length=200, db_index=True)
description = models.TextField(blank=True)
price = models.DecimalField(max_digits=10, decimal_places=2)
stock = models.PositiveIntegerField()
available = models.BooleanField(default=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
ordering = ('name', )
index_together = (('id', 'slug'), )
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('products:product_detail', args=[self.id, self.slug])
class ProductImage(models.Model):
property = models.ForeignKey('Product', related_name='images', on_delete=models.CASCADE)
image = models.ImageField(upload_to='products')
And this is my views.py:
def product_list(request, category_slug=None):
category = None
categories = Category.objects.all()
products = Product.objects.filter(available=True)
product_img = Product.images.all()
if category_slug:
category = get_object_or_404(Category, slug=category_slug)
products = products.filter(category=category)
return render(request, 'products/list.html', {'category': category, 'categories': categories, 'products': products, 'product_img': product_img})
I've seen similar post here on stack overflow, and have tried to do the same thing, but I still get the following error: AttributeError: 'ReverseManyToOneDescriptor' object has no attribute 'all'
Where am I going wrong here?