6

So there should be a very basic way to do this, but unfortunately I don't seem to be able to find it.

How can one set an Href link to point to the 'base website url' + the 'link', rather than adding the link to the current page.

I.e. if I'm at www.example.com/content1/

I want the search function to go to www.example.com/search/

and not www.example.com/content1/search

I could just specify "www.example.com/search/" but then if it page is deployed locally I end up with a bunch of links to non-existent pages or vice versa. How can I specify the The Base hosting URL using DJango (whichever the server is running, whether the hostname, the current server ip, localhost etc.).

user3467349
  • 3,043
  • 4
  • 34
  • 61

3 Answers3

4

The best way to do this is the name your urls and then use the url template tag. Example below:

First, name your views. Use something like:

urlpatterns = [
    ...
    url(r'^search/$', views.search_view, name="search"),
    ...
]

In this example, you've got your url for your example.com/search/ view. It is named 'search', which can be used url template tags and using the reverse() function.

Next, in your template, use the url tag with your url name:

<a href="{% url 'search' %}">Search</a>
Alex
  • 8,321
  • 1
  • 34
  • 30
  • Is it possible to concatenate the string "{% url 'search' %}" with some other string, just in the template? – Tms91 Dec 18 '19 at 16:42
3

You shouldn't need to add 'base website url' to your href, it is implied. Make sure href is prefixed with '/' to set and absolute path and no '/' for relative.

 <a href="/">home</a>

is the same as

 <a href="http://www.mywebsite.com/">home</a>

and will work no matter which sub directory you are in

If you are on the homepage and you use the link:

<a href="sample">sample</a>

it will effectively equal:

 <a href="http://www.mywebsite.com/sample">sample</a>

but that same link used on the page http://www.mywebsite.com/sample will equate to:

 <a href="http://www.mywebsite.com/sample/sample">sample</a>

using:

<a href="/sample">sample</a>

Will always equate to the following no matter where on the site it is used:

 <a href="http://www.mywebsite.com/sample">sample</a>

If you are using django consider using the url template tag as Alex suggested:

https://docs.djangoproject.com/en/dev/ref/templates/builtins/#url

Community
  • 1
  • 1
Chris Montanaro
  • 16,948
  • 4
  • 20
  • 29
1

Make the link point to /search.

Any link that starts with / is relative to the domain root (say, http://example.com/) whereas any other relative link is relative to the current URL.