4

So I am new to django I have been working on PHP CodeIgniter in which to put absolute URL in href I used a function called base_url by calling URL helper

<?php echo base_url().'user/login';?>


which gives output something like
http://localhost/projectname/user/login
I want the same thing in Django but haven't got any answer or answer which I could understand. I don't want to use relative URL and my expected result is should be something like this

{% url 'login' %}


above code should return
http://localhost/projectname/user/login

dvijparekh
  • 936
  • 7
  • 16
  • what is your expected result? – Danish Ali Feb 01 '19 at 10:01
  • i have edited my question please check – dvijparekh Feb 01 '19 at 10:05
  • if you're going to serve all your project urls under `/projectname/` you need to tell Django that by adding it to your root urls. Or you need to setup your server to remove it from the path when proxying to your django app server. But then you have to add it manually when you build your absolute uri. I think the first method is preferred. So then you can just use relative urls. – dirkgroten Feb 01 '19 at 11:03
  • Duplicate of https://stackoverflow.com/questions/2345708/how-can-i-get-the-full-absolute-url-with-domain-in-django - use https://docs.djangoproject.com/en/2.1/ref/request-response/#django.http.HttpRequest.build_absolute_uri – Risadinha Feb 11 '19 at 10:45
  • 1
    Possible duplicate of [How can I get the full/absolute URL (with domain) in Django?](https://stackoverflow.com/questions/2345708/how-can-i-get-the-full-absolute-url-with-domain-in-django) – Risadinha Feb 11 '19 at 10:45

2 Answers2

4

You can get absolute url in 2 ways in django.

One is build your custom template tag by using HttpRequest.build_absolute_uri() method from HttpRequest

Or simply use following line in your django template.

<a href="{{ request.get_host }}{% url your_url_name %}">Link</a>

See this link for details: https://docs.djangoproject.com/en/2.1/ref/request-response/#django.http.HttpRequest.get_host

Shubho Shaha
  • 1,869
  • 1
  • 16
  • 22
  • will it work if i put my project in subfolder of any project on server eg. from https://domainname.com/ to https://domainname.com/xyz_folder ? – dvijparekh Feb 01 '19 at 10:15
  • @dvijparekh yes it should do the trick as per django Official doc. See this https://docs.djangoproject.com/en/2.1/ref/request-response/#django.http.HttpRequest.get_host – Shubho Shaha Feb 01 '19 at 10:41
1

If you have a URL path in your urls.py file defined like this:

path('user/', views.user, name='user_list')

Then you can call this URL in the template like this:

<a href="{% url 'user_list' %}">Users</a>

Check https://docs.djangoproject.com/en/2.1/ref/templates/builtins/#url for details.

For absolute URL you can use:

<a href="{{ request.get_host }}{% url 'user_list' %}">Users</a>
Rakib
  • 327
  • 2
  • 9