Django 视图

项目创建
python s.py djangoproject usr_app
创建后的目录截图如下

urls.py设定
#djangoproject的urls.py指向app_user的urls.py--namespace:模块名

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

urlpatterns = [
    #app_user
    url(r'^', include('app_user.urls',namespace="app_user")),
    
    #admin
    url(r'^admin/', include(admin.site.urls)),
]

#app_user内urls.py文件设定该模块的所有路由

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

urlpatterns = [
    #name--反向解析的名字
    url(r'^app_user$', views.test,name="user"),
]
写一个小视图模板进行测试
<!-- 简单的视图模板 -->

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

    <p> 你好:{{ usrname }}</p>
    <!-- 使用反向解析,传递的user就是视图中设定的解析路由,即/app_user/ -->
    <a herf="{% url 'app_user:user' %}">{% url 'app_user:user' %}</a>

</body>
</html>
app_user:view.py 编写视图,构建上下文,生成html网页,设定cookie值
#coding: utf-8

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

def test(request):
    #构建上下文
    context = dict(
        usrname="shihongguang"
    )
    
    #render构建要返回的HttpResponse(request,templates,context)
    response = render(request, 'app_user/test.html', context)
    
    #HttpResponse设定cookie,后面的都时默认参数,方便后面查看
    response.set_cookie("auth",value="shihongguang",max_age=None, expires=None, path='/',
                   domain=None, secure=False, httponly=False)
    
    #返回构建好的response
    return response

修改搜索的模板路径
#模板路径修改
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',
            ],
        },
    },
]
启动测试服务器
./manage.py runserver
浏览器运行的结果


第一篇,写完了,后续会继续更新。欢迎大家批评指正。
posted @ 2017-05-28 23:39  sawyer_aquarius  阅读(140)  评论(0编辑  收藏  举报