user9745220
user9745220

Reputation: 253

Django: URL Reverse custom parameter to match?

I'm trying to figure out if I can build a url which would match objects in my model with other field instead of pk. I have a model which has many fields, and I was happy while using simple <int:id> while building url paths, so in this case:

path("<int:pk>/", ProductDetailView.as_view(), name="product_detail")

But things changed, and we decided to use our old url regex, so instead this we changed to:

path("<slug:url>/", ProductDetailView.as_view(), name="product_detail"),

Our model have this field:

url = models.TextField(null=True)

and I can easily filter out by url, like this: model.filter(url='/nesiojami-kompiuteriai/nesiojami-kompiuteriai.html') for example.

I have a problem while trying to reverse and url for the model instance:

prod = Product.objects.filter(is_deleted=False, category_id=64, url__isnull=False).first()
return reverse("product:product_detail", kwargs={"url": prod.url})

NoReverseMatch at /nesiojami-kompiuteriai/nesiojami-kompiuteriai/
Reverse for 'product_detail' with keyword arguments '{'url': '/nesiojami-kompiuteriai/nesiojami-kompiuteriai/nesiojamas-kompiuteris-acer-sf314-14-i5-8265-8256gb--9618707.html'}' not found. 1 pattern(s) tried: ['product/(?P<url>[-a-zA-Z0-9_]+)/$']

Upvotes: 1

Views: 274

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476659

Your url field contains as value:

/nesiojami-kompiuteriai/nesiojami-kompiuteriai/nesiojamas-kompiuteris-acer-sf314-14-i5-8265-8256gb--9618707.html

This is not a slug. A slug is a sequence of alphanumerical characters, hyphens and underscores. But it is not allowed to contain slashes (/), or dots (.).

If you want to include this, then you can work with a <path:…> path converter [Django-doc], which will accept a sequence of characters including the slash and dot:

path('<path:url>/', ProductDetailView.as_view(), name='product_detail'),

but perhaps your url field contains the wrong data. Typically a slug is made by transforming the title of something into a slug with slugify(…) [Django-doc] this will replace all spacing characters with hyphens and remove all characters that are not valid slug characters.

Upvotes: 2

Related Questions