This section covers the common steps performed to set up routing in your django website.
Please note that this is site provides the most commonly used django features. It is by no means intended to be an exhaustive documentation of the Django framework. You can always use the official django documentation by clicking the big green button below.
Django Urls DocsTo get started configuring the routing of your Django project, first, you'll need to verify that you are importing the admin object. This is so that you can access to the admin site, once you configure it. In <project>/urls.py file, add the following imports if not there already:
from django.contrib import admin
Also import the path and include functions.
In the same file, the <project>/urls.py file, import if not these functions:
from django.urls import path, include
Then in your <app_name>/templates directoy (that you just created),
add another directoy called templates:
cd templates && mkdir <app_name>
The next step is to create a list called urlpatters and use the path function to create two paths. The first path is to /admin, and the second can be to an empty string. Your file will loook like this:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('.urls'))
]
Setting up this section of your app depends entirely on how many routes you want to set up. The first step to creating your app urls is to make sure you have imported the path function from django.shortcuts. To do this, go into the file in your app, and near the top of the page, add:
from django.urls import path, include
Also import * from the views.py as done below:
from .views import *
Then define a function that accepts request as a parameter. You can call this function whatever you like, but it would be customery to call it index.
def index(request):
The next step is to create a list called urlpatters and use the path function to create as many paths as you have views. The first path could be 'home', and the second can be to 'about'. Your paths will be associated with views and names (which are used for linking in templates) Your file will loook something like depending on how you name it this:
from django.urls import path
from .views import *
urlpatterns = [
path('home/', index, name='home'),
path('about/', about, name='about'),
]