How to Hardcode URLs in Django



Python


In this article, we show how to hardcode URLs in Django.

URLs are one of the theme points of HTML.

URLs, encoded in anchor tags, allow a user to go anywhere, to any page, on the web.

Now, it's now not given much thought, but it was one the revolutionary breakthroughs in the early days of the web.

So how can we hardcode URLs in the Django framework in templates.

We focus on templates, because, for the most part, that's the only place you would put URLs encoded in anchor tags.

Templates are the pages that the user interacts with.

So hardcoding URLs in Django is pretty basic.

The following url references the Blog app in the project.



One of the most important parts about hardcoding URLs in Django is you always want to start the href attribute with "/". Doing this makes the path relative to the domain name of the website or the IP address of the website.

What is meant is this. If you have a website named, http://mywebsite.com, if you put in an anchor tag with the href attribute beginning with "/", after that comes after this is the path after the domain name of the website. Therefore, it's like the absolute path for the website. If you don't specify the first character as "/", it represents the relative path from the page that you are writing the anchor tag in. So if you don't specify "/" as the first character, you are giving the relative URL. So if the current page you're on is http://www.mywebsite.com/Blog/4/ and you specify an anchor tag of, <a href="Blog, the full path will be, http://www.mywebsite.com/Blog/4/Blog/

This is not normally what you would want. Normally, absolute paths make more sense, but it depends on you. Again, to give an absolute path, you specify "/" as the first character in the href attribute of the anchor tag and then after you specify after that is the path after the domain name or ip address of the website, whichever one you're using.

To give a few more examples, we have a few more examples.

The following URL references the Blog1 page in the Blog app. The full path will be http://www.mywebsite/Blog/Blog1



The following URL references the mortgage page in the Articles app. The full path will be http://www.mywebsite/Articles/mortgage/



So this is just a few examples of hardcoding URLs in anchor tags in Django.

If you want as well, just like in regular HTML pages (outside of a framework like Django, you could specify the full path using the domain name of the website.

So if your website is, http://www.mywebsite.com and you want to access the Blog1 page in the Blog app, the complete link would be, as shown by the following below.



And this is all there is to hardcoding URLs with anchor tags in the Django framework.


Related Resources

How to Create Dynamic URLs in Django

How to Create a Video Uploader with Python in Django

How to Create an Image Uploader with Python in Django



HTML Comment Box is loading comments...