Vivek K. Singh
Vivek K. Singh

Reputation: 170

How to escape '/' in django urls

I am working on a project that generates dynamic urls for eg if you type mysite.com/<yourtexthere> The site should generate a url with mysite.com/yourtexthere (where yourtext here is a slug of a model)and I am able to do that but the problem arises when I put something like this mysite.com/yourtexthere/moretext, Django doesn't match it with any of my existing URL patterns and gives me 404.

I wanted to ask is there a way by which I can treat '/' as just another character and generate unique url mymysite.com/yourtexthere/moretext where yourtexthere/moretext is now the slug.

views.py

def textview(request, slug):
    obj, created= Text.objects.get_or_create(slug=slug, defaults={'text':'', 'password':'123'})
    return render(request, 'text/textpage.html', {'obj' : obj, 'created' : created})

urls.py

# Only patterns
urlpatterns = [
    path('', home, name='home'),
    path('<slug:slug>/', textview, name='textview'),
]

Upvotes: 1

Views: 385

Answers (2)

BigBill
BigBill

Reputation: 40

Django path converters match strings in the input URL using regex. The default path converters are pretty basic - source code.

The slugConverter matches any string that only contains characters, numbers, and dashes, not forward slashes. In string yourtexthere/moretext the largest substring it will match is yourtexthere.

The pathConverter matches a string containing any type of character, so the result can contain a forward slash. It will match all of yourtexthere/moretext. So change your urlpatterns to this:

# Only patterns
urlpatterns = [
    path('', home, name='home'),
    path('<path:slug>/', textview, name='textview'),
]

The pathConverter will match all special characters. If you don't want this you can create your own custom converter with a regex tailored to your needs. For example, you could simply extend the slugConverter to also match strings with forward slashes.

class SlugPathConverter(StringConverter):
    regex = '[-a-zA-Z0-9_/]+'

Upvotes: 0

vlizana
vlizana

Reputation: 3242

From Django models docs:

A slug is a short label for something, containing only letters, numbers, underscores or hyphens.

So the 404 is actually correct, maybe use another field.

Upvotes: 1

Related Questions