Answer the question
In order to leave comments, you need to log in
How to make a url from two slugs?
There are category and product models. It is necessary that the product url consists of a category slug and its own slug. This should look like 'category/slug category/product slug/'.
models.py
class Category(models.Model):
title = models.CharField(max_length=155, verbose_name='Название категории')
icon = models.ImageField(upload_to='img/category', blank=True, null=True, verbose_name='Картинка категории')
slug = models.SlugField(unique=True, verbose_name='Слаг категории')
def get_absolute_url(self):
return reverse('category', kwargs={"slug": self.slug})
def __str__(self):
return self.title
class Product(models.Model):
title = models.CharField(max_length=155, verbose_name='Название товара')
description = models.TextField(blank=True, verbose_name='Описание товара')
price = models.IntegerField(blank=True, verbose_name='Цена')
category = models.ForeignKey('Category', on_delete=models.CASCADE)
icon = models.ImageField(upload_to='img/product/%m', verbose_name='Картинка товара')
slug = models.SlugField(unique=True, verbose_name='Адрес товара')
def get_absolute_url(self):
return reverse('product', kwargs={"slug": self.slug})
def __str__(self):
return self.title
urls.py
from django.urls import path
from . views import *
urlpatterns = [
path('', home, name='home'),
path('register/', user_register, name='register'),
path('logout/', user_logout, name='logout'),
path('login/', user_login, name='login'),
path('category/<str:slug>/', CategoryList.as_view(), name='category'),
path('<str:category>/<str:slug>/', ProductDetail.as_view(), name='product'),
]
views.py
class CategoryList(ListView):
model = Product
template_name = 'categories.html'
context_object_name = 'items'
paginate_by = 10
allow_empty = False
def get_queryset(self):
return Product.objects.filter(category__slug=self.kwargs['slug'])
def get_context_data(self, *, object_list=None, **kwargs):
context = super().get_context_data(**kwargs)
context['title'] = Category.objects.get(slug=self.kwargs['slug'])
return context
class ProductDetail(DetailView):
model = Product
template_name = 'product.html'
context_object_name = 'item'
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question