The article directories

  • Urls. Py is introduced
  • routing
    • The simplest route
    • Cross-file routing
    • Built-in routing in APP
  • The ginseng
    • Simple mass participation
    • Path converter
    • Regular expression recognition parameter (RE_path)
    • Common parameter transfer mode
    • Specify default parameters
    • redirect
  • Reverse URL parsing
    • Application namespace
    • Instance namespace
    • URL parameter inversion

Urls. Py is introduced

Urls.py is the most important thing for routing. It tells the route what to do and how to do it, and basically all of our routing is done in urls.py. There are also some simple examples of urls (it doesn’t matter if you can’t read the examples for now, we’ll explain the directions in detail below, and you’ll be able to read the official examples once you understand the explanation below)

The functional view1.Add an import:from my_app import views
    2.Add a URL to urlPatterns: path(' ', views.home, name='home'Class-based view1.Add an import:from other_app.views import Home
    2.Add a URL to urlPatterns: path(' ', Home.as_view(), name='home'Include another URLconf1.Import the include() function:from django.url import include,path
    2.Add a URL to urlPatterns: path('blog/', include('blog.urls'))
Copy the code

routing

The simplest route

To create the simplest route, we simply import two libraries: the path for creating the route and the HttpResponse for creating the page. As follows, the simplest route has been created. We open the page again (default: 127.0.0.1:8000) and see that the home page has been replaced with “My Home Page”.

from django.urls import path
from django.http import HttpResponse

def home(request) :
    return HttpResponse("My Home page")


urlpatterns = [ 
    path(' ', home)
]
Copy the code

Cross-file routing

In the above example, our page is in the route, but in reality, we cannot write all pages in the route. Here, we can write the page in different apps and import our route uniformly. We simply import the files that need to be routed

# Views.py in app_demo of the current APP
from django.shortcuts import render
from django.http import HttpResponse


Create a view here.
def demo(request) :
    return HttpResponse('I'm a test page')
Copy the code

We can add this file to our route

The code in # urls.py for the main project is
from django.urls import path
from app_demo.views import demo


urlpatterns = [
    path('demo', demo)
]
Copy the code

Or use the following method to add the same effect as above

The code in # urls.py for the main project is
from django.urls import path
from app_demo import views


urlpatterns = [
    path('demo/', views.demo)
]
Copy the code

Built-in routing in APP

A large number of apps can lead to naming conflicts, because the default view page in each APP is views.py. This problem can be solved simply by building in APP routing. We need to create our own urls.py in the APP and write the following code internally

from django.urls import path
from . import views

urlpatterns = [
    path(' ', views.demo)
]
Copy the code

For the main project route, we need to use the include method in the urls library to import the urls created in the APP

from django.urls import path, include

urlpatterns = [
    path('demo/', include('app_demo.urls')))Copy the code

The ginseng

Passing parameters in urls is also a very important function

Simple mass participation

The simplest way to pass an argument is to pass the argument to the view function.

from django.urls import path
from django.http import HttpResponse


def home_page(request, home_id) :
    return HttpResponse("First on the home page"+home_id+'pages')


urlpatterns = [
    path('<home_id>', home_page),
]
Copy the code
  • To value from the URL, use Angle brackets.
  • There’s no need to add a backslash here, because every URL has one. For example, it should be demo instead of /demo.

Path converter

By default, we can accept any form of argument, but most of the time, we want to receive arguments that are not just any form of argument. For example, when we turn a page, we want to receive arguments that are numeric, or we want to receive arguments that are text, UUID, etc. Path converters are designed for this purpose. Suppose we now want to receive a numeric ID and a user name consisting of ASCII letters or numbers and hyphens and underscores

from django.urls import path
from django.http import HttpResponse


def home_uid(request, home_id, home_name) :
	# 

is the HTML line break
return HttpResponse(User id:{}

User name :{}'
.format(home_id, home_name)) urlpatterns = [ path('<int:home_id>/<slug:home_name>', home_uid), ] Copy the code
Path converter role
str Matches non-empty strings other than ‘/’. (Default option)
int Matches 0 or any positive integer. Returns an int.
slug Matches any short label consisting of ASCII letters or numbers and hyphens and underscores. For example, build-your-1st-django-site.
uuid Matches a formatted UUID. To prevent multiple urls from mapping to the same page, dashes must be included and characters must be lowercase.
path Matches non-empty fields, including the path separator ‘/’. It allows you to match the entire URL path rather than parts of the URL as STR does.

In addition to the five built-in path converters, you can also customize the path converters and custom path converters methods

Regular expression recognition parameter (RE_path)

In addition to using the path converter to receive arguments of the specified form, we can also use re_path to identify arguments. Before using it, we need to import it from Django. urls import re_path named regular expression group syntax is (? P

pattern), where name is the group name and pattern is the pattern to be matched. Note:? P\

must be written here, and P must be capitalized.

from django.urls import re_path
from django.http import HttpResponse


def home_year(request, year) :
    return HttpResponse('The current is {} year'.format(year))


urlpatterns = [
    re_path('year/(? P
      
       (1|2)[0-9]{3})'
      , home_year),
]
Copy the code

Common parameter transfer mode

Most of the submissions we see on the site have been? The question mark is followed by a parameter, which is relatively easy for Django to implement. Let’s assume a requirement. In the app_demo APP, we need multiple arguments starting with? The question mark realizes the requirements of passing parameters and turning pages. ? GET (‘ parameter name ‘) can be received only if the parameter is passed with the specified parameter name. Otherwise, it cannot be received. For example, I write in app_demo/views.py

from django.http import HttpResponse


def demo_page(request) :
    page = request.GET.get('data')
    return HttpResponse('MY {} test page'.format(page))
Copy the code

In the URL must be written in http://127.0.0.1:8000/demo/page/? If you want to pass in the above code, you need to add path(‘page/’, views.demo_page) to app_demo\urls.py. You also need to have path(‘demo/’, include(‘app_demo.urls’))

Specify default parameters

When the special request, enter the specified url may not carry parameters directly, then we can use the specified parameters make the correct page jump to the place where we want to approach a: we can give parameters directly in the create view function when a default value, here it is important to note that the below routing need to specify a default parameter page when a default route.

from django.urls import path, include
from django.http import HttpResponse


def home_uid(request, home_id=1, home_name='xunmi') :
    return HttpResponse(User id:{}

User name :{}'
.format(home_id, home_name)) urlpatterns = [ path('home', home_uid), path('home/<int:home_id>/<slug:home_name>', home_uid), ] Copy the code

Request.GET. GET (‘ parameter name ‘) returns None if there is no argument or if it fails to receive.

def demo_page(request) :
    page = request.GET.get('data')
    if page is None:
        page = 1
    return HttpResponse('MY {} test page'.format(page))
Copy the code

redirect

If we receive the wrong parameter in the page, if we do not do it, then the page is likely to display error messages such as 404. To reduce 404 occurrences, we can make some simple judgments and let the wrong ID be redirected. This is where the redirect is needed. For example, the following code uses redirect to redirect the wrong parameters to the next layer.

from django.shortcuts import render, redirect
from django.http import HttpResponse


Create a view here.
def demo(request) :
    return HttpResponse('I'm a test page')


def demo_page(request) :
    page = request.GET.get('data')
    if page:
        return HttpResponse('MY {} test page'.format(page))
    else:
        return redirect('.. / ')
Copy the code

The current routing

from django.urls import path
from . import views

urlpatterns = [
    path(' ', views.demo),
    path('page/', views.demo_page)
]
Copy the code

Reverse URL parsing

In the above code, our URL is often written dead in the code, if there is a URL that has been referenced many times in the website suddenly needs us to modify, it will be a very troublesome work, and may cause a bug because of the missed conversion into a webpage error jump. URL flipping is created to solve this problem, and it’s as simple as adding the name attribute to path() when routing the page and the Reverse method when using it (in the Django.Shortcuts library, the same library that brought the viwe with you when creating your APP) S. py will be included)

Application namespace

Add name to path(e.g. Path (‘home/’, home_uid, name=’index’). Use this name when applying a namespace, such as reverse(‘index’)

from django.urls import path
from django.http import HttpResponse
from django.shortcuts import render, redirect, reverse


def home(request) :
    data = request.GET.get('id')
    print(data)
    if data:
        return redirect(reverse('index'))
    else:
        return HttpResponse("My Home page")


def home_uid(request, home_id=1, home_name='xunmi') :
    return HttpResponse(User id:{}

User name :{}'
.format(home_id, home_name)) urlpatterns = [ path(' ', home), path('home/', home_uid, name='index'), path('home/<int:home_id>/<slug:home_name>', home_uid), path('demo/', demo), ] Copy the code

Note: Application namespaces cannot coexist with include, such as path(‘demo/’, include(‘app_demo.urls’), name=’index’). (If we want to name the above case, we can go to app_demo/urls.py and add the name)

Instance namespace

When using include, you can also add a namespace to your custom urls.py to prevent naming conflicts when the same page appears in multiple apps. We can use when using the include namespace, but the namespace to use most is reversed (reverse DNS), when we reverse set more, may cause conflicts, and the default inversion is the routing to the APP itself and total project routing in looking for the name, if the name exists in other apps, directly Seek and find not

# add in app_demo.py
app_name = 'demo'
# add demo when using include to read routes
path('demo/', include('app_demo.urls'.'demo')),
Add namespaces using reverse (reverse parsing)
reverse('demo:index')
Copy the code

URL parameter inversion

Return redirect(reverse(‘page’, kwargs={‘page’: 1})) The question mark argument can be concatenated as follows

from django.shortcuts import render, redirect, reverse
from django.http import HttpResponse
# Create your views here.


def copy(request) :
    # data = request.GET.get('id')
    uid = request.GET.get('id')
    if uid:
        The parameter is passed in backslash form
        # return redirect(reverse('page', kwargs={'page': data}))
        # already? Form the participation
        data = reverse('copy:uid') +'? id='+uid
        return redirect(data)
    else:
        return redirect(reverse('page', kwargs={'page': 1}))


def copy_page(request, page) :
    return HttpResponse('I am page {}'.format(page))


def copy_uid(request) :
    uid = request.GET.get('id')
    return HttpResponse('My id is {}'.format(uid))
Copy the code

This routing for

from django.urls import path
from . import views

app_name = 'copy'

urlpatterns = [
    path(' ', views.copy),
    path('page/<page>', views.copy_page, name='page'),
    path('uid/', views.copy_uid, name='uid')]Copy the code