Инструкцией include подключить файл homepage urls py
В этом уроке мы расскажем о создании базового приложения для голосования.
Он будет состоять из двух частей:
- Публичный сайт, который позволяет людям просматривать опросы и голосовать в них.
- Сайт администратора, который позволяет добавлять, изменять и удалять опросы.
Мы предполагаем, что вы уже установили Django . Вы можете узнать, установлена ли Django и какая версия, выполнив в командной строке следующую команду (указывается префиксом $):
Этот учебник написан для Django 4.0, который поддерживает Python 3.8 и более поздние версии. Если версия Django не совпадает, вы можете обратиться к учебнику для вашей версии Django, используя переключатель версий в правом нижнем углу этой страницы, или обновить Django до самой новой версии. Если вы используете более старую версию Python, проверьте Какие версии Python можно использовать с Django? , чтобы найти совместимую версию Django.
Смотрите Как установить Django , чтобы узнать как удалить старые версии Django и установить последнюю версию.
Где можно получить помощь:
Если у вас возникли проблемы с прохождением этого руководства, перейдите в раздел часто задаваемых вопросов Получение справки .
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:
- A regex class attribute, as a 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 raise ValueError if it can’t convert the given value. A ValueError 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 raise ValueError if it can’t convert the given value. A ValueError is interpreted as no match and as a consequence reverse() will raise NoReverseMatch unless another URL pattern matches.
Register custom converter classes in your URLconf using register_converter() :
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.
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.
Передача дополнительных аргументов в include() ¶
Similarly, you can pass extra options to include() and each line in the included URLconf will be passed the extra options.
Например, эти два URLconf работают идентично:
Дополнительные аргументы всегда передаются каждому представлению во включенном URLconf, независимо от того, принимает оно эти аргументы или нет. Поэтому, такой подход полезен только если вы уверенны, что каждое представление принимает передаваемые аргументы.
handler403 ¶
A callable, or a string representing the full Python import path to the view that should be called if the user doesn’t have the permissions required to access a resource.
The development server¶
Let’s verify your Django project works. Change into the outer mysite directory, if you haven’t already, and run the following commands:
You’ll see the following output on the command line:
Ignore the warning about unapplied database migrations for now; we’ll deal with the database shortly.
You’ve started the Django development server, a lightweight web server written purely in Python. We’ve included this with Django so you can develop things rapidly, without having to deal with configuring a production server – such as Apache – until you’re ready for production.
Now’s a good time to note: don’t use this server in anything resembling a production environment. It’s intended only for use while developing. (We’re in the business of making web frameworks, not web servers.)
Changing the port
By default, the runserver command starts the development server on the internal IP at port 8000.
If you want to change the server’s port, pass it as a command-line argument. For instance, this command starts the server on port 8080:
If you want to change the server’s IP, pass it along with the port. For example, to listen on all available public IPs (which is useful if you are running Vagrant or want to show off your work on other computers on the network), use:
0 is a shortcut for 0.0.0.0. Full docs for the development server can be found in the runserver reference.
Automatic reloading of runserver
The development server automatically reloads Python code for each request as needed. You don’t need to restart the server for code changes to take effect. However, some actions like adding files don’t trigger a restart, so you’ll have to restart the server in these cases.
path() argument: route ¶
route is a string that contains a URL pattern. When processing a request, Django starts at the first pattern in urlpatterns and makes its way down the list, comparing the requested URL against each pattern until it finds one that matches.
Сервер разработки¶
Давайте проверим, работает ли ваш проект Django. Перейдите во внешний каталог mysite , если вы этого еще не сделали, и выполните следующие команды:
Вы увидите следующий вывод в командной строке:
Пока игнорируйте предупреждение о непримененных миграциях базы данных; мы разберемся с базой данных в ближайшее время.
Вы запустили сервер разработки Django - легкий веб-сервер, написанный исключительно на Python. Мы включили его в Django, чтобы вы могли быстро разрабатывать вещи, не занимаясь настройкой производственного сервера - такого как Apache - до тех пор, пока вы не будете готовы к производству.
Сейчас самое время отметить: не используйте этот сервер в чем-либо, напоминающем производственную среду. Он предназначен только для использования во время разработки. (Мы занимаемся созданием веб-фреймворков, а не веб-серверов).
По умолчанию команда runserver запускает сервер разработки на внутреннем IP адресе с портом 8000.
Для смены порта передайте его аргументом в командной строке. Например, эта команда запускает сервер на порту 8080:
Для изменения IP адреса сервера, передайте его вместе с портом. Например, чтобы использовать все доступные публичные IP-адреса (что полезно, если вы работаете с Vagrant или хотите показать свою работу на других компьютерах в сети), используйте:
0 это сокращение для 0.0.0.0. Полная документация по серверу разработки находится в руководстве runserver .
Сервер разработки автоматически перезагружает код Python для каждого запроса по мере необходимости. Вам не нужно перезагружать сервер, чтобы изменения в коде вступили в силу. Однако некоторые действия, такие как добавление файлов, в эти условия не входят, поэтому вам придется перезапустить сервер в этих случаях.
Specifying defaults for view arguments¶
A convenient trick is to specify default parameters for your views’ arguments. Here’s an example URLconf and view:
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.
Including other URLconfs¶
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:
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:
In this example, the /credit/reports/ URL will be handled by the credit_views.report() Django view.
This can be used to remove redundancy from URLconfs where a single pattern prefix is used repeatedly. For example, consider this URLconf:
We can improve this by stating the common path prefix only once and grouping the suffixes that differ:
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:
- A regex class attribute, as a 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 raise ValueError if it can’t convert the given value. A ValueError 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.
Register custom converter classes in your URLconf using register_converter() :
Производительность¶
Каждое регулярное выражение в urlpatterns будет скомпилировано при первом использовании. Это делает систему невероятно быстрой.
Captured parameters¶
An included URLconf receives any captured parameters from parent URLconfs, so the following example is valid:
In the above example, the captured "username" variable is passed to the included URLconf, as expected.
Создание приложения Polls¶
Теперь, когда ваше окружение - «проект» - настроено, вы можете приступить к дальнейшей работе.
Каждое приложение, которое вы пишете в Django, состоит из пакета Python, который следует определенному соглашению. Django поставляется с утилитой, которая автоматически генерирует базовую структуру каталогов приложения, поэтому вы можете сосредоточиться на написании кода, а не на создании каталогов.
Проекты и приложения
В чем разница между проектом и приложением? Приложение - это веб-приложение, которое что-то делает - например, система блогов, база данных публичных записей или небольшое приложение для проведения опросов. Проект - это набор конфигураций и приложений для определенного веб-сайта. Проект может содержать несколько приложений. Приложение может находиться в нескольких проектах.
Ваши приложения могут находиться где угодно в вашем пути Python . В этом руководстве мы создадим наше приложение для опроса в том же каталоге, что и ваш файл manage.py , чтобы его можно было импортировать как отдельный модуль верхнего уровня, а не как подмодуль mysite .
Чтобы создать приложение, убедитесь, что вы находитесь в том же каталоге, что и manage.py , и введите следующую команду:
Чистая, элегантная схема URL-ов – это важная часть качественного приложения. Django позволяет проектировать URL-адреса как вы пожелаете, без ограничений «фреймворка».
Читайте Cool URIs don’t change, создателя World Wide Web, Тима Бернерса-Ли, чтобы узнать почему URL-ы должны быть красивыми и практичными.
Обработчики ошибок¶
When Django can’t find a match for the requested URL, or when an exception is raised, Django invokes an error-handling view.
Эти представления определены в четырёх переменных. Их значения по-умолчанию должны подойти для большинства проектов, но вы можете их поменять при необходимости.
Эти значения должны быть определены в главном URLconf.
Значение это функции, или полный путь для импорта, которая будет вызвана, если не был найден подходящий URL-шаблон.
Есть следующие переменные:
- handler400 – Смотрите django.conf.urls.handler400 .
- handler403 – Смотрите django.conf.urls.handler403 .
- handler404 – Смотрите django.conf.urls.handler404 .
- handler500 – Смотрите django.conf.urls.handler500 .
URL namespaces¶
Пространства имен в конфигурации URL-ов¶
Using regular expressions¶
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 (?Ppattern) , 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:
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.
Support Us
© 2005-2022 Django Software Foundation and individual contributors. Django is a registered trademark of the Django Software Foundation.
Throughout this tutorial, we’ll walk you through the creation of a basic poll application.
It’ll consist of two parts:
- A public site that lets people view polls and vote in them.
- An admin site that lets you add, change, and delete polls.
We’ll assume you have Django installed already. You can tell Django is installed and which version by running the following command in a shell prompt (indicated by the $ prefix):
If Django is installed, you should see the version of your installation. If it isn’t, you’ll get an error telling “No module named django”.
This tutorial is written for Django 4.0, which supports Python 3.8 and later. If the Django version doesn’t match, you can refer to the tutorial for your version of Django by using the version switcher at the bottom right corner of this page, or update Django to the newest version. If you’re using an older version of Python, check What Python version can I use with Django? to find a compatible version of Django.
See How to install Django for advice on how to remove older versions of Django and install a newer one.
Where to get help:
If you’re having trouble going through this tutorial, please head over to the Getting Help section of the FAQ.
Примеры¶
Рассмотрим следующий URLconf:
According to this design, the URL for the archive corresponding to year nnnn is /articles// .
Вы можете получить его в шаблоне следующим образом:
Если по каким-либо причинам необходимо будет изменить URL, достаточно будет изменить запись в вашем URLconf.
В некоторых случаях URL-ы и представления могут соотноситься как многое-к-одному. В таких случаях название представления не может идентифицировать конкретный URL. Как решить эту проблему читайте в следующем разделе.
Например¶
Вот пример простого URLconf:
- To capture a value from the URL, use angle brackets.
- Captured values can optionally include a converter type. For example, use to capture an integer parameter. If a converter isn’t included, any string, excluding a / character, is matched.
- There’s no need to add a leading slash, because every URL has that. For example, it’s articles , not /articles .
- A request to /articles/2005/03/ would match the third entry in the list. Django would call the function views.month_archive(request, year=2005, month=3) .
- /articles/2003/ соответствует первому выражению, не второму, потому что шаблоны проверяются по порядку и берется первый найденный. Не стесняйтесь использовать порядок для обработки различных ситуаций, таких как эта. В данном примере Django вызовет функцию views.special_case_2003(request) .
- /articles/2003 не соответствует ни одному регулярному выражению, потому что каждое ожидает, что URL оканчивается на косую черту.
- /articles/2003/03/building-a-django-site/ would match the final pattern. Django would call the function views.article_detail(request, year=2003, month=3, slug="building-a-django-site") .
Support Django!
Overview¶
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.
Reverse resolution of URLs¶
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.
In other words, what’s needed is a DRY mechanism. Among other advantages it would allow evolution of the URL design without having to go over all the project source code to search and replace outdated URLs.
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.
- Starting with the identification of the corresponding Django view plus the values of arguments that would be passed to it, obtain the associated URL.
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:
- In templates: Using the url template tag.
- In Python code: Using the reverse() function.
- In higher level code related to handling of URLs of Django model instances: The get_absolute_url() method.
Getting help
Follow Us
Creating a project¶
If this is your first time using Django, you’ll have to take care of some initial setup. Namely, you’ll need to auto-generate some code that establishes a Django project – a collection of settings for an instance of Django, including database configuration, Django-specific options and application-specific settings.
From the command line, cd into a directory where you’d like to store your code, then run the following command:
This will create a mysite directory in your current directory. If it didn’t work, see Problems running django-admin .
You’ll need to avoid naming projects after built-in Python or Django components. In particular, this means you should avoid using names like django (which will conflict with Django itself) or test (which conflicts with a built-in Python package).
Where should this code live?
If your background is in plain old PHP (with no use of modern frameworks), you’re probably used to putting code under the web server’s document root (in a place such as /var/www ). With Django, you don’t do that. It’s not a good idea to put any of this Python code within your web server’s document root, because it risks the possibility that people may be able to view your code over the web. That’s not good for security.
Put your code in some directory outside of the document root, such as /home/mycode .
Let’s look at what startproject created:
- The outer mysite/ root directory is a container for your project. Its name doesn’t matter to Django; you can rename it to anything you like.
- manage.py : A command-line utility that lets you interact with this Django project in various ways. You can read all the details about manage.py in django-admin and manage.py .
- The inner mysite/ directory is the actual Python package for your project. Its name is the Python package name you’ll need to use to import anything inside it (e.g. mysite.urls ).
- mysite/__init__.py : An empty file that tells Python that this directory should be considered a Python package. If you’re a Python beginner, read more about packages in the official Python docs.
- mysite/settings.py : Settings/configuration for this Django project. Django settings will tell you all about how settings work.
- mysite/urls.py : The URL declarations for this Django project; a “table of contents” of your Django-powered site. You can read more about URLs in URL dispatcher .
- mysite/asgi.py : An entry-point for ASGI-compatible web servers to serve your project. See How to deploy with ASGI for more details.
- mysite/wsgi.py : An entry-point for WSGI-compatible web servers to serve your project. See How to deploy with WSGI for more details.
Вложенные аргументы¶
Регулярные выражения позволяют использовать вложенные аргументы, и Django может их найти и передать в представление. Во время поиска аргументов Django попытается получить самый внешний аргумент, игнорируя вложенные аргументы. Возьмем следующие шаблоны URL-ов, которые принимает необязательный номер страницы:
Оба шаблона используют вложенные аргументы и могут обрабатывать URL-ы: например, для blog/page-2/ будет найдено представление blog_articles с двумя позиционными аргументами page-2/ и 2 . Второй URL-шаблон для comments для comments/page-2/ найдет именованный аргумент page_number со значеним 2. Внешний аргумент в этом случае не захватываемый из-за (. ) .
При получении URL-а для представления blog_articles необходимо указать самый внешний аргумент( page-2/ ) или ни одного аргумента в данном случае. В то время как для comments необходимо передать значение page_number или не одного аргумента.
Вложенные захватываемые аргументы создают сильную связанность между URL и аргументами представления, как это показано для blog_articles : представление получает часть URL-а ( page-2/ ) вместо значение, которое на самом деле необходимо представлению. Эта связанность особенно заметна при создании URL-а т.к. необходимо передать часть URL-а вместо номера страницы.
Как правило, URL-шаблон должен захватывать только необходимые для представления аргументы.
Обзор¶
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).
Эта конфигурация может быть короткой или длинной настолько, насколько это нужно. Она может ссылаться на другие конфигурации. И, так как это код Python, может создаваться динамически.
Django также предоставляет метод для перевода URL на текущий язык. Обратитесь к документации на интернационализацию для подробностей.
Naming URL patterns¶
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.
Поиск URL-а по шаблону с пространством имен¶
Если необходимо найти URL по названию с пространством имен (например, 'polls:index' ), Django разбивает название на части и следует такому алгоритму:
Первым делом, Django проверяет название(пространсву имен) приложения (например, polls ). Django получает список экземпляров приложения.
If there is a current application defined, Django finds and returns the URL resolver for that instance. The current application can be specified with the current_app argument to the reverse() function.
Шаблонный тег url использует пространство имен представления как текущее приложение в RequestContext . Вы можете переопределить его, указав в атрибуте request.current_app .
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' ).
Если экземпляр по-умолчанию не найден, Django возьмет последний установленный экземпляр приложения, не обращая внимание на его название.
Если на первом шаге не было найдено приложение по указанному пространству имен, Django попытается найти экземпляр приложения по его названию, используя пространство имен как название экземпляра.
Если пространство имен вложенное, этот процесс будет повторен, пока неопределенным не останется только название представления. URL для названия представления будет искаться среди URL-шаблонов определенных в приложении, найденном через пространство имен.
Например¶
Разберем небольшой пример. У нас есть два экземпляра приложения polls : один назван 'author-polls' , другой - 'publisher-polls' . Предположим, что мы уже изменили код приложения и оно учитывает текущее пространство имен при создании страниц.
Returns an element for inclusion in urlpatterns . For example:
The route argument should be a string or gettext_lazy() (see Translating URL patterns ) that contains a URL pattern. The string may contain angle brackets (like above) to capture part of the URL and send it as a keyword argument to the view. The angle brackets may include a converter specification (like the int part of ) which limits the characters matched and may also change the type of the variable passed to the view. For example, matches a string of decimal digits and converts the value to an int . See How Django processes a request for more details.
The view argument is a view function or the result of as_view() for class-based views. It can also be an django.urls.include() .
The kwargs argument allows you to pass additional arguments to the view function or method. See Passing extra options to view functions for an example.
See Naming URL patterns for why the name argument is useful.
Contents
Значения по умолчанию для аргументов представления¶
Принято указывать значения по-умолчанию для аргументов представления. Пример URLconf и представления:
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.
Browse
- Django 4.0 documentation
- django.urls functions for use in URLconfs
- To capture a value from the URL, use angle brackets.
- Captured values can optionally include a converter type. For example, use to capture an integer parameter. If a converter isn’t included, any string, excluding a / character, is matched.
- There’s no need to add a leading slash, because every URL has that. For example, it’s articles , not /articles .
- A request to /articles/2005/03/ would match the third entry in the list. Django would call the function views.month_archive(request, 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 function views.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 function views.article_detail(request, year=2003, month=3, slug="building-a-django-site") .
- Внешний корневой каталог mysite/ — это контейнер для вашего проекта. Его имя не имеет значения для Джанго; Вы можете переименовать его на что угодно.
- manage.py : утилита, позволяющая взаимодействовать с проектом различными способами. Вы можете прочитать все подробности о manage.py в django-admin и manage.py .
- Внутренний каталог mysite/ это Python модуль вашего проекта. Его название вы будете использовать для импорта чего-либо из этого модуля (например, mysite.urls ).
- mysite/__init__.py : пустой файл, который сообщает Python, что этот каталог должен рассматриваться как пакет Python’а. Если вы новичок в Python, прочитайте больше о пакетах в официальной документации Python.
- mysite/settings.py : Конфигурация и настройки проекта Django. В Настройки Django рассказано все о том, как работают настройки.
- mysite/urls.py : указание URL проекта на Django, можно сказать, что это «оглавление» вашего проекта. Прочитайте больше информации о URL в Диспетчер URL .
- mysite/asgi.py : точка входа для ASGI-совместимых веб-серверов для обслуживания вашего проекта. Смотрите Как развертывать с помощью ASGI для получения более подробной информации.
- mysite/wsgi.py : Точка входа для WSGI совместимых веб-серверов для работы с проектом. Смотрите Как развертывать с помощью WSGI для уточнения деталей работы.
- handler400 – See django.conf.urls.handler400 .
- handler403 – See django.conf.urls.handler403 .
- handler404 – See django.conf.urls.handler404 .
- handler500 – See django.conf.urls.handler500 .
- module – URLconf module (or module name)
- namespace (str) – Instance namespace for the URL entries being included
- pattern_list – Iterable of path() and/or re_path() instances.
- app_namespace (str) – Application namespace for the URL entries being included
- 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.
- Получая запрошенный URL находит необходимое представление и предоставляет все необходимые аргументы полученные из URL-а.
- Получая идентификатор представления и передаваемые ему аргументы, возвращает URL.
- В шаблонах: Использование шаблонного тега url .
- In Python code: Using the reverse() function.
- На более высоком уровне для привязки URL-ов к моделям - метод get_absolute_url() .
path() argument: name ¶
Naming your URL lets you refer to it unambiguously from elsewhere in Django, especially from within templates. This powerful feature allows you to make global changes to the URL patterns of your project while only touching a single file.
When you’re comfortable with the basic request and response flow, read part 2 of this tutorial to start working with the database.
A clean, elegant URL scheme is an important detail in a high-quality web application. Django lets you design URLs however you want, with no framework limitations.
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.
Передача дополнительных аргументов в представление¶
Конфигурация URL-ов позволяет определить дополнительные аргументы для функции представления, используя словарь Python.
The path() function can take an optional third argument which should be a dictionary of extra keyword arguments to pass to the view function.
In this example, for a request to /blog/2005/ , Django will call views.year_archive(request, year=2005, foo='bar') .
Такой подход используется в syndication framework для передачи параметров и дополнительных данных в представление.
Если регулярное выражение URL-шаблона выделяет из URL-а аргумент с названием, которое уже используется в дополнительных именованных аргументах, будет использован аргумент из словаря дополнительных аргументов, вместо значения из URL.
Examples¶
Consider again this URLconf entry:
According to this design, the URL for the archive corresponding to year nnnn is /articles// .
You can obtain these in template code by using:
Or in Python code:
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.
register_converter() ¶
The function for registering a converter for use in path() route s.
The converter argument is a converter class, and type_name is the converter name to use in path patterns. See Registering custom path converters for an example.
Path converters¶
The following path converters are available by default:
static() ¶
Helper function to return a URL pattern for serving files in debug mode:
Passing extra options to include() ¶
Similarly, you can pass extra options to include() and each line in the included URLconf will be passed the extra options.
For example, these two URLconf sets are functionally identical:
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.
Path converters¶
The following path converters are available by default:
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:
First, Django looks for a matching application namespace (in this example, 'polls' ). This will yield a list of instances of that application.
If there is a current application defined, Django finds and returns the URL resolver for that instance. The current application can be specified with the current_app argument to the reverse() function.
The url template tag uses the namespace of the currently resolved view as the current application in a RequestContext . You can override this default by setting the current application on the request.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.
Example¶
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.
Example¶
Here’s a sample URLconf:
Именованные URL-шаблоны¶
Для того, чтобы выполнить обратное разрешение URL, вам потребуется использовать именованные URL шаблоны, как это показано в примерах выше. Строка, использованная для наименования URL, может содержать любые символы. Вы не ограничены только теми именами, что позволяет Python.
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.
Nested arguments¶
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:
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.
handler404 ¶
A callable, or a string representing the full Python import path to the view that should be called if none of the URL patterns match.
Syntax of the urlpatterns variable¶
urlpatterns should be a sequence of path() and/or re_path() instances.
Создание проекта¶
Если вы раньше Django не использовали, то необходимо позаботиться о начальной настройке. А именно, необходимо автоматически сгенерировать определенный код, который устанавливает Django project — набор настроек для конкретного экземпляра Django, включающий в себя конфигурацию базы данных, специфичные для Django опции специфичные настройки для приложения.
Выполните в терминале в командной строке cd : смену каталога на тот, в котором вы сохранили код, затем запустите следующую команду:
Это создаст каталог mysite в текущем каталоге. Если этого не произошло, то смотрите Проблемы с запуском django-admin .
Не рекомендуется в качестве названия проекта названия встроенных компонентов Python или Django. Это значит, что следует избегать использования таких имен, как django (будет конфликт с самим фреймворком) или test (будет конфликтовать со стандартным пакетом Python).
Где этот код должен находится?
Если вы работаете на старом добром PHP (без использования современных фреймворков), вы, вероятно, привыкли размещать код в корне документа веб-сервера (в таком месте, как /var/www ). В Django вы этого не сделаете. Это не очень хорошая идея - помещать любой из этого кода Python в корень документа вашего веб-сервера, потому что это рискует тем, что люди могут иметь возможность просматривать ваш код через Интернет. Это не очень хорошо для безопасности.
Размещайте свой код в каком-либо каталоге вне корневого каталога сервера, например /home/mycode .
Давайте посмотрим на результат выполнения команды startproject :
Разберем, для чего нужны эти файлы и каталоги:
Syntax of the urlpatterns variable¶
urlpatterns should be a sequence of path() and/or re_path() instances.
Creating the Polls app¶
Now that your environment – a “project” – is set up, you’re set to start doing work.
Each application you write in Django consists of a Python package that follows a certain convention. Django comes with a utility that automatically generates the basic directory structure of an app, so you can focus on writing code rather than creating directories.
Projects vs. apps
What’s the difference between a project and an app? An app is a web application that does something – e.g., a blog system, a database of public records or a small poll app. A project is a collection of configuration and apps for a particular website. A project can contain multiple apps. An app can be in multiple projects.
Your apps can live anywhere on your Python path . In this tutorial, we’ll create our poll app in the same directory as your manage.py file so that it can be imported as its own top-level module, rather than a submodule of mysite .
To create your app, make sure you’re in the same directory as manage.py and type this command:
That’ll create a directory polls , which is laid out like this:
This directory structure will house the poll application.
path() argument: view ¶
handler400 ¶
Introduction¶
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).
A URL namespace comes in two parts, both of which are strings:
application namespace 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' . instance namespace This identifies a specific instance of an application. Instance namespaces should be unique across your entire project. However, an instance namespace can be the same as the application namespace. This is used to specify a default instance of an application. For example, the default Django admin instance has an instance namespace of 'admin' .
Namespaced URLs are specified using the ':' operator. For example, the main index page of the admin application is referenced using 'admin:index' . This indicates a namespace of 'admin' , and a named URL of 'index' .
Namespaces can also be nested. The named URL 'sports:polls:index' would look for a pattern named 'index' in the namespace 'polls' that is itself defined within the top-level namespace 'sports' .
Error handling¶
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.
See the documentation on customizing error views for the full details.
Such values can be set in your root URLconf. Setting these variables in any other URLconf will have no effect.
Values must be callables, or strings representing the full Python import path to the view that should be called to handle the error condition at hand.
include() ¶
include (module, namespace=None)¶ include (pattern_list) include ((pattern_list, app_namespace), namespace=None)
A function that takes a full Python import path to another URLconf module that should be “included” in this place. Optionally, the application namespace and instance namespace where the entries will be included into can also be specified.
Usually, the application namespace should be specified by the included module. If an application namespace is set, the namespace argument can be used to set a different instance namespace.
include() also accepts as an argument either an iterable that returns URL patterns or a 2-tuple containing such iterable plus the names of the application namespaces.
Learn More
Download:
Offline (Django 4.0): HTML | PDF | ePub
Provided by Read the Docs.Using unnamed regular expression groups¶
As well as the named group syntax, e.g. (?P4) , you can also use the shorter unnamed group, e.g. (6) .
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.
Как Django обрабатывает запрос¶
При запросе к странице вашего Django-сайта, используется такой алгоритм для определения какой код выполнить:
Django loads that Python module and looks for the variable urlpatterns . This should be a sequence of django.urls.path() and/or django.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:
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 to django.urls.path() or django.urls.re_path() .
In older versions, the keyword arguments with None values are made up also for not provided named parts.
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.
Get Involved
path() argument: kwargs ¶
Arbitrary keyword arguments can be passed in a dictionary to the target view. We aren’t going to use this feature of Django in the tutorial.
Using unnamed regular expression groups¶
As well as the named group syntax, e.g. (?P2) , you can also use the shorter unnamed group, e.g. (5) .
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.
Using regular expressions¶
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 (?Ppattern) , 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:
This accomplishes roughly the same thing as the previous example, except:
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.
re_path() ¶
Returns an element for inclusion in urlpatterns . For example:
The route argument should be a string or gettext_lazy() (see Translating URL patterns ) that contains a regular expression compatible with Python’s re module. Strings typically use raw string syntax ( r'' ) so that they can contain sequences like \d without the need to escape the backslash with another backslash. When a match is made, captured groups from the regular expression are passed to the view – as named arguments if the groups are named, and as positional arguments otherwise. The values are passed as strings, without any type conversion.
When a route ends with $ the whole requested URL, matching against path_info , must match the regular expression pattern ( re.fullmatch() is used).
The view , kwargs and name arguments are the same as for path() .
In older versions, a full-match wasn’t required for a route which ends with $ .
How Django processes a request¶
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:
Нахождение аргументов в URL¶
Включенный URLconf получает все аргументы найденные родительским URLconfs, поэтому этот пример работает:
В примере выше, найденный аргумент "username" передается во включенный URLconf, как и ожидалось.
Описание¶
Пространства имен позволяют получить URL по названию URL-шаблона даже, если несколько приложений используют одинаковые названия. Для сторонних приложений использование пространств имен – хорошая практика (как мы и делали в учебнике). Аналогично можно получить URL, если несколько экземпляров одного приложения подключены в конфигурацию URL-ов.
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).
Пространство имен состоит из двух частей, каждая из которых это строка:
application namespace¶ Указывает название установленного приложения. Все экземпляры одного приложения будет иметь одно название. Например, название приложения администратора Django – admin . instance namespace¶ Идентифицирует конкретный экземпляр приложения. Должно быть уникальным для проекта. Однако, название экземпляра может быть равным названию приложения. Оно используется по-умолчанию при создании приложения. Например, пространство имен приложения администратора Django – admin .
Пространство имен определяется с помощью оператора ':' . Например, главная страница интерфейса администратора определяется как 'admin:index' . Мы видим пространство имен 'admin' , и название URL-шаблона 'index' .
Пространства имен могут быть вложенными. Название URL-а 'sports:polls:index' означает именованный URL-шаблон с названием 'index' в пространстве имен 'polls' , которое было определенно в другом пространстве имен - 'sports' .
Performance¶
Each regular expression in a urlpatterns is compiled the first time it’s accessed. This makes the system blazingly fast.
Что использует URLconf при поиске нужного шаблона URL¶
URLconf использует запрашиваемый URL как обычную строку Python. Он не учитывает параметры GET, POST и имя домена.
URLconf не учитывает тип запроса. Другими словами, все типы запросов – POST , GET , HEAD , и др. – будут обработаны одним представлением при одинаковом URL.
handler500 ¶
A callable, or a string representing the full Python import path to the view that should be called in case of server errors. Server errors happen when you have runtime errors in view code.
Поиск URL-а по URL-шаблону¶
Обычной задачей является получение URL-а по его определению для отображения пользователю или для редиректа.
Очень важно не «хардкодить» URL-ы (трудоемкая и плохо поддерживаемая стратегия). Также не следует создавать «костыли» для генерации URL-ов, которые не следуют задокументированному дизайну URLconf.
В общем необходимо придерживаться принципа DRY. Немаловажно иметь возможность менять URL-ы в одном месте, а не выполнять поиск и замену по всему проекту.
Для получения URL-а нам необходим его идентификатор, то есть название URL-шаблона, и позиционные и именованные аргументы.
В Django для работы с URL-ами используется так называемый «URL mapper». Ему передается URLconf, и теперь его можно использовать в два направления:
Первое это то, что мы уже рассмотрели в предыдущем разделе. Второе называется URL reversing, в общем получение URL-а по его названию.
Django предоставляет инструменты для получения URL-ов в различных компонентах фреймворка:
Write your first view¶
Let’s write the first view. Open the file polls/views.py and put the following Python code in it:
This is the simplest view possible in Django. To call the view, we need to map it to a URL - and for this we need a URLconf.
To create a URLconf in the polls directory, create a file called urls.py . Your app directory should now look like:
In the polls/urls.py file include the following code:
The next step is to point the root URLconf at the polls.urls module. In mysite/urls.py , add an import for django.urls.include and insert an include() in the urlpatterns list, so you have:
The include() function allows referencing other URLconfs. 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.
The idea behind include() is to make it easy to plug-and-play URLs. Since polls are in their own URLconf ( polls/urls.py ), they can be placed under “/polls/”, or under “/fun_polls/”, or under “/content/polls/”, or any other path root, and the app will still work.
You should always use include() when you include other URL patterns. admin.site.urls is the only exception to this.
You have now wired an index view into the URLconf. Verify it’s working with the following command:
The path() function is passed four arguments, two required: route and view , and two optional: kwargs , and name . At this point, it’s worth reviewing what these arguments are for.
Passing extra options to view functions¶
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.
In this example, for a request to /blog/2005/ , Django will call views.year_archive(request, year=2005, foo='bar') .
This technique is used in the syndication framework to pass metadata and options to views.
Dealing with conflicts
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.
Комбинирование URLconfs¶
В любой момент, ваш urlpatterns может «включать» другие модули URLconf.
Вот пример URLconf для сайта Django. Он включает множество других конфигураций URL:
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:
В этом примере URL /credit/reports/ обработан представлением credit_views.report() .
Такой подход может применяться для уменьшения дублирования кода в настройках URL, когда используется один и тот же шаблонный префикс. Например, возьмём такую конфигурацию URL:
Мы можем сделать её проще, указав общий префикс только один раз и сгруппировав различающиеся суффиксы:
Читайте также: