Django|URL and view

view

Views are usually written in the views. Of the app Py. And the first parameter of the view is always request (an HttpRequest) object. This object stores all the information from the request, including the parameters carried and some header information. In the view, logic related operations are generally completed. For example, if the request is to add a blog, you can receive these data through the request, store them in the database, and finally return the execution results to the user browser. The return result of the view function must be an HttpResponseBase object or an object of a subclass.

news/views.py

from django.http import HttpResponse
def news(request):
    return HttpResponse("Journalism!")

urls.py

from news import views

urlpatterns = [
    path("news",views.news)
]

URL mapping

After the view is written, it should be mapped with the URL, that is, the user can request the view function when entering what URL in the browser. When the user enters a URL and requests to our website, django will start from the URLs of the project Py file to find the corresponding view. In URLs There is a urlpatterns variable in the PY file, and django will read all matching rules from this variable in the future. Matching rules require the use of django urls. Path function, which will return URLPattern or URLResolver objects according to the passed parameters.

from django.contrib import admin
from django.urls import path
from book import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('book/',views.book_list)
]

Add parameter to URL

Sometimes, the url contains some parameters that need to be adjusted dynamically. For example, the url of the details page of an article in Jianshu is https://www.jianshu.com/p/a5aab9c4978e The following a5aab9c4978e is the ID of this article, so the url of the article details page of Jianshu can be written as https://www.jianshu.com/p/ , where id is the ID of the article. So how to implement this requirement in django. At this time, we can define a parameter in the form of angle brackets in the path function. For example, if I want to get the details of a book now, I should specify this parameter in the url.

from django.contrib import admin
from django.urls import path
from book import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('book/',views.book_list),
    path('book/<book_id>/',views.book_detail)
]
------------------------------------------------------------------
views.py The codes in are as follows:
def book_detail(request,book_id):
    text = "The name of the book you entered id Yes:%s" % book_id
    return HttpResponse(text)

You can also pass a parameter by querying a string.

urlpatterns = [
    path('admin/', admin.site.urls),
    path('book/',views.book_list),
    path('book/detail/',views.book_detail)
]

------------------------------------------------------------------
views.py The codes in are as follows:
def book_detail(request):
    book_id = request.GET.get("id")
    text = "The book you entered id Yes:%s" % book_id
    return HttpResponse(text)

URL modularization

The URL contains another urls module:

In our project, there can't be only one app. If we put all the views in the app's views in urls Mapping in py will certainly make the code look very messy. Therefore, django provides us with a method to include its own url matching rules in the app, and in the urls. url of the project The urls containing this app will be unified in py. Using this technique requires the use of the include function.

# django_first/urls.py file:

from django.contrib import admin
from django.urls import path,include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('book/',include("book.urls"))
]

In URLs Py file, move all URLs related to the book app to app / URLs Py, Django_ first/url s. Py, include book. Py through the include function URLs, you need to add a Book prefix when requesting book related URLs in the future.

Django built in converter

Python

Copy code

from django.urls import converters

UUID:https://www.cnblogs.com/franknihao/p/7307224.html

url naming and inversion

●1. Why do I need URL naming
Because the URL address may change frequently in the process of project development, it will be modified frequently if it is written dead

●2. How to assign a name to a URL
path("",views.index,name="index")

●3. Application namespace
URLs with the same name may be generated between multiple apps. In order to avoid this situation, namespaces can be used to distinguish. In URLs Add app to PY_ Name.

Application namespace and instance namespace

One App can create multiple instances. Multiple URL s can be used to map the same App. When reversing, if you use the application namespace, confusion will occur. To avoid this problem, you can use the instance namespace. The instance namespace uses, namespace = 'instance namespace'

from django.contrib import admin
from django.urls import path,include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('cms1/', include("cms.urls",namespace='cms1')),
    path('cms2/', include("cms.urls",namespace='cms2')),
    path('front/', include("front.urls")),
]

URL inversion pass parameters

If you need to pass parameters in this url, you can pass parameters through kwargs.

reverse("book:detail",kwargs={"book_id":1})

Because reverse in django does not distinguish between GET requests and POST requests when reversing URLs, you cannot add query string parameters during inversion. If you want to add query string parameters, you can only add them manually.

login_url = reverse("front:singin") + "?name=jr"
return redirect(login_url)

Specify default parameters

from django.http import HttpResponse

# Create your views here.

article_lists = ["a","b","c"]

def article(request):
    return HttpResponse(article_lists[0])

def page(request,page_id=0):
    return HttpResponse(article_lists[page_id])
from django.urls import re_path,path
from . import views

urlpatterns = [
    path("",views.article),
    path("page/",views.page),
    path("page/<int:page_id>",views.page),
]

re_path function

Sometimes when we write url matching, we want to use regular expressions to realize some complex requirements. At this time, we can use re_path. re_ The parameters of path as like as two peas path parameters, but the first parameter, that is, route parameter, can be a regular expression.

article/urls.py
------------------------------------------------------------------
from django.urls import re_path
from . import views

urlpatterns = [
    re_path(r"^$",views.article),
    re_path(r"^article_list/(?P<year>\d{4})/",views.article_list)
    re_path(r"^article_list/(?P<mouth>\d{2})/",views.article_mouth)
]

Keywords: Python Django

Added by almightyegg on Thu, 16 Dec 2021 21:42:24 +0200