0

assume the following:

Your model has: Products.slug

urls: path('<int:id>/<slug:slug>/', views.product_detail, name='product_detail'),

views: products = Products.objects.get(id=id, slug=slug)

Someone goes to /products/1/brazil-nuts/, and it goes to the right page.

But then someone copy/pastes the url wrong to: /products/1/brazil-nu/

Then you get a DoesNotExist error... Now you could "fix" this by not forcing the slug=slug argument in your query, but then the url is incorrect, and people could link from /products/1/brazil-nu-sjfhkjfg-dfh, which is sloppy.

So how would I redirect an incorrect url to the correct one with the same url structure as the correct one (only id and slug arguments), without relying on JavaScript's window.history.pushState(null, null, proper_url); every time the page loads?

I've already tried making the same url pattern to redirect, but since django uses the first pattern match, it won't work no matter where you put the url in your list.

1 Answers1

0

Just update your view:

products_q = Products.objects.filter(id=id, slug__startswith=slug)
products_count = products_q.count()

if products_count == 1:
    product = products_q.first()
    return reverse_lazy('product_detail', args=[product.id, product.slug])
Yevgeniy Kosmak
  • 3,561
  • 2
  • 10
  • 26