How can made a url with slug
and id
, like:
https://example.com/product/beauty-slug/1
The Product
model can accept repeated title
product, and insted use unique slug
i prefer use the slug
with id
models.py
class Product(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
product_title = models.CharField(max_length=255, default='product_title')
slug = models.SlugField(max_length=250,unique=True,null=True)
def __str__(self):
return self.product_title
def get_absolute_url(self):
return reverse('product_change', kwargs={'slug': self.slug})
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.product_title)
return super().save(*args, **kwargs)
And how use it in a template
product_list.html
<a href="{% url 'product_view' product.slug %}">see product</a>
urls.py
...
path('product/<slug:slug>', ProductView.as_view(), name='product_view'),
...
Thats works, but i know i gona have identical products title, so i think with id
is better to my case, becouse if needed costumer can reference the order to seller with id
number...
CodePudding user response:
As path you can use:
path('product/<slug:slug>/<int:pk>/', ProductView.as_view(), name='product_view'),
You thus can link to the URL with:
<a href="{% url 'product_view' product.slug product.pk %}">see product</a>
If you update the product_change
URL pattern as well, the .get_absolute_url()
method [Django-doc] of the model should be rewritten to:
class Product(models.Model):
# …
def get_absolute_url(self):
return reverse('product_change', kwargs={'slug': self.slug, 'pk': self.pk})