Django框架Day1之url和views

一、新建一个Django程序(window 7进入cmd里面操作):注意,此处要需在指定的文件夹下
  a,django-admin startproject django_test(django_test指的是项目名称)
  b,进入django_test [cd django_test]
  c,创建app[python manage.py startapp test_01]
  d,进入project运行项目[python manage.py runserver]-------然后可以在浏览器中查看http://127.0.0.1:8000/,有It's worked,即表示创建成功

二、url常用匹配方法1--直接显示urls:

在django_test下的urls.py文件中输入以下代码

from django.conf.urls import include, url
from django.contrib import admin
from test_01 import views

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^articles/$', views.special_case),
]

然后在test_01views文件中创建函数special_case,即:

from django.shortcuts import render
from django.shortcuts import HttpResponse

def special_case(request):
    return HttpResponse("It's ok")

运行http://127.0.0.1:8000/articles/即可查看【It’s ok】已经生效。

同时,还有以下几种url直接匹配方式:两种匹配方式有些许区别(具体区别后续附上)

 

urlpatterns = [
    url(r'^articles/2003/$', views.special_case_2003),
    url(r'^articles/([0-9]{4})/$', views.year_archive),
    url(r'^articles/([0-9]{4})/([0-9]{2})/$', views.month_archive),
    url(r'^articles/([0-9]{4})/([0-9]{2})/([0-9]+)/$', views.article_detail),
]
urlpatterns = [
    url(r'^articles/2003/$', views.special_case_2003),
    url(r'^articles/(?P<year>[0-9]{4})/$', views.year_archive),
    url(r'^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/$', views.month_archive),
    url(r'^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/(?P<day>[0-9]{2})/$', views.article_detail),
]



 

此处的views文件代码如下:

def year_archive(request,year):
    print("---->",year)
    return HttpResponse(year)

def month_archive(request,year,month):
    print("--->",year,month)
    return HttpResponse("%s %s"%(year,month))

三、url常用匹配方法2--通过app聚合url来使一部分urls聚集在某一个app下:

1.首先在django_test下的urls.py文件中引入payment_urls

from django.conf.urls import include, url
from django.contrib import admin
from test_01 import views
from test_01 import urls as payment_urls

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^articles/$', views.special_case),
    url(r'^payment/',include(payment_urls)),
]

然后在test_01下新建一个urls.py文件,如下:

from django.conf.urls import include, url
from django.contrib import admin
from test_01 import views

urlpatterns = [
    url(r'^$',views.index),
]

最后在test_01下的views文件中创建一个index函数

def index(request):
    HttpResponse("*****Welcome to the payment mall*****")

需要复杂一点的话,就是此段

def index(request):
    if request.method == "GET":
        user_infos = [
            {'username':'Lemon0', 'name':'Lemon Li0'},
            {'username':'Lemon1', 'name':'Lemon Li1'},
            {'username':'Lemon2', 'name':'Lemon Li2'},
            {'username':'Lemon3', 'name':'Lemon Li3'},
        ]
        return render(request,'test_01/index.html')
    else:
        return HttpResponse("*****Welcome to the payment mall*****")

此处需要配置django_test下的settings文件:首先在INSTALLED_APPS中加入“test_01”,然后在 TEMPLATES下改DIRS文件      'DIRS': [os.path.join(BASE_DIR,"templates")],

同时,此处引入了html文件,需要在templates下新建一个index.html文件,如果没有templates创建该文件即可,index.html文件如下。然后运行http://127.0.0.1:8000/payment/即可

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<h1>Welcome to the payment center</h1>
<ul>
    {% for user_obj in user_objs %}
    <li style="background-color:red">username:{{user_obj.username}},name:{{user_obj.name}}</li>
    {% endfor %}
</ul>

</body>
</html>
View Code

四、url常用匹配方法3--url的合理利用重复性:如

from django.conf.urls import url
from . import views
 
urlpatterns = [
    url(r'^(?P<page_slug>[\w-]+)-(?P<page_id>\w+)/history/$', views.history),
    url(r'^(?P<page_slug>[\w-]+)-(?P<page_id>\w+)/edit/$', views.edit),
    url(r'^(?P<page_slug>[\w-]+)-(?P<page_id>\w+)/discuss/$', views.discuss),
    url(r'^(?P<page_slug>[\w-]+)-(?P<page_id>\w+)/permissions/$', views.permissions),
]

为了不必要写这么多代码,可以用下面的方法替代:

from django.conf.urls import include, url
from . import views
 
urlpatterns = [
    url(r'^(?P<page_slug>[\w-]+)-(?P<page_id>\w+)/', include([
        url(r'^history/$', views.history),
        url(r'^edit/$', views.edit),
        url(r'^discuss/$', views.discuss),
        url(r'^permissions/$', views.permissions),
    ])),
]

2.同时,也可以在urls中标记,方便后续的查找,如:

urlpatterns = [ url(r'^blog/(?P<year>[0-9]{4})/$',views.year_archive, {'foo': 'bar'}),]

五、Django Views

1.最简单的返回一个字符串形式的view 

from django.http import HttpResponse
 
def my_view(request):
    if request.method == 'GET':
        # <view logic>
        return HttpResponse('result')

返回一个html文档用render

from django.shortcuts import render,HttpResponse

def test_view(request):
    return render(request,'index.html')

# 多级html文档返回
  
  return render(request, 'test_01/book_modelform.html')

关于render

help文档中描述如下:

render(request, template_name, context=None, content_type=None, status=None, using=None)

Returns a HttpResponse whose content is filled with the result of calling django.template.loader.render_to_string() with the passed arguments.

此方法的作用---结合一个给定的模板和一个给定的上下文字典,并返回一个渲染后的 HttpResponse 对象。

通俗的讲就是把context的内容, 加载进templates中定义的文件, 并通过浏览器渲染呈现.

讲解:

request: 是一个固定参数, 没什么好讲的。

template_name: templates 中定义的文件, 要注意路径名. 比如'templates\polls\index.html', 参数就要写‘polls\index.html’

context: 要传入文件中用于渲染呈现的数据, 默认是字典格式

content_type: 生成的文档要使用的MIME 类型。默认为DEFAULT_CONTENT_TYPE 设置的值。

status: http的响应代码,默认是200.

using: 用于加载模板使用的模板引擎的名称。

常见的MIME类型(通用型):

超文本标记语言文本 .html text/html
xml文档 .xml text/xml
XHTML文档 .xhtml application/xhtml+xml
普通文本 .txt text/plain
RTF文本 .rtf application/rtf
PDF文档 .pdf application/pdf
Microsoft Word文件 .word application/msword
PNG图像 .png image/png
GIF图形 .gif image/gif
JPEG图形 .jpeg,.jpg image/jpeg
au声音文件 .au audio/basic
MIDI音乐文件 mid,.midi audio/midi,audio/x-midi
RealAudio音乐文件 .ra, .ram audio/x-pn-realaudio
MPEG文件 .mpg,.mpeg video/mpeg
AVI文件 .avi video/x-msvideo
GZIP文件 .gz application/x-gzip
TAR文件 .tar application/x-tar
任意的二进制数据 application/octet-stream

举例

from django.shortcuts import render  
  
def my_view(request):  
    # View code here...  
    return render(request, 'myapp/index.html', {  
        'foo': 'bar',  
    }, content_type='application/xhtml+xml')  
原文地址:https://www.cnblogs.com/xiaobucainiao/p/6126042.html