I am creating an e-commerce website in django where the homepage can be changed dynamically by changing the instances of FeaturedProduct objects. These objects have two ForeignKeys. First is to the Product class and the other is to FeaturedCategory class(this is for the type of deal, eg: daily deals, new arrivals, etc). So, I'm trying to get the Product instances in a queryset instead of the FeaturedProduct queryset. When I union two querysets, I get an error that 'Product' object has no attribute '_combinator_query'. The codes have been shown below.
My models.py
class Product(models.Model):
product_id = models.AutoField
product_name = models.CharField(max_length=50, unique=True)
category = models.ForeignKey(Category, on_delete=models.SET_DEFAULT, default='1')
sub_category = models.ForeignKey(SubCategory, on_delete=models.SET_DEFAULT, default='2')
price = models.IntegerField(default=0)
stock = models.IntegerField(default=0)
desc = models.TextField()
pub_date = models.DateField()
avg_rating = models.IntegerField(default=0)
avg_rating_float = models.FloatField(default=0.0)
number_of_ratings = models.IntegerField(default=0)
image1 = models.ImageField(upload_to="images", default="")
image2 = models.ImageField(upload_to="images", default="")
image3 = models.ImageField(upload_to="images", default="")
slug = models.SlugField(blank=True, help_text=('Leave this parameter empty, it will get generated automatically.'))
def save(self, *args, **kwargs):
self.slug = slugify(self.product_name)
super(Product, self).save(*args, **kwargs)
def __str__(self):
return self.product_name
class FeaturedCategory(models.Model):
category = models.CharField(max_length=100)
def __str__(self):
return self.category
class Meta:
verbose_name_plural = "Featured Categories"
class FeaturedProduct(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
featured_category = models.ForeignKey(FeaturedCategory, on_delete=models.CASCADE)
def __str__(self):
return self.product.product_name
My views.py
def index(request):
prod = Product.objects.none()
feat = FeaturedProduct.objects.all()
for pro in feat:
ob = Product.objects.get(product_name=pro.product)
print(ob.product_name)
print(ob.category)
print(ob.sub_category)
print(ob.price)
prod.union(ob) # Error found here
# Working part
products = Product.objects.all()
context = {'products': products}
return render(request, 'index.html', context)
The last three lines are working fine, but not the other part of the index function.
Please help. Thank You.
Related
i'm starting out with Django and trying to render all Shows(screenings) that selected Movie had. Here's the code:
url
path('movie/<int:pk>/', MovieDetails.as_view(), name='movie'),
Models
class Movie(models.Model):
title = models.CharField(max_length=200)
description = models.CharField(max_length=255, blank=True)
def __str__(self):
return f'{self.title}'
class Show(models.Model):
show_date = models.DateField()
start_time = models.TimeField()
movie = models.ForeignKey(Movie, on_delete=models.CASCADE, null=True, blank=True)
city = models.ForeignKey(City, on_delete=models.CASCADE, null=True, blank=True)
title = models.CharField(max_length=200, blank=True)
def __str__(self):
return f'{self.show_date}'
View
class MovieDetails(DetailView):
model = Movie
context_object_name = 'movie'
def get_queryset(self):
self.movie = get_object_or_404(Movie, id=self.kwargs['pk']) #find movie by id from url
shows_played = Show.objects.filter(movie=self.movie)
print(shows_played) #prints out some shows
return shows_played
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['shows_played'] = Show.objects.filter(movie=self.movie)
return context
The shows_played prints out some shows, so it seems like everything is fine but when the url: /movies/1
is called I get a 404, No show found matching the query rendered in browser and
Not Found: /movie/1/ printed in console
What am i doing wrong?
Thank you
I figured it out. My mistake was that i was using DetailView instead of ListView(which has get_queryset method) for "MovieDetails".
i am trying to create a blog by the admin panell. but i am not able to save. Can you please help.
Model.py
class blog(models.Model):
author = models.ForeignKey(User, null=True, on_delete=models.CASCADE)
city_id = models.AutoField(primary_key=True)
blog_title=models.CharField(max_length=200)
created_at = models.DateTimeField(auto_now_add=True)
slug = models.CharField(max_length=500, blank=True)
tags = TaggableManager()
blog_category_name=models.ForeignKey(blog_category,on_delete=models.CASCADE,null=True,blank=True)
blog_sub_category_name=models.ForeignKey(blog_sub_category,on_delete=models.CASCADE,null=True,blank=True)
written_by = models.CharField(max_length=200, default='sandeep')
image_banner= models.ImageField(upload_to='image_banner')
medium_thumbnail = models.ImageField(upload_to='medium_thumbnail')
content = RichTextField() # RichTextField is used for paragraphs
is_authentic=models.BooleanField(default=False)
class Meta: # Plurizing the class name explicitly
verbose_name_plural = 'blog'
def __str__(self): # Dundar Method
return self.blog_title
def save(self, *args, **kwargs): # Saving Modefied Changes
if not self.slug:
self.slug = slugify(self.blog_title)
view.py
def tags(request,tags):
blogs = blog.objects.filter(
Q(blog_title__icontains = tags.replace('-',' ')) |
Q(content__icontains = tags.replace('-',' '))
)
print(tags)
return render(request, 'services/blog-with-sidebar.html',
{'blogs': blogs,'media_url':settings.MEDIA_URL})
For some reason when I'm trying to save the tags and the data I'm getting this error:
Django 'CategorisedListView' object has no attribute 'slug' or Page not found (error 404) issue
I'm on Django 2.0, using generic class list view. I have tried dynamic url based on slug and queryset filter on slug to get list of charts by category.
Please help! I've been stuck here for a couple of days since.
views.py
class CategoriesView(generic.ListView):
template_name = 'Bokeh/categories.html'
context_object_name = 'all_categories'
def get_queryset(self):
return Category.objects.all()
class CategorisedListView(generic.ListView):
model = Category
template_name = 'categories/list_of_charts_by_category.html'
context_object_name = 'categorised'
def get_queryset(self):
self.category = get_object_or_404(Category, name = self.kwargs['slug'])
return Chart.objects.filter(category=self.slug)
models.py
class Category(models.Model):
name = models.CharField(max_length=100)
image_file = models.ImageField(default=None, unique=True)
slug = models.SlugField(max_length=100, unique=True)
parent = models.ForeignKey('self', on_delete=models.PROTECT, blank=True, null=True, related_name='children')
def __str__(self):
return self.name
def get_absolute_url(self):
return '{slug}/'.format(slug=self.slug)
class Meta:
ordering = ('name',)
verbose_name = 'Category'
verbose_name_plural = 'Categories'
class Chart(models.Model):
name = models.CharField(max_length=250)
slug = models.SlugField(max_length=250, unique=True)
description = models.TextField(max_length=250)
url = models.URLField(default=None, blank=True)
embed_url = models.TextField(default=None, blank=True)
image_file = models.ImageField(default=None, unique=True)
code_file = models.FileField(default=None, blank=True, unique=True)
chart_library = models.CharField(max_length=250)
author = models.ForeignKey(User, on_delete=models.CASCADE, default=1)
tag = TaggableManager()
category = models.ForeignKey(Category, on_delete=models.CASCADE, blank=True, null=True)
def __str__(self):
return self.name + ' - ' + self.chart_library
def get_absolute_url(self):
return reverse('Bokeh:detail', kwargs={'pk': self.pk})
def read_file(self):
data = self.code_file.path
with open(self.code_file.path, 'r', encoding='UTF-8') as data:
content = data.read()
return content
class Meta:
ordering = ('name',)
urls.py
path("categories/", views.CategoriesView.as_view(), name='categories'),
# /Bokeh/categories/<category_slug>
path("categories/<slug:slug>/", views.CategorisedListView.as_view(), name='list_of_charts_by_category'),
it is supposed to query the database when a specific category is clicked and return the list of charts categorised under that specific category. However, the page throws 'CategorisedListView' object has no attribute 'slug'
The lookup you're doing in get_queryset() isn't quite right. Firstly, you seem to be looking up the Category by name rather than by the slug. Then you try and filter the Charts using their category attribute, but instead of passing the category you pass a non-existent attribute self.slug.
Try changing the implementation to this:
def get_queryset(self):
# Lookup the Category using it's slug attribute, not name, and assign to local variable
category = get_object_or_404(Category, slug=self.kwargs['slug'])
# Now lookup the Charts using the category we just looked up
return Chart.objects.filter(category=category)
I'm working with a ManyToManyField and using a ModelMultipleChoice on form, I want to get the entries, but all I get is appname.Extra.none
models.py
class Extra(models.Model):
extra_n = models.CharField(max_length=200)
extra_price = models.IntegerField(default=0)
def __str__(self):
return self.extra_n
class Meal(models.Model):
restaurant = models.ForeignKey(Restaurant, on_delete=models.PROTECT)
category = models.ForeignKey(MealCategory, on_delete=models.PROTECT)
name = models.CharField(max_length=500)
short_description = models.CharField(max_length=500)
image = models.ImageField(upload_to='meal_images/', blank=False)
price = models.IntegerField(default=0)
extras = models.ManyToManyField(Extra, related_name='extras')
def __str__(self):
return self.name
forms.py
class MealForm(forms.ModelForm):
extras = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple(), queryset=Meal.extras)
class Meta:
model = Meal
exclude = ("restaurant",)
views.py
def restaurant_meal(request):
meals = Meal.objects.filter(restaurant = request.user.restaurant).order_by("-id")
return render(request, 'restaurant/meal.html', {"meals": meals})
The output desired is getting the extras added displayed on restaurant_meal view.
you can try change
meals = Meal.objects.filter(restaurant = request.user.restaurant).order_by("-id")
to
meals = Meal.objects.filter(restaurant = request.user.restaurant).prefetch_related('extras').order_by("-id")
and try again.
Doc of this in prefetch_related
I am working on a blog like project but different and I have recently started learning Django. So, in my app we have categories and tags as well. Now there's an Entry model which has ManyToMany relation with both Category and Tag. Now I am trying to get all the Entries which falls under a particular category, it's a similar feature that we have in blogs.
Following is my Tag and Category Model.
class CategoryQuerySet(models.QuerySet):
def category_menu(self):
return self.filter(intopmenu=True)
def top_catgories(self):
return self.order_by("views")[:5]
class Category(models.Model):
name = models.CharField(max_length=50, unique=True)
views = models.IntegerField(default=0)
intopmenu = models.BooleanField(default=False)
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
slug = models.SlugField(unique=True)
objects = CategoryQuerySet.as_manager()
def save(self, *args, **kwargs):
self.slug = slugify(self.name)
super(Category, self).save(*args, **kwargs)
def __str__(self):
return self.name
class Meta:
verbose_name = "Entry Category"
verbose_name_plural = "Entry Categories"
ordering = ["created"]
class Tag(models.Model):
name = models.CharField(max_length=20)
slug = models.SlugField(max_length=200, unique=True)
def __str__(self):
return self.slug
Following is my Entry Model.
class EntryQuerySet(models.QuerySet):
def published(self):
return self.filter(publish=True)
def most_liked(self, num):
return self.order_by("-likes")[:num]
def most_views(self, num):
return self.order_by('-views')[:num]
class Entry(models.Model):
image = models.ImageField(upload_to='entries_images/', null=True)
image_alt = models.CharField(max_length=200, blank=True)
name = models.CharField(max_length=50, blank=True)
text = models.CharField(max_length=500, unique=True)
views = models.IntegerField(default=0)
likes = models.IntegerField(default=0)
publish = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
source = models.URLField(blank=True)
slug = models.SlugField(unique=True)
categories = models.ManyToManyField(Category)
tags = models.ManyToManyField(Tag)
objects = EntryQuerySet.as_manager()
def save(self, *args, **kwargs):
self.slug = slugify(self.name)
super(Entry, self).save(*args, **kwargs)
def __str__(self):
return self.text
class Meta:
verbose_name = "Entry"
verbose_name_plural = "Entries"
ordering = ["created"]
In my urls.py I have the following url to view all entries by that fall under a particular category.
url(r'^category/(?P<category_slug>[\w\-]+)/$', views.category, name='category'),
Apparently, I don't understand how to write the view to retrieve list of all the entries falling under particular category or tag. Any help will be appreciated. I did refer many blog posts on the web regarding my problem and also searched SO, 1 is a similar question I found but that didn't help much.
try:
def category(request,category_slug):
category = get_object_or_404(Category,slug=category_slug)
return render(request,'template_name.html',{'category':category,'posts':category.entry_set.all()})
More information on https://docs.djangoproject.com/en/1.9/topics/db/examples/many_to_many/