Direction resolution of django template: generate link address based on url

Keywords: Web Development Django vim Attribute Python

Environment the same django article.


web services running django:

 cd py3/django-test1/test4
 python manage.py runserver 192.168.255.70:8000


First, use a tag hyperlink in html to automatically match the url route of the application, and then display the specified html page:

Edit view function:

vim bookshop/views.py

from django.shortcuts import render
from .models import *
def index(request):
    #list = HeroInfo.objects.all()
    list = HeroInfo.objects.filter(isDelete=False)
    context = {'list1':list}
    return render(request,'bookshop/index.html',context)
def show(request,id):
    context = {'id':id}
    return render(request,'bookshop/show.html',context)

Edit url route:

vim bookshop/urls.py

from django.conf.urls import url
from .  import views

urlpatterns = [
    url(r'^$',views.index,name='index'),
    
    url(r'^(\d+)$',views.show,name='show'),
    #Parentheses indicate that parameters are to be passed in the url;
]

Edit html template:

vim templates/bookshop/index.html

<!DOCTYPE html>
<html>
<head>
    <title>Title</title>
</head>
<body>
<a href="123">Linked digit</a>
</body>
</html>

vim templates/bookshop/show.html

<!DOCTYPE html>
<html>
<head>
    <title>Title</title>
</head>
<body>
{{ id }}
</body>
</html>

Browser access: http://192.168.255.70:8000/

Show:

Click hyperlink: the browser address automatically changes to: http://192.168.255.70:8000/123

Show:


When the main url route test4/urls.py is modified to:

urlpatterns = [
    ...
    url(r'^bookshop/',include('bookshop.urls',namespace='bookshop')),
]

In this way, when you change the url route, you need to change the link address in html; if you use the reverse resolution in django, when you change the url route, you do not need to change the link address in html, and the reverse resolution will automatically complete the modification:


Edit html template:

vim templates/bookshop/index.html

<!DOCTYPE html>
<html>
<head>
    <title>Title</title>
</head>
<body>
<!--<a href="123">Linked digit</a>-->
<a href="{% url 'bookshop:show' '123' %}">link--Backward analysis</a>
<!--bookshop It is the Lord. url Routing namespace Attribute, show It is applied. url Routing name Attribute, 123 is the application url Parameters to receive in-->
</body>
</html>

Only the reverse parsing part of the html template file is modified, and other configurations remain unchanged.

The same for browsing.



Posted by Hoppus on Mon, 02 Dec 2019 08:15:47 -0800