Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Django slug with id in url

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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…

>Solution :

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})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading