Django learning-second lecture Django URL and view

1. The concept of view

Views are generally written in the views.py of the app, and an app can be regarded as a module in a website. And the first parameter of the view is always a request (an HttpRequest) object. This object stores all the information requested, including the parameters carried and some header information. In the view, logic-related operations are generally completed. For example, if this request is to add a blog, the data can be received through the request, and then stored in the database, and finally the result of the execution is returned to the browser. The return result of the view function must be an HttpResponseBase object or a subclass object. The sample code is as follows:

news/views.py

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

urls.py

from news import views

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

1.1 Some methods in the test request

from django.http import HttpResponse
def news(request):
    print(type(request))
    print(request.method)
    return HttpResponse("新闻!")

2. URL mapping

That is, the url address generation rules when we visit the website. Django reads the configuration information of the url according to the content of the ROOT_URLCONF configuration item in settings.py to read the url mapping information:

After the view is written, it needs to be mapped with the URL, that is, the user can request this view function when entering any URL in the browser. When the user enters a certain url and requests to our website, Django will look for the corresponding view from the project's urls.py file. There is a urlpatterns variable in the urls.py file, and django will read all matching rules from this variable in the future. The matching rules need to be wrapped with the django.urls.path function, which will return URLPattern or URLResolver objects according to the passed parameters. The sample code is as follows:

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)
]

3. Add parameters to the URL

Sometimes, some parameters contained in the url need to be dynamically adjusted. For example, the url of the detail page of an article in Jianshu is https://www.jianshu.com/p/a5aab9c4978e. The a5aab9c4978e behind the article is the id of this article. Then the url of the article detail page in Jianshu can be written as https: //www.jianshu.com/p/, where id is the id of the article. So how to achieve this requirement in django.

The first type: At this time, we can use angle brackets to define a parameter <book_id> in the path function. For example, if I want to get the detailed information of a book, this parameter should be specified in the url. The sample code is as follows:

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中的代码如下:
def book_detail(request,book_id):
    text = "您输入的书籍的id是:%s" % book_id
    return HttpResponse(text)

The second: can also pass a parameter in the past through the query string? The way of parameters (?.. Use ampersand to connect between multiple parameters). The sample code of book_detail/?id=4 &name='123' is as follows:

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

------------------------------------------------------------------
views.py中的代码如下:
def book_detail(request):
    book_id = request.GET.get("id")
    text = "您输入的书籍id是:%s" % book_id
    return HttpResponse(text)

The writing in our address bar in the second method:
http://127.0.0.1:8000/book/book_detail/?id=4

4. URL Modularization

The URL contains another urls module:

In our project, it is impossible to have only one app. If all the views in the app’s views are mapped in urls.py, it will definitely make the code very messy. Therefore, django provides us with a method to include our own URL matching rules in the app, and then uniformly include the app's URLs in the project's urls.py. Use of this technique requires the help of the include function. The sample code is as follows:

# test1/urls.py文件:

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

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

In the urls.py file, all the urls related to the book app have been moved to app/urls.py. In test1/urls.py, book.urls is included through the include function, and the book-related urls will be requested later You need to add a book prefix. urls file under book

from django.urls import path
from . import views
urlpatterns = [
    path("", views.index),
    path("book_list/", views.book_list),
    path("book_detail/", views.book_detail)
]

5. Django built-in converter

from django.urls import converters

The principle of the built-in converter is the regular expression used, including the following:

  • path
  • str default
  • int
  • slug
  • How to
    use uuid :

path(“book_detail/int:id”, views.book_detail)

Introduction to the content of UUID input
[https://www.cnblogs.com/franknihao/p/7307224.html]

6. Url namespace and reversal

6.1 url namespace and reversal

If there are foreground and background in the same website, both the foreground and the background include the login function. For example, we have written a login function, but the name needs to be changed when mapping the path.

  • 1. Why do you need URL naming?
    Because the URL address may change frequently during the development of the project, it will often be modified if it is hard to write.

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

  • 3. Application namespaces
    URLs with the same name may be generated between multiple apps. In order to avoid this situation, namespaces can be used to distinguish them. Just add app_name in urls.py.

  • 4. Reverse reverse() needs to be used in conjunction with redirect

return redirect(reverse("cms:login"))

The corresponding code of the case:
front part:

  • front-urls.py code:
from django.urls import path
from . import views
# 设置app命名空间用于区分
app_name = 'front'
urlpatterns = [
    path("",views.index),
    # 前台登录url映射
    path("sigin/",views.login,name = "login")
]
  • front-views.py code:
from django.shortcuts import render, redirect, reverse
# Create your views here.
from django.http import HttpResponse
def index(request):
    # 判断是否登录,url中是否传递username,如果传了,直接登录,没有传递跳转到登录页面
    username = request.GET.get("username")
    # 如果有就到首页
    if username:
        return HttpResponse('前台首页')
    else:
        # 没有就到登录页面,使用 redirect方法进行url重定向
        # urls中指定了url的name,此时地址栏中的登录不管是什么可以随便变
        # 我们只需要通过reverse将其对应的url进行反转即可,减少了代码修改的问题
        # 但是这也需要配合app_name使用,否则名字相同,程序无法区分具体是哪个中的方法
        return redirect(reverse("front:login"))
def login(request):
    return HttpResponse('前台登录页面')

cms background part:

  • cms-urls.py code:
from django.urls import path
from . import views

# 设置app命名空间用于区分
app_name = 'cms'

urlpatterns=[
    path("",views.index),
    # 后台登录url映射
    path("sigin/",views.login,name='login')
  • cms-views.py code:
from django.shortcuts import render,redirect,reverse
from django.http import HttpResponse
def index(request):
    username = request.GET.get("username")
    # 如果有就到首页
    if username:
        return HttpResponse('后台首页')
    else:
        # 没有就到登录页面,使用 redirect方法进行url重定向
        #urls中指定了url的name,此时地址栏中的登录不管是什么可以随便变
        #我们只需要通过reverse将其对应的url进行反转即可,减少了代码修改的问题
        #但是这也需要配合app_name使用,否则名字相同,程序无法区分具体是哪个中的方法
        return redirect(reverse("cms:login"))
def login(request):
    return HttpResponse('后台登录页面')

6.2 Application Namespace and Instance Namespace

One app can create multiple instances. You can use multiple URLs to map the same App. When doing the reverse, if you use the application namespace, confusion will occur. To avoid this problem, you can use the instance namespace, use the instance namespace, namespace='instance namespace'

urls.py

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")),
]

call in views

def XX:
    current_namespace= request.rewsolver_match.namespace
    return redirect(reverse('{}:login'.format(current_namespace)))

6.3 URL inverse pass parameters

The first type: If parameters need to be passed in this url, then parameters can be passed through kwargs.

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

url

path('detail/<int:book_id>')

The second type: string, because reverse in django does not distinguish between GET requests and POST requests when reversing urls, so you cannot add query string parameters when reversing. 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)

6.4 Specify default parameters

article/views.py
-----------------------------------------------------------------
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])

-------------------------------------------------------------------
article/urls.py

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),
]

7.re_path function

Sometimes when we write URL matching, we want to use regular expressions to achieve some complex requirements, then we can use re_path to achieve this. The parameters of re_path are exactly the same as the path parameters, except that the first parameter, the 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)
]

Guess you like

Origin blog.csdn.net/scyllake/article/details/99721493