Pengirim URL¶
Bersih, skema URL anggun adalah rincian penting dalam aplikasi jaringan kualitas-tinggi. Django membuat anda merancang URL bagaimanapun anda inginkan, dengan tanpa batasan kerangka kerja.
See Cool URIs don't change, by World Wide Web creator Tim Berners-Lee, for excellent arguments on why URLs should be clean and usable.
Ikhtisar¶
To design URLs for an app, you create a Python module informally called a URLconf (URL configuration). This module is pure Python code and is a mapping between URL path expressions to Python functions (your views).
This mapping can be as short or as long as needed. It can reference other mappings. And, because it's pure Python code, it can be constructed dynamically.
Django also provides a way to translate URLs according to the active language. See the internationalization documentation for more information.
Bagaimana Django mengolah permintaan¶
When a user requests a page from your Django-powered site, this is the algorithm the system follows to determine which Python code to execute:
Django determines the root URLconf module to use. Ordinarily, this is the value of the
ROOT_URLCONF
setting, but if the incomingHttpRequest
object has aurlconf
attribute (set by middleware), its value will be used in place of theROOT_URLCONF
setting.Django loads that Python module and looks for the variable
urlpatterns
. This should be a sequence ofdjango.urls.path()
and/ordjango.urls.re_path()
instances.Django runs through each URL pattern, in order, and stops at the first one that matches the requested URL, matching against
path_info
.Once one of the URL patterns matches, Django imports and calls the given view, which is a Python function (or a class-based view). The view gets passed the following arguments:
Sebuah instance dari
HttpRequest
.If the matched URL pattern contained no named groups, then the matches from the regular expression are provided as positional arguments.
The keyword arguments are made up of any named parts matched by the path expression that are provided, overridden by any arguments specified in the optional
kwargs
argument todjango.urls.path()
ordjango.urls.re_path()
.
If no URL pattern matches, or if an exception is raised during any point in this process, Django invokes an appropriate error-handling view. See Error handling below.
Contoh¶
Ini adalah contoh URLconf:
from django.urls import path
from . import views
urlpatterns = [
path("articles/2003/", views.special_case_2003),
path("articles/<int:year>/", views.year_archive),
path("articles/<int:year>/<int:month>/", views.month_archive),
path("articles/<int:year>/<int:month>/<slug:slug>/", views.article_detail),
]
Catatan:
Untuk menangkap nilai dari URL, gunakan kurung sudut.
Captured values can optionally include a converter type. For example, use
<int:name>
to capture an integer parameter. If a converter isn't included, any string, excluding a/
character, is matched.Tidak perlu menambahkan awalan garis miring, karena setiap URL memilikinya. Sebgai contoh, itu adalah
articles
, bukan/articles
.
Contoh permintaan:
Permintaan pada
/articles/2005/03/
akan mencocokkan masukan ketiga dalam list. Django akan memanggil fungsiviews.month_archive(permintaan, year=2005, month=3)
./articles/2003/
would match the first pattern in the list, not the second one, because the patterns are tested in order, and the first one is the first test to pass. Feel free to exploit the ordering to insert special cases like this. Here, Django would call the functionviews.special_case_2003(request)
/articles/2003
would not match any of these patterns, because each pattern requires that the URL end with a slash./articles/2003/03/building-a-django-site/
would match the final pattern. Django would call the functionviews.article_detail(request, year=2003, month=3, slug="building-a-django-site")
.
Perubah jalur¶
Perubah jalur berikut tersedia secara awalan:
str
- Matches any non-empty string, excluding the path separator,'/'
. This is the default if a converter isn't included in the expression.int
- Cocok nol atau integer positif apapun. Mengembalikan sebuahint
.slug
- Matches any slug string consisting of ASCII letters or numbers, plus the hyphen and underscore characters. For example,building-your-1st-django-site
.uuid
- Matches a formatted UUID. To prevent multiple URLs from mapping to the same page, dashes must be included and letters must be lowercase. For example,075194d3-6885-417e-a8a8-6c931e272f00
. Returns aUUID
instance.path
- Matches any non-empty string, including the path separator,'/'
. This allows you to match against a complete URL path rather than a segment of a URL path as withstr
.
Registering custom path converters¶
For more complex matching requirements, you can define your own path converters.
A converter is a class that includes the following:
Atribut kelas
regex
, sebagai string.A
to_python(self, value)
method, which handles converting the matched string into the type that should be passed to the view function. It should raiseValueError
if it can't convert the given value. AValueError
is interpreted as no match and as a consequence a 404 response is sent to the user unless another URL pattern matches.A
to_url(self, value)
method, which handles converting the Python type into a string to be used in the URL. It should raiseValueError
if it can't convert the given value. AValueError
is interpreted as no match and as a consequencereverse()
will raiseNoReverseMatch
unless another URL pattern matches.
Sebagai contoh:
class FourDigitYearConverter:
regex = "[0-9]{4}"
def to_python(self, value):
return int(value)
def to_url(self, value):
return "%04d" % value
Register custom converter classes in your URLconf using
register_converter()
:
from django.urls import path, register_converter
from . import converters, views
register_converter(converters.FourDigitYearConverter, "yyyy")
urlpatterns = [
path("articles/2003/", views.special_case_2003),
path("articles/<yyyy:year>/", views.year_archive),
...,
]
Ditinggalkan sejak versi 5.1: Overriding existing converters with django.urls.register_converter()
is
deprecated.
Menggunakan regular expression¶
If the paths and converters syntax isn't sufficient for defining your URL
patterns, you can also use regular expressions. To do so, use
re_path()
instead of path()
.
In Python regular expressions, the syntax for named regular expression groups
is (?P<name>pattern)
, where name
is the name of the group and
pattern
is some pattern to match.
Here's the example URLconf from earlier, rewritten using regular expressions:
from django.urls import path, re_path
from . import views
urlpatterns = [
path("articles/2003/", views.special_case_2003),
re_path(r"^articles/(?P<year>[0-9]{4})/$", views.year_archive),
re_path(r"^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/$", views.month_archive),
re_path(
r"^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/(?P<slug>[\w-]+)/$",
views.article_detail,
),
]
This accomplishes roughly the same thing as the previous example, except:
The exact URLs that will match are slightly more constrained. For example, the year 10000 will no longer match since the year integers are constrained to be exactly four digits long.
Each captured argument is sent to the view as a string, regardless of what sort of match the regular expression makes.
When switching from using path()
to
re_path()
or vice versa, it's particularly important to be
aware that the type of the view arguments may change, and so you may need to
adapt your views.
Using unnamed regular expression groups¶
As well as the named group syntax, e.g. (?P<year>[0-9]{4})
, you can
also use the shorter unnamed group, e.g. ([0-9]{4})
.
This usage isn't particularly recommended as it makes it easier to accidentally introduce errors between the intended meaning of a match and the arguments of the view.
In either case, using only one style within a given regex is recommended. When both styles are mixed, any unnamed groups are ignored and only named groups are passed to the view function.
Penjelasan bersarang¶
Regular expressions allow nested arguments, and Django will resolve them and pass them to the view. When reversing, Django will try to fill in all outer captured arguments, ignoring any nested captured arguments. Consider the following URL patterns which optionally take a page argument:
from django.urls import re_path
urlpatterns = [
re_path(r"^blog/(page-([0-9]+)/)?$", blog_articles), # bad
re_path(r"^comments/(?:page-(?P<page_number>[0-9]+)/)?$", comments), # good
]
Both patterns use nested arguments and will resolve: for example,
blog/page-2/
will result in a match to blog_articles
with two
positional arguments: page-2/
and 2
. The second pattern for
comments
will match comments/page-2/
with keyword argument
page_number
set to 2. The outer argument in this case is a non-capturing
argument (?:...)
.
The blog_articles
view needs the outermost captured argument to be reversed,
page-2/
or no arguments in this case, while comments
can be reversed
with either no arguments or a value for page_number
.
Nested captured arguments create a strong coupling between the view arguments
and the URL as illustrated by blog_articles
: the view receives part of the
URL (page-2/
) instead of only the value the view is interested in. This
coupling is even more pronounced when reversing, since to reverse the view we
need to pass the piece of URL instead of the page number.
As a rule of thumb, only capture the values the view needs to work with and use non-capturing arguments when the regular expression needs an argument but the view ignores it.
What the URLconf searches against¶
The URLconf searches against the requested URL, as a normal Python string. This does not include GET or POST parameters, or the domain name.
Sebagai contoh, dalam permintaan pada https://www.example.com/myapp/
, URLconf akan mencari myapp/
.
Dalam permintaan untuk https://www.example.com/myapp/?page=3
, the URLconf akan mencari myapp/
.
The URLconf doesn't look at the request method. In other words, all request
methods -- POST
, GET
, HEAD
, etc. -- will be routed to the same
function for the same URL.
Menentukan awalan untuk menampilkan argumen¶
A convenient trick is to specify default parameters for your views' arguments. Here's an example URLconf and view:
# URLconf
from django.urls import path
from . import views
urlpatterns = [
path("blog/", views.page),
path("blog/page<int:num>/", views.page),
]
# View (in blog/views.py)
def page(request, num=1):
# Output the appropriate page of blog entries, according to num.
...
In the above example, both URL patterns point to the same view --
views.page
-- but the first pattern doesn't capture anything from the
URL. If the first pattern matches, the page()
function will use its
default argument for num
, 1
. If the second pattern matches,
page()
will use whatever num
value was captured.
Penampilan¶
Django processes regular expressions in the urlpatterns
list which is
compiled the first time it's accessed. Subsequent requests use the cached
configuration via the URL resolver.
Sintaksis dari variabel urlpatterns
¶
urlpatterns
should be a sequence of path()
and/or re_path()
instances.
Penanganan kesalahan¶
When Django can't find a match for the requested URL, or when an exception is raised, Django invokes an error-handling view.
The views to use for these cases are specified by four variables. Their default values should suffice for most projects, but further customization is possible by overriding their default values.
Lihat dokumentasi pada customizing error views 1 untuk rincian penuh.
Nilai-nilai itu dapat disetel dalam URLconf akar anda. Pengaturan variabel-variabel ini dalam URLconf lain apapun tidak mempunyai pengaruh.
Nilai-nilai harus callable, atau deretan karakter mewakili jalur impor Pythn penuh pada tampilan yang harus dipanggil untuk menangani kondisi kesalahan di tangan.
Variabel nya adalah:
handler400
-- Lihatdjango.conf.urls.handler400
.handler403
-- Lihatdjango.conf.urls.handler403
.handler404
-- Lihatdjango.conf.urls.handler404
.handler500
-- Lihatdjango.conf.urls.handler500
.
Menyertakan URLconf lain¶
At any point, your urlpatterns
can "include" other URLconf modules. This
essentially "roots" a set of URLs below other ones.
For example, here's an excerpt of the URLconf for the Django website itself. It includes a number of other URLconfs:
from django.urls import include, path
urlpatterns = [
# ... snip ...
path("community/", include("aggregator.urls")),
path("contact/", include("contact.urls")),
# ... snip ...
]
Whenever Django encounters include()
, it chops off
whatever part of the URL matched up to that point and sends the remaining
string to the included URLconf for further processing.
Another possibility is to include additional URL patterns by using a list of
path()
instances. For example, consider this URLconf:
from django.urls import include, path
from apps.main import views as main_views
from credit import views as credit_views
extra_patterns = [
path("reports/", credit_views.report),
path("reports/<int:id>/", credit_views.report),
path("charge/", credit_views.charge),
]
urlpatterns = [
path("", main_views.homepage),
path("help/", include("apps.help.urls")),
path("credit/", include(extra_patterns)),
]
Dalam contoh ini, URL /credit/reports/
akan ditangani oleh tampilan Django credit_views.report()
.
This can be used to remove redundancy from URLconfs where a single pattern prefix is used repeatedly. For example, consider this URLconf:
from django.urls import path
from . import views
urlpatterns = [
path("<page_slug>-<page_id>/history/", views.history),
path("<page_slug>-<page_id>/edit/", views.edit),
path("<page_slug>-<page_id>/discuss/", views.discuss),
path("<page_slug>-<page_id>/permissions/", views.permissions),
]
Kami dapat meningkatkan dengan menyatakan awalan jalur umum hanya sekali dan mengelompokkan akhiran yang beda:
from django.urls import include, path
from . import views
urlpatterns = [
path(
"<page_slug>-<page_id>/",
include(
[
path("history/", views.history),
path("edit/", views.edit),
path("discuss/", views.discuss),
path("permissions/", views.permissions),
]
),
),
]
Parameter tertangkap¶
An included URLconf receives any captured parameters from parent URLconfs, so the following example is valid:
# In settings/urls/main.py
from django.urls import include, path
urlpatterns = [
path("<username>/blog/", include("foo.urls.blog")),
]
# In foo/urls/blog.py
from django.urls import path
from . import views
urlpatterns = [
path("", views.blog.index),
path("archive/", views.blog.archive),
]
In the above example, the captured "username"
variable is passed to the
included URLconf, as expected.
Melewatkan pilihan tambahan untuk melihat fungsi¶
URLconfs have a hook that lets you pass extra arguments to your view functions, as a Python dictionary.
The path()
function can take an optional third argument
which should be a dictionary of extra keyword arguments to pass to the view
function.
Sebagai contoh:
from django.urls import path
from . import views
urlpatterns = [
path("blog/<int:year>/", views.year_archive, {"foo": "bar"}),
]
Dalam contoh ini, untuk permintaan ke /blog/2005/
, Django akan memanggil views.year_archive(permintaan, year=2005, foo='bar')
.
This technique is used in the syndication framework to pass metadata and options to views.
Berurusan dengan pertentangan
It's possible to have a URL pattern which captures named keyword arguments, and also passes arguments with the same names in its dictionary of extra arguments. When this happens, the arguments in the dictionary will be used instead of the arguments captured in the URL.
Melewatkan pilihan tambahan untuk include()
¶
Similarly, you can pass extra options to include()
and
each line in the included URLconf will be passed the extra options.
Sebagai contoh, kumpulan URLcond dua ini adalah kegunaannya mirip:
Setel satu:
# main.py
from django.urls import include, path
urlpatterns = [
path("blog/", include("inner"), {"blog_id": 3}),
]
# inner.py
from django.urls import path
from mysite import views
urlpatterns = [
path("archive/", views.archive),
path("about/", views.about),
]
Setel dua:
# main.py
from django.urls import include, path
from mysite import views
urlpatterns = [
path("blog/", include("inner")),
]
# inner.py
from django.urls import path
urlpatterns = [
path("archive/", views.archive, {"blog_id": 3}),
path("about/", views.about, {"blog_id": 3}),
]
Note that extra options will always be passed to every line in the included URLconf, regardless of whether the line's view actually accepts those options as valid. For this reason, this technique is only useful if you're certain that every view in the included URLconf accepts the extra options you're passing.
Membalikkan resolusi URL¶
A common need when working on a Django project is the possibility to obtain URLs in their final forms either for embedding in generated content (views and assets URLs, URLs shown to the user, etc.) or for handling of the navigation flow on the server side (redirections, etc.)
It is strongly desirable to avoid hard-coding these URLs (a laborious, non-scalable and error-prone strategy). Equally dangerous is devising ad-hoc mechanisms to generate URLs that are parallel to the design described by the URLconf, which can result in the production of URLs that become stale over time.
Dengan kata lain, apa yang dibutuhkan adalah mekanisme DRY. Diantara keuntungan lain itu akan mengizinkan evolusi dari rancangan URL tanpa harus pergi ke semua kode sumber proyek untuk mencari dan mengganti URL usang.
The primary piece of information we have available to get a URL is an identification (e.g. the name) of the view in charge of handling it. Other pieces of information that necessarily must participate in the lookup of the right URL are the types (positional, keyword) and values of the view arguments.
Django provides a solution such that the URL mapper is the only repository of the URL design. You feed it with your URLconf and then it can be used in both directions:
Starting with a URL requested by the user/browser, it calls the right Django view providing any arguments it might need with their values as extracted from the URL.
Dimulai dengan pencirian dari tampilan Django sesuai ditambah nilai-nilai dari argumen yang akan dilewatkan ke itu, ambil URL terkait.
The first one is the usage we've been discussing in the previous sections. The second one is what is known as reverse resolution of URLs, reverse URL matching, reverse URL lookup, or simply URL reversing.
Django provides tools for performing URL reversing that match the different layers where URLs are needed:
Dalam cetakan: Menggunakan etiket cetakan
url
.Dalam kode Python: Menggunakan fungsi
reverse()
.In higher level code related to handling of URLs of Django model instances: The
get_absolute_url()
method.
Contoh¶
Pertimbangkan kembali masukan URLconf ini:
from django.urls import path
from . import views
urlpatterns = [
# ...
path("articles/<int:year>/", views.year_archive, name="news-year-archive"),
# ...
]
Menurut rancangan ini, URL untuk arsip yang sesuai pada tahun nnnn adalah /articles/<nnnn>/
.
Anda dapat mendapatkan ini dalam kode cetakan dengan menggunakan:
<a href="{% url 'news-year-archive' 2012 %}">2012 Archive</a>
{# Or with the year in a template context variable: #}
<ul>
{% for yearvar in year_list %}
<li><a href="{% url 'news-year-archive' yearvar %}">{{ yearvar }} Archive</a></li>
{% endfor %}
</ul>
Atau di kode Phyton
from django.http import HttpResponseRedirect
from django.urls import reverse
def redirect_to_year(request):
# ...
year = 2006
# ...
return HttpResponseRedirect(reverse("news-year-archive", args=(year,)))
If, for some reason, it was decided that the URLs where content for yearly article archives are published at should be changed then you would only need to change the entry in the URLconf.
In some scenarios where views are of a generic nature, a many-to-one relationship might exist between URLs and views. For these cases the view name isn't a good enough identifier for it when comes the time of reversing URLs. Read the next section to know about the solution Django provides for this.
Menamai pola URL¶
In order to perform URL reversing, you'll need to use named URL patterns as done in the examples above. The string used for the URL name can contain any characters you like. You are not restricted to valid Python names.
When naming URL patterns, choose names that are unlikely to clash with other
applications' choice of names. If you call your URL pattern comment
and another application does the same thing, the URL that
reverse()
finds depends on whichever pattern is last in
your project's urlpatterns
list.
Putting a prefix on your URL names, perhaps derived from the application
name (such as myapp-comment
instead of comment
), decreases the chance
of collision.
You can deliberately choose the same URL name as another application if you
want to override a view. For example, a common use case is to override the
LoginView
. Parts of Django and most
third-party apps assume that this view has a URL pattern with the name
login
. If you have a custom login view and give its URL the name login
,
reverse()
will find your custom view as long as it's in
urlpatterns
after django.contrib.auth.urls
is included (if that's
included at all).
You may also use the same name for multiple URL patterns if they differ in
their arguments. In addition to the URL name, reverse()
matches the number of arguments and the names of the keyword arguments. Path
converters can also raise ValueError
to indicate no match, see
Registering custom path converters for details.
Namespace URL¶
Kata Pengantar¶
URL namespaces allow you to uniquely reverse named URL patterns even if different applications use the same URL names. It's a good practice for third-party apps to always use namespaced URLs (as we did in the tutorial). Similarly, it also allows you to reverse URLs if multiple instances of an application are deployed. In other words, since multiple instances of a single application will share named URLs, namespaces provide a way to tell these named URLs apart.
Django applications that make proper use of URL namespacing can be deployed
more than once for a particular site. For example django.contrib.admin
has an AdminSite
class which allows you to
deploy more than one instance of the admin. In a
later example, we'll discuss the idea of deploying the polls application from
the tutorial in two different locations so we can serve the same functionality
to two different audiences (authors and publishers).
Sebuah namespace URL datang dalam dua bagian, keduanya adalah string:
- namespace aplikasi¶
This describes the name of the application that is being deployed. Every instance of a single application will have the same application namespace. For example, Django's admin application has the somewhat predictable application namespace of
'admin'
.- namespace instance¶
Ini mencirikan instance khusus dari sebuah aplikasi. Namespace-namespace instance harus unik terhadap keseluruhan proyen anda. Bagaimanapun, sebuah namespace instance dapat berupa sama seperti namespace aplikasi. Ini digunakan untuk menentukan instance awalan dari sebuah aplikasi. Sebagai contoh, instance admin Django awalan mempunyai sebuah namespace instance dari
'admin'
.
URL namespace ditentukan menggunakan penghubung ':'
. Sebagai contoh, halaman indeks utama dari aplikasi admin diacukan menggunakan 'admin:index'
. Ini menunjukkan sebuah namespace dari 'admin'
, dan sebuah URL bernama dari 'index'
.
Namespace juga dapat bersarang. URL bernama 'sports:polls:index'
akan terlihat untuk sebuah pola bernama 'index'
dalam namespace 'polls'
yag itu sendiri ditentukan dalam namespace tingkat-atas 'sports'
.
Reversing namespaced URLs¶
When given a namespaced URL (e.g. 'polls:index'
) to resolve, Django splits
the fully qualified name into parts and then tries the following lookup:
Pertama, Django mencari untuk kecocokan application namespace (dalam contoh ini,
'polls'
). Ini akan menghasilkan daftar dari instance dari aplikasi itu.Jika ada aplikasi saat ini ditentukan, Django menemukan dan mengembalikan penyelesai URL untuk instance itu. Aplikasi saat ini dapat ditentukan dengan argumen
current_app
ke fungsireverse()
.The
url
template tag uses the namespace of the currently resolved view as the current application in aRequestContext
. You can override this default by setting the current application on therequest.current_app
attribute.If there is no current application, Django looks for a default application instance. The default application instance is the instance that has an instance namespace matching the application namespace (in this example, an instance of
polls
called'polls'
).If there is no default application instance, Django will pick the last deployed instance of the application, whatever its instance name may be.
If the provided namespace doesn't match an application namespace in step 1, Django will attempt a direct lookup of the namespace as an instance namespace.
If there are nested namespaces, these steps are repeated for each part of the namespace until only the view name is unresolved. The view name will then be resolved into a URL in the namespace that has been found.
Contoh¶
To show this resolution strategy in action, consider an example of two instances
of the polls
application from the tutorial: one called 'author-polls'
and one called 'publisher-polls'
. Assume we have enhanced that application
so that it takes the instance namespace into consideration when creating and
displaying polls.
from django.urls import include, path
urlpatterns = [
path("author-polls/", include("polls.urls", namespace="author-polls")),
path("publisher-polls/", include("polls.urls", namespace="publisher-polls")),
]
from django.urls import path
from . import views
app_name = "polls"
urlpatterns = [
path("", views.IndexView.as_view(), name="index"),
path("<int:pk>/", views.DetailView.as_view(), name="detail"),
...,
]
Menggunakan pengaturan ini, pencarian berikut adalah mungkin:
If one of the instances is current - say, if we were rendering the detail page in the instance
'author-polls'
-'polls:index'
will resolve to the index page of the'author-polls'
instance; i.e. both of the following will result in"/author-polls/"
.Dalam metode dari tampilan berdasarkan-kelas:
reverse("polls:index", current_app=self.request.resolver_match.namespace)
dan di cetakan:
{% url 'polls:index' %}
If there is no current instance - say, if we were rendering a page somewhere else on the site -
'polls:index'
will resolve to the last registered instance ofpolls
. Since there is no default instance (instance namespace of'polls'
), the last instance ofpolls
that is registered will be used. This would be'publisher-polls'
since it's declared last in theurlpatterns
.'author-polls:index'
will always resolve to the index page of the instance'author-polls'
(and likewise for'publisher-polls'
) .
If there were also a default instance - i.e., an instance named 'polls'
-
the only change from above would be in the case where there is no current
instance (the second item in the list above). In this case 'polls:index'
would resolve to the index page of the default instance instead of the instance
declared last in urlpatterns
.
Namespace URL dan URLconf disertakan¶
Namespace-namespace aplikasi dari URLconf disertakan dapat ditentukan dalam dua cara.
Firstly, you can set an app_name
attribute in the included URLconf module,
at the same level as the urlpatterns
attribute. You have to pass the actual
module, or a string reference to the module, to include()
,
not the list of urlpatterns
itself.
from django.urls import path
from . import views
app_name = "polls"
urlpatterns = [
path("", views.IndexView.as_view(), name="index"),
path("<int:pk>/", views.DetailView.as_view(), name="detail"),
...,
]
from django.urls import include, path
urlpatterns = [
path("polls/", include("polls.urls")),
]
URL ditentukan dalam polls.urls
akan memiliki sebuah namespace aplikasi polls
.
Secondly, you can include an object that contains embedded namespace data. If
you include()
a list of path()
or
re_path()
instances, the URLs contained in that object
will be added to the global namespace. However, you can also include()
a
2-tuple containing:
(<list of path()/re_path() instances>, <application namespace>)
Sebagai contoh:
from django.urls import include, path
from . import views
polls_patterns = (
[
path("", views.IndexView.as_view(), name="index"),
path("<int:pk>/", views.DetailView.as_view(), name="detail"),
],
"polls",
)
urlpatterns = [
path("polls/", include(polls_patterns)),
]
Ini akan menyertakan pola URL ditunjuk kedalam namespace aplikasi diberikan.
The instance namespace can be specified using the namespace
argument to
include()
. If the instance namespace is not specified,
it will default to the included URLconf's application namespace. This means
it will also be the default instance for that namespace.