English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Django URL 映射

Jetzt haben wir eine funktionierende Ansicht im vorangegangenen Kapitel erklärt. Wir möchten, dass man diese Ansicht über eine URL erreichen kann. Django hat seine eigene URL-Mapping-Methode, und jetzt bearbeiten wir die Datei url.py im Projekt (im Projekt myproject/urls.py abgeschlossen. Der Inhalt der Datei url.py sieht so aus:

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : de.oldtoolbag.com
# Date : 2020-08-08
from django.conf.urls import patterns, include, url
 from django.contrib import admin
 admin.autodiscover()
 urlpatterns = patterns('',
    #Examples
    #url(r'^, 'myproject.view.home', name = 'home'),
    #url(r'^blog/', include('blog.urls')),
    url(r'^admin', include(admin.site.urls)),
 ) , 'myproject.view.home', name = 'home'),
    #url(r'^blog/', include('blog.urls')),
    url(r'^admin', include(admin.site.urls)),
 )

Wenn ein Benutzer eine Webseite in Ihrem Webanwendung initiiert eine Anfrage, übernimmt der Django-Controller durch die Datei url.py die Suche nach der entsprechenden Ansicht und gibt die HTML-Antwort zurück oder wenn nichts gefunden wird, gibt er zurück404Fehler nicht gefunden. Wichtig ist der “urlpatterns”-Tupel. Dies ist die Definition der Abhängigkeit zwischen URL und Ansicht. Ein URL-Modus-Tupel ist wie ein Tupel −

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : de.oldtoolbag.com
# Date : 2020-08-08
from django.conf.urls import patterns, include, url
 from django.contrib import admin
 admin.autodiscover()
 urlpatterns = patterns('',
    #Examples
    #url(r'^, 'myproject.view.home', name = 'home'),
    #url(r'^blog/', include('blog.urls')),
    url(r'^admin', include(admin.site.urls)),
    url(r'^hello/', myapp.views.hello', name = 'hello'),
 ) , 'myproject.view.home', name = 'home'),
    #url(r'^blog/', include('blog.urls')),
    url(r'^admin', include(admin.site.urls)),
    url(r'^hello/', myapp.views.hello', name = 'hello'),
 )

URL-Zuweisungsmarkenzeile "/"home" bis zu "myapp/ Hello-Ansicht erstellt im view.py-Datei. Wie Sie oben sehen, besteht die Zuordnung aus drei Elementen -

Muster - Ein reguläres Ausdruck, der auf die URL zutrifft und diese zuordnen kann. Alles, was mit dem Python-Modul “re” funktioniert, ist ein Muster, das mit URL-Parametern übertragen werden kann (sehr nützlich, wenn Sie Parameter über URLs übertragen möchten). python zum Pfad der Ansicht - Der gleiche, wenn Sie das Modul importieren. Name - Um URL-Inversen auszuführen, muss der Name der URL-Mode verwendet werden, um die obige Beispiel auszuführen. Nachdem Sie dies getan haben, starten Sie den Server und greifen Sie auf Ihre Ansicht über die folgende URL zu: http://127.0.0.1/hello

URLs sortieren

Bis jetzt haben wir “myprojects” erstellt/url.py”-Datei die URLs, aber wie in der vorherigen Django-Beschreibung erwähnt, ist es am besten, eine Anwendung zu erstellen, die in verschiedenen Projekten wiederverwendet werden kann. Auf diese Weise können Sie leicht sehen, was das Problem ist, wenn Sie alle URLs in der Datei “projecturl.py” speichern möchten. Daher ist es am besten, für jede Anwendung eine “url.py” zu erstellen und diese in unsere Hauptprojekt urls.py-Datei aufzunehmen (einschließlich der URLs, die in unserer Management-Oberfläche verwaltet werden).

Wie macht es das?

Wir müssen den folgenden Code verwenden, um eine urls.py-Datei im myapp-Verzeichnis zu erstellen (im Verzeichnis myapp,/urls.py) −

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : de.oldtoolbag.com
# Date : 2020-08-08
from django.conf.urls import patterns, include, url
 urlpatterns = patterns('', url(r'^hello/', myapp.views.hello, name='hello'),)

myproject/urls.py wird in folgendem geändert-

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : de.oldtoolbag.com
# Date : 2020-08-08
from django.conf.urls import patterns, include, url
 from django.contrib import admin
 admin.autodiscover()
 urlpatterns = patterns('',
    #Examples
    #url(r'^, 'myproject.view.home', name = 'home'),
    #url(r'^blog/', include('blog.urls')),
    url(r'^admin', include(admin.site.urls)),
    url(r'^myapp/', include(myapp.urls)),
 ) , 'myproject.view.home', name = 'home'),
    #url(r'^blog/', include('blog.urls')),
    url(r'^admin', include(admin.site.urls)),
    url(r'^myapp/', include(myapp.urls)),
 )

Wir haben alle URLs der myapp-Anwendung enthalten. Dies erfolgt durch den Zugriff auf home.html für “/hello”, ist jetzt “/myapp/hello”, das ist eine bessere und einfacher zu verstehende Struktur für Web-Anwendungen.

Erstellen Sie einen neuen Ansichtsdatei: C:\myproject\templates\myapp\hello.html, deren Inhalt wie folgt ist:

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : de.oldtoolbag.com
# Date : 2020-08-08
<html>
 <head>
   <meta http-equiv="content-type" content="text/html; charset=utf-8>
   <title>Hello </title>
   <meta name="robots" content="NONE,NOARCHIVE">
   </style>
 </head>
     <body>
         <h2>Welcome to w3codebox .</h2>
         <p>This is my first Django App</p>
     <body>
 </html>

Lassen Sie uns nun überlegen, dass wir in einer anderen Ansicht von 'morning' in myapp, die wir in der Abbildung myapp/url.py, dann ändern wir unseren myapp/url.py zu −

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : de.oldtoolbag.com
# Date : 2020-08-08
from django.conf.urls import patterns, include, url
 urlpatterns = patterns('',
    url(r'^hello/', myapp.views.hello', name = 'hello'),
    url(r'^morning/', myapp.views.morning', name = 'morning'),
 )

Dies kann umstrukturiert werden in −

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : de.oldtoolbag.com
# Date : 2020-08-08
from django.conf.urls import patterns, include, url
 urlpatterns = patterns('myapp.views',
    url(r'^hello/', 'hello', name = 'hello'),
    url(r'^morning/', morning', name = 'morning'),)

Wie Sie sehen können, verwenden wir derzeit den ersten Element des Tupels urlpatterns.

send parameters to the view

Now that we know how to map URLs and how to organize them, let's see how to pass parameters to the view. A classic article example (the article you want to access to "/articles/article_id)".

Parameters are passed to the view by capturing them through URL pattern regular expressions. If we have a view like the following "myapp/view.py"

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : de.oldtoolbag.com
# Date : 2020-08-08
from django.shortcuts import render
 from django.http import HttpResponse
 def hello(request):
    return render(request, "hello.html", {})
 def viewArticle(request, articleId):
    text = "Displaying article Number: %s"%articleId
    return HttpResponse(text)

We want to map it to myapp/urls.py", so we can access it through "/myapp/article/articleId - Access, we need to add it in the following "myapp/urls.py - Definition

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : de.oldtoolbag.com
# Date : 2020-08-08
from django.conf.urls import url
 from . import views
 urlpatterns = [
     url(r'^hello', views.hello, name='hello'),
     url(r'^article/(\d+)/', views.viewArticle, name='article'), 
     url(r'^', views.index, name='index'),
 ], views.index, name='index'),
 ]


When Django sees the URL: "/myapp/article/42",它将传递参数42to the viewArticle view, in the browser, you should get the following result -

Note that the order of the parameters here is very important. Suppose we want to view a list of articles for a specific month of a year, now add a viewArticles view. The code in view.py becomes -

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : de.oldtoolbag.com
# Date : 2020-08-08
from django.shortcuts import render
 from django.http import HttpResponse
 def hello(request):
    return render(request, "hello.html", {})
 def viewArticle(request, articleId):
    text = "Displaying article Number: %s"%articleId
    return HttpResponse(text)
 def viewArticles(request, month, year):
    text = "Displaying articles of: %s"/%s"%(year, month)
    return HttpResponse(text)

相应的 myapp/urls.py 文件看起来如下 −

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : de.oldtoolbag.com
# Date : 2020-08-08
from django.conf.urls import patterns, include, url
 urlpatterns = patterns('myapp.views',
    url(r'^hello/', 'hello', name = 'hello'),
    url(r'^morning/', 'morning', name = 'morning'),
    url(r'^article/(\d+)/', 'viewArticle', name = 'article'),
    url(r'^articles/(\d{2})/(\d{4})', 'viewArticles', name = 'articles'),)

现在,当您访问 http://localhost:8000/myapp/articles/12/2015/,会得到'Displaying articles of: 2015/12‘ ,但如果转换参数,将不能得到相同的结果。

为了避免这种情况,有可能一个URL参数会链接到视图参数。因此 url.py 将成为 -

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : de.oldtoolbag.com
# Date : 2020-08-08
from django.conf.urls import patterns, include, url
 urlpatterns = patterns('myapp.views',
    url(r'^hello/', 'hello', name = 'hello'),
    url(r'^morning/', 'morning', name = 'morning'),
    url(r'^article/(\d+)/', 'viewArticle', name = 'article'),
    url(r'^articles/(?P\d{2})/(?P\d{4})', 'viewArticles', name = 'articles'),)