Django: get URL of current page, including parameters, in a template

前端 未结 6 1241
忘了有多久
忘了有多久 2020-12-01 00:05

Is there a way to get the current page URL and all its parameters in a Django template?

For example, a templatetag that would print a full URL like /foo/bar?p

6条回答
  •  一生所求
    2020-12-01 00:46

    Django has a lot of built-in stuff, but if you don't explicit what do you want to use, it won't be used.

    So, in MTV schema (Model, Template, View) the view receives a request and uses a template render to generate a response, passing on it a dictionary or all local variables (using the locals() function) of this view. Knowing this, we can insert the current url that came from the response, like this:

    views.py:

    from django.shortcuts import render
    
    def page(request):
        currentUrl = request.get_full_path()
        return render(request, 'app/page.html', locals())
    

    Then, in the template 'app/page.html' you just have to do the following to display the currentUrl variable that we just created and passed through via locals():

    app/template/page.html:

    {{ currentUrl }}
    

提交回复
热议问题