How can I separate categories in different pages in Python and Django?
I need help with my e-commerce website project. I will have 5 categories in the dropdown menu. I want to see different categories on different pages when I click on a category in a dropdown menu. Now I see all products on the home page and when I click on a category as BOOKS I see books on the home page but I don't want it. I want to use the home page for ads and when I click on a category, I want to see it on a different page. How can I separate them?
My models:
class Category(models.Model):
name = models.CharField(max_length=250, unique=True)
slug = models.SlugField(max_length=250, unique=True)
description = models.TextField(blank=True)
class Meta:
ordering = ('name',)
verbose_name = 'category'
verbose_name_plural = 'categories'
def get_url(self):
return reverse('products_by_category', args=[self.slug])
def __str__(self):
return str(self.name)
# Model: Product
# Model: Cart
class Add(models.Model):
image = models.ImageField(upload_to='add', blank=True)
image1 = models.ImageField(upload_to='add', blank=True)
image2 = models.ImageField(upload_to='add', blank=True)
class Meta:
verbose_name = 'add'
verbose_name_plural = 'adds'
def __str__(self):
return str(self.image)
class Product(models.Model):
name = models.CharField(max_length=250, unique=True)
slug = models.SlugField(max_length=250, unique=True)
description = models.TextField(blank=True)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
price = models.DecimalField(max_digits=10, decimal_places=2)
image = models.ImageField(upload_to='product', blank=True)
image1 = models.ImageField(upload_to='product', blank=True)
image2 = models.ImageField(upload_to='product', blank=True)
image3 = models.ImageField(upload_to='product', blank=True)
stock = models.IntegerField()
available = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Meta:
ordering = ('name',)
verbose_name = 'product'
verbose_name_plural = 'products'
def get_url(self):
return reverse('product_detail', args=[self.category.slug, self.slug])
def __str__(self):
return str(self.name)
# Model: Cart
class Cart(models.Model):
cart_id = models.CharField(max_length=250, blank=True)
date_added = models.DateField(auto_now_add=True)
class Meta:
db_table = 'Cart'
ordering = ['date_added']
My View:
def home(request, category_slug=None):
category_page = None
products_list = None
if category_slug != None:
category_page = get_object_or_404(Category, slug=category_slug)
products_list = Product.objects.filter(category=category_page, available=True)
else:
products_list = Product.objects.all().filter(available=True)
paginator = Paginator(products_list, 8)
try:
page = int(request.GET.get('page', '1'))
except:
page = 1
try:
products = paginator.page(page)
except(EmptyPage, InvalidPage):
products = paginator.page(paginator.num_pages)
return render(request, 'home.html', {'category': category_page, 'products': products})
def productPage(request, category_slug, product_slug):
try:
product = Product.objects.get(category__slug=category_slug, slug=product_slug)
except Exception as e:
raise e
if request.method == 'POST' and request.user.is_authenticated and request.POST['content'].strip() != '':
Review.objects.create(product=product,
user=request.user,
content=request.POST['content'])
reviews = Review.objects.filter(product=product)
return render(request, 'product.html', {'product': product, 'reviews': reviews})
def _cart_id(request):
cart = request.session.session_key
if not cart:
cart = request.session.create()
return cart
def add_cart(request, product_id):
product = Product.objects.get(id=product_id)
try:
cart = Cart.objects.get(cart_id=_cart_id(request))
except Cart.DoesNotExist:
cart = Cart.objects.create(
cart_id=_cart_id(request)
)
cart.save()
try:
cart_item = CartItem.objects.get(product=product, cart=cart)
if cart_item.quantity < cart_item.product.stock:
cart_item.quantity += 1
cart_item.save()
except CartItem.DoesNotExist:
cart_item = CartItem.objects.create(
product=product,
quantity=1,
cart=cart
)
cart_item.save()
return redirect('cart_detail')
My URL :
urlpatterns = [
path('', views.home, name='home'),
path('category/<slug:category_slug>', views.home, name='products_by_category'),
path('category/<slug:category_slug>/<slug:product_slug>', views.productPage, name='product_detail'),
path('cart/add/<int:product_id>', views.add_cart, name='add_cart'),
path('cart', views.cart_detail, name='cart_detail'),
path('cart/remove/<int:product_id>', views.cart_remove, name='cart_remove'),
path('cart/remove_product/<int:product_id>', views.cart_remove_product, name='cart_remove_product'),
path('thankyou/<int:order_id>', views.thanks_page, name='thanks_page'),
path('account/create/', views.signupView, name='signup'),
path('account/signin/', views.signinView, name='signin'),
path('account/signout/', views.signoutView, name='signout'),
path('order_history/', views.orderHistory, name='order_history'),
path('order/<int:order_id>', views.viewOrder, name='order_detail'),
path('search/', views.search, name='search'),
Product selecter:
<!-- ALL PRODUCRS -->
<div class="container-fluid">
<div class="py-4">
<div class="container">
<div class="row">
<div class="col-8 mx-auto my-2 text-center">
<a href="{% url 'allproducts' %}">
<h4 class="text-captitalze font-weight-bold">
</h4>
</a>
</div>
</div>
</div>
</div>
<div class="container">
<div class="row">
{% for product in products %}
<div class="col-9 mx-auto col-md-4 col-lg-3">
<div class="card mb-4" style="border-color: transparent;">
<div class="p-3">
<a href="{{product.get_url}}">
<img src="{{product.image.url}}" class="card-img-top" alt="{{product.name}}">
</a>
</div>
<div class="card-footer justify-content-between"
style="background: transparent;
border: transparent;
text-overflow: ellipsis;
word-wrap: break-word;
overflow: hidden;
max-height: 3.9em;
line-height: 1.0em;">
<p>
<span>{{product.name}}</span>
</p>
<hr>
</div>
<hr>
<h5>
<span class="mr-1">$</span> {{product.price}}
</h5>
</div>
</div>
{% endfor %}
</div>