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

前端 未结 6 1249
忘了有多久
忘了有多久 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:32

    Write a custom context processor. e.g.

    def get_current_path(request):
        return {
           'current_path': request.get_full_path()
         }
    

    add a path to that function in your TEMPLATE_CONTEXT_PROCESSORS settings variable, and use it in your template like so:

    {{ current_path }}
    

    If you want to have the full request object in every request, you can use the built-in django.core.context_processors.request context processor, and then use {{ request.get_full_path }} in your template.

    See:

    • Custom Context Processors
    • HTTPRequest's get_full_path() method.

提交回复
热议问题