Course Content
Django: First Dive
Django: First Dive
URL
Let's connect our view to the URL.
First, we need to distribute URLs between connected apps. This means that the URL element will point to the corresponding App and its endpoints.
Let's describe the https://your-server.com/storage/list
URL address:
- The
your-server.com/
is an address to the server. - The next part of the URL is an app with features in a specific area. In our case, it is the
storage/
. - All of the following can be specific endpoints for accessing server functionality. In our case is a
list/
, which displays a list of goods.
This distribution allows for clear site navigation and logical separation of server functionality for future updates.
How to do URL distribution?
Step 1. Create the URLs file in App.
Find the connected app folder and create the urls.py
file:
Step 2. Include app URLs to the main core of project.
Open the urls.py
file in the main core of project (in our case, the Main
folder):
Now we need to add our app to the urlpatterns
list using the path()
and include()
functions:
The provided code sets up a URL pattern for the Django project. It defines a URL pattern with the path 'app1/'
that includes the URLs from the 'new_app.urls'
module. The include()
function is used to include the URL patterns from the 'new_app.urls'
module, and the namespace
parameter is set to "NewApp"
, providing a unique namespace for the app's URLs. This configuration allows requests with the path starting with 'app1/'
to be handled by the URLs defined in the 'new_app.urls'
module, with the ability to refer to them using the namespace "NewApp"
.
path
The path()
function is used in Django to define URL patterns within the URL configuration of a Django project. It is imported from the django.urls
module.
The path()
function takes two or more arguments:
- The first argument is a string representing the URL pattern.
- The second argument is the view function or a reference to another URL configuration module using the
include()
function. - Additional arguments can be provided to specify additional parameters, such as a name for the URL pattern or to capture dynamic elements from the URL.
include
The include()
function is used to include other URL configurations from separate files or modules. It is also imported from the django.urls
module.
The include()
function takes at least one argument:
- The first argument is a string representing the URL pattern or the path to the URL configuration module to include.
- It is commonly used when you have multiple apps within a Django project, and each app has its own set of URL patterns defined in a separate
urls.py
file.
By including the URL patterns from different apps using include()
, you can organize and modularize your URL configurations.
The basic URL is http://127.0.0.1:7000/
(local storage).
Everything was clear?