Django路由系统

2020-11-12  本文已影响0人  干掉楼上

路由系统

获取url上的参数

def news_view(request):
    print(request.GET)
    print(request.GET.get('data'))
    print(request.GET.get('wd'))
    return HttpResponse('news')

路径参数(简书)

路径参数的使用

path("<int:u_id>", views.index)

自定义路径参数

新建文件converter.py

class FourDigitYearConverter:
    regex = r'[0-9]{4}'

    def to_python(self, value):
        return int(value)

    def to_url(self, value):
        return str(value)

#  在 urls中使用
from django.urls import register_converter
from . import converter

register_converter(converter.FourDigitYearConverter, 'year')

app_name = 'news'
# 这是新闻模块的路由
urlpatterns = [
    path('<year:year_d>/', views.detail_y)

re_path

# 给路径命名 固定写法
re_path(r'(?P<year>[0-9]{4})', views.images_view)


def images_view(request, year):
    return HttpResponse(year)

渲染模板

def images_view(request, year):
    # 浏览器可以正常渲染
    return HttpResponse(f"<h1>{year}</h1>")

配置模板文件路径

在settings.py中配置

'DIRS': [os.path.join(BASE_DIR, 'templates')],

在template目录中添加模板文件

在render中使用模板文件

return render(request, 'login.html')

获取请求方法

print(request.method)

(redirect)重定向

return redirect('/index/')

render传参(模板语言)

return render(request, 'login.html', context={'tips': '用户名或密码错误'})

在html中{{ tips }}

命名空间

url反转(reverse)

# urls.py
path('', views.index, name='index'),
# views.pu
return redirect(reverse('index'))

app的命名空间(app_name)

多个app中存在相同的url名字

在子路由中配置app_name

静态文件引入

创建一个static用于存放css、js、图片等文件的目录

# 配置静态文件目录
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static'),
]

在模板中引入静态文件

在html中

<link rel="stylesheet" href="/static/css/style.css">

第二种方法,通过模板语言引入css样式表

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Title</title>
    <link rel="stylesheet" href={% static 'css/style.css' %}>
</head>
上一篇 下一篇

猜你喜欢

热点阅读