How to change url to show description instead of id with django?

Viewed 511

I am building my first website. But instead of the page being products/15 (where 15 is the product id), I want it to show the description of the product. How can I achieve that?

Here are my models.py:

class Product(models.Model):
    name = models.CharField(max_length=100)
    category = models.CharField(max_length=100)
    description = models.TextField()

    def __str__(self):
        return self.name
       

views.py:

def product(request, id):
    return render(request, 'product.html', {})

urls.py:

urlpatterns = [
    path('products/<id>/', post, name='sub-detail'),
]

Thanks in advance for the help!

1 Answers

As babak gholamirad saids you should use a key that is UNIQUE in the model and the URL, just as id is but not description.

But, if you want to use and display a more "descriptive" KEY than the id in the URL: Django's slugs are made for that.

What is a "slug" in Django?

https://docs.djangoproject.com/en/3.0/ref/models/fields/#slugfield

models.py

class Product(models.Model):
    name = models.CharField(max_length=100)
    slug = models.CharField(max_length=256, unique=True)
    category = models.CharField(max_length=100)
    description = models.TextField()

    def __str__(self):
        return self.name

views.py:

def product(request, slug):
    product_object = Product.objects.get(slug=slug)
    ...
    return render(request, 'product.html', {})

urls.py:

urlpatterns = [
    path('products/<slug>/', post, name='sub-detail'),
]

usage:

https://<my-domain>/products/my-wonderfull-descriptive-product-name/
Related