我爱编程

URL的问题

2018-04-14  本文已影响0人  流蓝浅

1 要在setting文件中配置
2 在项目的urls.py配置
3 在app下的urls.py中配置
4 文件中使用

1 要在setting文件中配置
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',
            ],
        },
    },
]

2 在项目的urls.py配置
from django.contrib import admin
from django.urls import path
from django.conf.urls import url, include

urlpatterns = [
    path('admin/', admin.site.urls),
    url(r"^books/", include('book1.urls')),
    url(r"^", include('PIANKE.urls')),
]

3 在app下的urls.py中配置
from django.conf.urls import url
from . import views

urlpatterns = [
    url(r"^$", views.index),
    url(r"^detail/(\d+)/$", views.detail),
    url(r"^test1/$", views.test1),
    url(r"^test2/$", views.test2),
    url(r"^test3/$", views.test3),
]

4 文件中使用
# 第一种
    return render(request, "books/index.html", context)
# 第二种
好吧其他的路径我都用了反向生成

传递参数的url

# url 配置
urlpatterns = [
    url(r"^$", views.index),
    url(r"^detail/(\d+)/$", views.detail),
    url(r"^test1/$", views.test1),
    url(r"^test2/$", views.test2),
    url(r"^test3/$", views.test3),
]

# view中处理参数的函数
def test1(request):
    return render(request, "books/test1.html")


def test2(request):
    a = request.GET['a'] # 从request中得到数据传递给页面
    b = request.GET['b']
    context = {"a": a, "b": b}
    return render(request, "books/test2.html", context)


def test3(request):
    a = request.GET["a"]
    b = request.GET.getlist("b")
    context = {"a": a, "b": b}
    return render(request, "books/test3.html", context)
三个test 页面
# test1
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<a href="/books/test2/?a=1&b=2">test2</a> # 从链接中提交数据
<a href="/books/test3/?a=1&b=2&b=3&b=4">test3</a>
</body>
</html>
# test2
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
a:{{ a }} # 在页面上显示获取到的数据
b:{{ b }}
</body>
</html>
# test3
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
a:{{ a }}
b:{{ b }}
</body>
</html>

querydict与python中dict不太一样,前者一个键可以对应多个值,后者一个键只能对应一个值

上一篇下一篇

猜你喜欢

热点阅读