Can a empty string be passed in the url in django?

Viewed 886

I am working on a django project which have a posts page. I have its url as follows:

path('posts/<str:sort>', views.posts, name='posts'),

and this is what its view looks like:

def posts(request,sort)
    b=""
    if b=="time":
        posts=Post.objects.all().order_by(b)
    else:
        posts=Post.objects.all()
    return render(request,posts.html,{'posts':posts})

Now what I want is that if there is nothing passed as sort in the url or the url is like : /posts/ I want to display all posts but if the parameter is 'time' then I want to order_by as in my view. But currently if nothing is passed in url for sort then I get the error that no path found the url.

1 Answers

str converter is defined as follows:

class StringConverter:
    regex = '[^/]+'
    
    # other methods

Which means it requires at least one character (note +, not *). You can create a new url mapping and manually pass empty string as sort parameter:

path('posts/', views.posts, kwargs={'sort': ''})

You can also register your own converter to allow empty string or just switch to plain old re_path. These options are preferred in case if you want to reduce code repetition and reuse this behavior somewhere else. They also allow you to keep the same url name (useful if you're planning to reverse urls)

Related