Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way of linking to a page in Django

Tags:

python

django

I managed to create a URL tag for my index. But right now I'm confused how to add links to other pages.

I put this on my urls.py

url(r'^$', 'index', name='index'),

The next thing I put this tag into the href:

{% url 'index' %}

But what if I wanted to create a new page and would be linking to it. How would I do it the best way?

like image 664
qu4ntum Avatar asked Apr 08 '14 13:04

qu4ntum


2 Answers

Django has updated urlpatterns to take 'path' instead of using url so it's become much more efficient. You don't have to use regex anymore

from django.urls import path
from . import views

urlpatterns=[
    path('', views.index , name='index'),
    path('blog/', views.blog , name='blog'),]

Then in templates, you can use template tagging

<a href="{% url 'index' %}">Index</a>
<a href="{% url 'blog' %}">Blog</a>

If you have multiple apps, you can tag it as follows. For example, if this is under 'post' app:

In post app urls.py:

from django.urls import path
from . import views

app_name = 'post'
urlpatterns=[
    path('', views.index , name='index'),
    path('blog/', views.blog , name='blog'),]

in the project urls.py:

from django.urls import path, include

urlpatterns=[
path('post/', include('post.urls'),]

In templates, you do as following:

<a href="{% url 'post:index' %}">Index</a>
<a href="{% url 'post:blog' %}">Blog</a>
like image 127
uclaastro Avatar answered Oct 23 '22 18:10

uclaastro


So next you would extend your urls.py to look something like this:

url(r'^$', 'index', name='index'),
url(r'^blog$', 'blog', name='blog'),

Then in your html you can use either one:

<a href="{% url 'index' %}">Home</a>
<a href="{% url 'blog' %}">Blog</a>

You can of course use the template tage {% url 'index' %} as many times as you need in any template.

like image 37
aychedee Avatar answered Oct 23 '22 17:10

aychedee