Django知识点

Posted wanghuaqiang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Django知识点相关的知识,希望对你有一定的参考价值。

urlpatterns = [
    url(r^admin/, admin.site.urls),
    url(r^index/, views.index),
]
views.index调用即index()时默认会传入一个request

 

-----------------------------------------------------
无名分组:
    urlpatterns = [
        url(r^archive/(\d+), views.archive),
    ]

    备注:url(r^archive/(\d+), views.archive),
    1:\d+表示匹配一个或多个数字:
    2:此处的加括号()表示分组,对应的函数archive()可以多传一个值
    views.py里
        def archive(request,id):此处的id是(\d+)传递的


http://127.0.0.1:8001/archive/12
def archive(request,id):
    return HttpResponse( id)打印结果为12

url(r^archive/(\d+)$, views.archive),匹配结尾的
-------------------------------------------
同时接收两个值需要两个\d均加括号,才能传递给视图函数
http://127.0.0.1:8001/archive2/2014/12
url(r^archive2/(\d{4})/(\d{2}), views.archive2),
def archive2(request,year,month):
    return HttpResponse(year+month)
------------------------------------------

-----------------------------------------------------
有名分组(就是Python的关键字参数形式传给视图):
    定义:
        urlpatterns = [
            url(r^archive2/(?P<y>\d+)/(?P<m>\d{2}), views.archive2),
        ]
        1、(\d+)
        2在前半括号后加?P<y>
         2.1:?P<>固定形式
         2.2:y表示虚参,随便定义
     调用:
         def archive2(request,y,m):
            return HttpResponse(y+m)
----------------------------------------------------------------------------

 

 

多个应用时用:
多个应用的url都放在全局的urls.py里不合适也很麻烦,需要做到解耦

项目的urls.py文件需要导入include
from django.conf.urls import url,include
from django.contrib import admin
from app01 import views
urlpatterns = [
    url(r^app01/, include(app01.url)),
]

应用的url
from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
    url(r^archive/(\d+)$, views.archive),
    url(r^archive2/(?P<y>\d+)/(?P<m>\d{2}), views.archive2),
]

 

def index(request):
    # book_list=Book.objects.filter(price__gt=39) #价格大于39元的书
    # book_list = Book.objects.filter(price__lt=8)#价格大于39元的书
    # book_list = Book.objects.filter(title__contains=‘py‘)#title包含py的书
    # book_list = Book.objects.filter(title__startswith=‘py‘)#title以py开头的书
    # book_list = Book.objects.filter(title__endswith=‘va‘)  # title以va结尾的书
    # book_list = Book.objects.filter(price__in=[8,9,10])#价格在[8,9,10]列表里的书
    book_list = Book.objects.filter(price__range=[20,89])  # 价格在20到89之间的的书
    return render(request,query.html,{"book_list":book_list})

 

以上是关于Django知识点的主要内容,如果未能解决你的问题,请参考以下文章

django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE的解决办法(转)(代码片段

android小知识点代码片段

Django REST框架--认证和权限

如何在 Django 中显式重置模板片段缓存?

使用 Django 模板作为片段

python 通过django片段很多很多