2

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!

Adam
  • 23
  • 5
  • Maybe this link. https://docs.djangoproject.com/en/3.0/ref/request-response/#django.http.HttpResponse – Zoe Jul 10 '20 at 07:26
  • urls are for passing data to the views not showing data to user so it's better to pass id which you can find product by that not description which can be multiple of it in database – babak gholamirad Jul 10 '20 at 07:37

1 Answers1

1

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/
franckfournier
  • 344
  • 1
  • 4
  • 12
  • 2
    PS Adam, If you have some SEO more specific needs, that are not fulfilled by the Django slug mechanism, it's always possible to implement a slug-like mechanism that better suits your needs. – franckfournier Jul 15 '20 at 16:40