Django reverse function

The reverse function is used to reverse the URL, and then we introduce several uses of the reverse function.

1.Before, we used the URL to access the view function. Sometimes we know this view function, but want to reverse its url. At this time, it can be achieved through reverse. The sample code is as follows

> /list/

2. If there is an application namespace or an instance namespace, the namespace should be added when inverting. The sample code is as follows

> /book/list/

3. If parameters need to be passed in this url, then parameters can be passed through kwargs. The sample code is as follows

> /front/articles/1

4. Because reverse in Django does not distinguish between GET requests and POST requests when reversing urls, it is not possible to add query string parameters when reversing. If you want to add query string parameters, you can only add them manually. The sample code is as follows

login_url = reverse('login') + "?next=/"

Next, we will imitate Zhihu and make a small case. We visit the homepage of Zhihu If you are not logged in, the website will be redirected to next=%2F login page, next we will implement this function

app_name = "front"
urlpatterns = [
    path('', views.index, name="index"),
    path('signIn/', views.login, name="login"),

def index(request):
    username = request.GET.get('username')
    if username:
        return HttpResponse("front home")
        return redirect(reverse('front:login')  + "?next=/")

def login(request):
    return HttpResponse('front login page')

Next, we visit through the browser, the page will be automatically redirected to, we can clearly see the redirection process through the pycharm console

[14/May/2021 09:46:58] "GET /front/ HTTP/1.1" 302 0
[14/May/2021 09:46:58] "GET /front/signIn/?next=/ HTTP/1.1" 200 17

Leave a Reply