Django——2 路由分配設置 re_path正則匹配 include總路由 url傳參 name使用 模板渲染render方法 模板渲染方法


Django

  1. 路由分配設置
  2. re_path正則匹配
  3. include總路由設置
  4. url額外參數的傳遞
  5. name的使用
  6. 模板的渲染:render方法

 

 


 

路由的分配中,

可以設定相應的轉換器加以約束,比如只能輸入數字,特殊符號。。

形如

from django.urls import path
from . import views

urlpatterns = [
    path('hello/<int:age>/<name>/', views.hello),
]

設置views以查看結果:(參數格式不正確的話,會無法顯示網頁)

from django.http import HttpResponse
# Create your views here.

def hello(request, age, name):
    return HttpResponse('%d歲的%s, 正在學習Django'%(age, name))

類似的還有:

  • str,匹配除了路徑分隔符(/)之外的非空字符串,這是默認的形式
  • int,匹配正整數,包含0。
  • slug,匹配字母、數字以及橫杠、下划線組成的字符串。
  • uuid,匹配格式化的uuid,如 075194d3-6885-417e-a8a8-6c931e272f00。
  • path,匹配任何非空字符串,包含了路徑分隔符

 

 

 re_path正則匹配(了解即可,推薦path方法)

from django.urls import path, re_path
from . import views

urlpatterns = [
    re_path('^hello/$', views.hello),
    re_path('^hello/(?P<yy>[0-9]+)/', views.hello),
]

 

 ?p: 固定寫法

 

 include總路由設置

在總的項目文件夾下,urls.py一般這樣設置:(因為每個app里面都會有很多的路由,這樣分類比較方便)

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

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

 

 然后再app中urls.py中設置:

from django.urls import path
from . import views

urlpatterns = [
    path('hello/<int:age>/<name>/', views.hello),
]

 

 最后在對應app中設置views.py:

from django.http import HttpResponse
# Create your views here.

def hello(request, age, name):
    return HttpResponse('%d歲的%s, 正在學習Django'%(age, name))

 

url參數的傳遞

urls.py:

from django.urls import path
from . import views

urlpatterns = [
    path('hello/<int:age>/<name>/', views.hello, {'key': True}),
]

 views.py:

from django.http import HttpResponse
# Create your views here.

def hello(request, age, name, **kwargs):
    if kwargs['key']:
        print('True')
    return HttpResponse('%d歲的%s, 正在學習Django'%(age, name))

 

 name的作用:

在url的路由配置中加上一個name的設置的話,在使用到url的路徑時,都可以用name的別名代替,減少路由修改和維修的代價

主要應用在頁面重定向

模板頁面的href跳轉({%  url 'url_name' %})

urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('old/', views.old_page),
    path('new/', views.new_page ,name='new'),
]

 views.py

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

def old_page(request):
    # return HttpResponse('there is a <b>old</b> page')
    return redirect(reverse('new'))

def new_page(request):
    return HttpResponse('there is a <b>new</b> page')

 

 這樣在訪問老的頁面時,就會自動跳轉到新的頁面,不再寫入url的路徑

name的作用:

name參數可以給這個url取一個合適的名字。通過給url取名字,以后在view或者模板中使用這個URL,就只需要通過這個名字就可以了。

這樣做的原因是防止url的規則更改,會導致其他地方用了這個url的地方都需要更改,但是如果取名字了,就不要做任何改動了。

模板的渲染:render方法

 在項目總的大環境下,新建規定的文件名:templates

在配置文件settings.py中,添加templates到模板配置TEMPLATES中:這樣app中就可以使用了模板了

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

 

 templates文件夾中新建對應app數目,對應名字的文件夾(這樣方便使用,非硬性),新建html文件,以便views渲染

html:(隨意寫入)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>首頁</title>
    <style>
        * {
            background-color: lightgoldenrodyellow;
            margin: 0;
            padding: 0;
        }
    </style>
</head>
<body>
    <h1 style="text-align: center">welcome to my home!</h1><br><br>
    <p style="text-align: center; color: royalblue">what do you want?</p>
    <a href="{% url 'old' %}">name作用:old頁面之無力回天</a><br>
    <a href="https://www.baidu.com">有啥不懂得問我</a>
</body>
</html>

html代碼划線處是name的第二個常用處

 

urls.py:

from django.urls import path
from . import views

urlpatterns = [
    path('views/', views.show_views, name='show_views')
]

 views.py:

def show_views(request):
    return render(request, 'book/book_index.html')

 訪問頁面:

 

name的作用,點擊還是會被重定向到new頁面

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM