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
reverse("list")
> /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
reverse('book:list')
> /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
reverse("front:articles",kwargs={"id":1})
> /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 https://www.zhihu.com/. If you are not logged in, the website will be redirected to https://www.zhihu.com/signin? next=%2F login page, next we will implement this function
# urls.py
app_name = "front"
urlpatterns = [
path('', views.index, name="index"),
path('signIn/', views.login, name="login"),
]
# views.py
def index(request):
username = request.GET.get('username')
if username:
return HttpResponse("front home")
else:
return redirect(reverse('front:login') + "?next=/")
def login(request):
return HttpResponse('front login page')
Next, we visit 127.0.0.1/front/ through the browser, the page will be automatically redirected to 127.0.0.1:8000/front/signIn/?next=/, 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