Ask Your Question
4

What is the method for obtaining the current base URL path for a Django app?

asked 2023-07-08 17:20:45 +0000

lalupa gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-07-08 17:45:01 +0000

djk gravatar image

In a Django app, the current base URL path can be obtained using the request object. Here's an example:

from django.shortcuts import render

def my_view(request):
    base_url = request.scheme + '://' + request.get_host() + request.path
    return render(request, 'my_template.html', {'base_url': base_url})

In the above code:

  • request.scheme returns the protocol (http or https)
  • request.get_host()returns the hostname of the server (e.g. www.example.com)
  • request.path returns the path of the current URL

These three values are combined to create the base_url. This value can then be used in the view or passed to the template as a context variable.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-07-08 17:20:45 +0000

Seen: 13 times

Last updated: Jul 08 '23