Django之View(视图)

 一、Django的View(视图)

一个视图函数(类),简称视图,是一个简单的Python 函数(类),它接受Web请求并且返回Web响应。用来处理业务逻辑。

响应可以是一张网页的HTML内容,一个重定向,一个404错误,一个XML文档,或者一张图片。

无论视图本身包含什么逻辑,都要返回响应。代码写在哪里也无所谓,只要它在你当前项目目录下面。除此之外没有更多的要求了——可以说“没有什么神奇的地方”。为了将代码放在某处,大家约定成俗将视图放置在项目(project)或应用程序(app)目录中的名为views.py的文件中。

(一)一个简单的视图

下面是一个以HTML文档的形式返回当前日期和时间的视图:

from django.http import HttpResponse
import datetime

def current_datetime(request):
    now = datetime.datetime.now()
    html = "<html><body>It is now %s.</body></html>" % now
    return HttpResponse(html)
  • 首先,我们从 django.http模块导入了HttpResponse类,以及Python的datetime库。

  • 接着,我们定义了current_datetime函数。它就是视图函数。每个视图函数都使用HttpRequest对象作为第一个参数,并且通常称之为request

    注意,视图函数的名称并不重要;不需要用一个统一的命名方式来命名,以便让Django识别它。我们将其命名为current_datetime,是因为这个名称能够比较准确地反映出它实现的功能。

  • 这个视图会返回一个HttpResponse对象,其中包含生成的响应。每个视图函数都负责返回一个HttpResponse对象。

Django使用请求和响应对象来通过系统传递状态。

当浏览器向服务端请求一个页面时,Django创建一个HttpRequest对象,该对象包含关于请求的元数据。然后,Django加载相应的视图,将这个HttpRequest对象作为第一个参数传递给视图函数。

每个视图负责返回一个HttpResponse对象。

(二)CBV和FBV

基于函数的view,就叫FBV(function based view)。基于类的view就叫做CBV (class based view )

FBV版

#添加出版社
def add_publisher(request):
    if request.method == 'POST':
        add_name = request.POST.get('new_name')
        if not add_name:
            return render(request, 'add_publisher.html', {"err_name": add_name, 'err_msg': '不能为空'})
        pub_list = models.Publisher.objects.filter(name=add_name)
        if pub_list:
            return render(request, 'add_publisher.html',{"err_name":add_name,'err_msg':'出版社已存在'})
        models.Publisher.objects.create(name=add_name)
        return redirect('/publisher/')
    return render(request,'add_publisher.html')

CBV版

 
 
from django.views import View # 先导入View模块
class AddPublisher(View):

    def get(self, request):
        print('这个是get')
        # print(self.request)
        return render(self.request, 'add_publisher.html')

    def post(self, request):
        print('这个是post')
        err_msg = ''
        add_name = request.POST.get('new_name')
        pub_list = models.Publisher.objects.filter(name=add_name)
        if add_name and not pub_list:
            models.Publisher.objects.create(name=add_name)
            return redirect('/publisher/')
        if not add_name:
            err_msg = '不能为空'
        if pub_list:
            err_msg = '出版社已存在'

        return render(request, 'add_publisher.html', {"err_name": add_name, 'err_msg': err_msg})

修改urls.py

url(r'^add_publisher/', views.AddPublisher.as_view()),

(三)分析CBV执行的流程

 
 

1. AddPublisher.as_view() ——》 view函数
2. 当请求到来的时候才执行view函数
  1. 实例化AddPublisher ——》 self
  2. self.request = request
  3. 执行self.dispatch(request, *args, **kwargs)
      1. 判断请求方式是否被允许
        handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
        通过反射获取对应的方法
        GET ——》 get
        POST ——》 post

      2. 执行获取到的方法 get(request,) 或者post(request,)
      3. 得到HttpResponse对象,返回给self.dispatch
  4. 得到HttpResponse对象,返回django处理


@classonlymethod
def as_view(cls, **initkwargs): """ Main entry point for a request-response process. """ for key in initkwargs: if key in cls.http_method_names: raise TypeError("You tried to pass in the %s method name as a " "keyword argument to %s(). Don't do that." % (key, cls.__name__)) if not hasattr(cls, key): raise TypeError("%s() received an invalid keyword %r. as_view " "only accepts arguments that are already " "attributes of the class." % (cls.__name__, key)) def view(request, *args, **kwargs):
self
= cls(**initkwargs) if hasattr(self, 'get') and not hasattr(self, 'head'): self.head = self.get self.request = request self.args = args self.kwargs = kwargs return self.dispatch(request, *args, **kwargs) view.view_class = cls view.view_initkwargs = initkwargs # take name and docstring from class update_wrapper(view, cls, updated=()) # and possible attributes set by decorators # like csrf_exempt from dispatch update_wrapper(view, cls.dispatch, assigned=()) return view def dispatch(self, request, *args, **kwargs): # Try to dispatch to the right method; if a method doesn't exist, # defer to the error handler. Also defer to the error handler if the # request method isn't on the approved list. if request.method.lower() in self.http_method_names: handler = getattr(self, request.method.lower(), self.http_method_not_allowed) else: handler = self.http_method_not_allowed return handler(request, *args, **kwargs)

(四)给视图加装饰器

1、FBV加装饰器

FBV本身就是一个函数,所以和给普通的函数加装饰器无差:

def wapper(func):
    def inner(*args, **kwargs):
        start = time.time()
        ret = func(*args, **kwargs)
        print("函数的执行时间是:{}".format(time.time() - start))
        return ret

    return inner
@wapper
def add_publisher(request):
    add_name, err_msg = '', ''
    if request.method == 'POST':
        add_name = request.POST.get('new_name')
        pub_list = models.Publisher.objects.filter(name=add_name)
        if add_name and not pub_list:
            models.Publisher.objects.create(name=add_name)
            return redirect('/publisher/')
        if not add_name:
            err_msg = '不能为空'
        if pub_list:
            err_msg = '出版社已存在'
    return render(request, 'add_publisher.html', {"err_name": add_name, 'err_msg': err_msg})

2、使用装饰器装饰CBV

类中的方法与独立函数不完全相同,因此不能直接将函数装饰器应用于类中的方法 ,我们需要先将其转换为方法装饰器。

Django中提供了method_decorator装饰器用于将函数装饰器转换为方法装饰器。

先导入method_decorator

from django.utils.decorators import method_decorator

方法一:加在方法上

class AddPublisher(View):
def get(self, request):
        print('这个是get')
        # print(self.request)
        return render(self.request, 'add_publisher.html')

    @method_decorator(wapper) # 把装饰器当参数传进去
    def post(self, request):
        print('这个是post')
        err_msg = ''
        add_name = request.POST.get('new_name')
        pub_list = models.Publisher.objects.filter(name=add_name)
        if add_name and not pub_list:
            models.Publisher.objects.create(name=add_name)
            return redirect('/publisher/')
        if not add_name:
            err_msg = '不能为空'
        if pub_list:
            err_msg = '出版社已存在'

        return render(request, 'add_publisher.html', {"err_name": add_name, 'err_msg': err_msg})

方法二:加在类上

@method_decorator(wapper, name='post') #也可以同时给两个方法都加上,name就是方法的名称
@method_decorator(wapper, name='get')
class AddPublisher(View):
def get(self, request):
        print('这个是get')
        # print(self.request)
        return render(self.request, 'add_publisher.html')

    def post(self, request):
        print('这个是post')
        err_msg = ''
        add_name = request.POST.get('new_name')
        pub_list = models.Publisher.objects.filter(name=add_name)
        if add_name and not pub_list:
            models.Publisher.objects.create(name=add_name)
            return redirect('/publisher/')
        if not add_name:
            err_msg = '不能为空'
        if pub_list:
            err_msg = '出版社已存在'

        return render(request, 'add_publisher.html', {"err_name": add_name, 'err_msg': err_msg})

方法三:

请求过来后会先执行dispatch()这个方法,如果需要批量对具体的请求处理方法,如get,post等做一些操作的时候,这里我们可以手动改写dispatch方法,然后给dispatch加装饰器相当于是给类里的方法都加了装饰器。

class AddPublisher(View):

    @method_decorator(wapper)
    def dispatch(self, request, *args, **kwargs):
        print('执行get方法之前')
        ret = super().dispatch(request, *args, **kwargs)
        print('执行get方法之后')
        return ret

    def get(self, request):
        print('这个是get')
        # print(self.request)
        return render(self.request, 'add_publisher.html')

    def post(self, request):
        print('这个是post')
        err_msg = ''
        add_name = request.POST.get('new_name')
        pub_list = models.Publisher.objects.filter(name=add_name)
        if add_name and not pub_list:
            models.Publisher.objects.create(name=add_name)
            return redirect('/publisher/')
        if not add_name:
            err_msg = '不能为空'
        if pub_list:
            err_msg = '出版社已存在'

        return render(request, 'add_publisher.html', {"err_name": add_name, 'err_msg': err_msg})

二、request对象

 当一个页面被请求时,Django就会创建一个包含本次请求原信息的HttpRequest对象。Django会将这个对象自动传递给响应的视图函数,一般视图函数约定俗成地使用 request 参数承接这个对象。

(一)request对象属性

django将请求报文中的请求行、头部信息、内容主体封装成 HttpRequest 类中的属性。 除了特殊说明的之外,其他均为只读的。

1、HttpRequest.scheme

表示请求方案的字符串(通常为http或https)

2、HttpRequest.body

一个字符串,代表请求报文的主体。在处理非 HTTP 形式的报文时非常有用,例如:二进制图片、XML,Json等。 但是,如果要处理表单数据的时候,推荐还是使用 HttpRequest.POST 。  另外,我们还可以用 python 的类文件方法去操作它,详情参考 HttpRequest.read() 。

3、HttpRequest.path

一个字符串,表示请求的路径组件(不含域名)。   例如:"/music/bands/the_beatles/"

4、HttpRequest.method

一个字符串,表示请求使用的HTTP 方法。必须使用大写。   例如:"GET"、"POST"

5、HttpRequest.encoding

一个字符串,表示提交的数据的编码方式(如果为 None 则表示使用 DEFAULT_CHARSET 的设置,默认为 'utf-8')。 这个属性是可写的,你可以修改它来修改访问表单数据使用的编码。 接下来对属性的任何访问(例如从 GET 或 POST 中读取数据)将使用新的 encoding 值。 如果你知道表单数据的编码不是 DEFAULT_CHARSET ,则使用它。

6、HttpRequest.GET

一个类似于字典的对象,包含 HTTP GET 的所有参数。详情请参考 QueryDict 对象。

"GET /test/?a=1&b=3 HTTP/1.1" 200 422
<QueryDict: {'a': ['1'], 'b': ['3']}>

7、 HttpRequest.POST

一个类似于字典的对象,如果请求中包含表单数据,则将这些数据封装成 QueryDict 对象。   POST 请求可以带有空的 POST 字典 —— 如果通过 HTTP POST 方法发送一个表单,但是表单中没有任何的数据,QueryDict 对象依然会被创建。 因此,不应该使用 if request.POST 来检查使用的是否是POST 方法;应该使用 if request.method == "POST"   另外:如果使用 POST 上传文件的话,文件信息将包含在 FILES 属性中。

<QueryDict: {'new_name': ['大遥'], 's_new_id': ['2']}>

 8、HttpRequest.COOKIES

一个标准的Python 字典,包含所有的cookie。键和值都为字符串。

{'sessionid': 'or3j83c6ve9jq9mrns415t96ft9cad41', 'csrftoken': 'DGHcCwbCjmny2XTznEXUWyWo1c2qeSLQRGIGpEQxH4TuqlWWelNvbK36tM2Cvi7L'}

9、HttpRequest.FILES

一个类似于字典的对象,包含所有的上传文件信息。 FILES 中的每个键为<input type="file" name="" /> 中的name,值则为对应的数据。   

注意,FILES 只有在请求的方法为POST 且提交的<form> 带有enctype="multipart/form-data" 的情况下才会 包含数据。否则,FILES 将为一个空的类似于字典的对象。

<form action="" method="post" enctype="multipart/form-data"> {% csrf_token %}
        <p><input type="file" name="file"></p>
        <p><input type="submit" value="提交"></p>
    </form>


<MultiValueDict: {'file': [<TemporaryUploadedFile: python知识点汇总.xmind.zip (application/zip)>]}>

10、HttpRequest.META   

一个标准的Python 字典,包含所有的HTTP 首部。具体的头部信息取决于客户端和服务器,

下面是一些示例:

CONTENT_LENGTH —— 请求的正文的长度(是一个字符串)。

CONTENT_TYPE —— 请求的正文的MIME 类型。

HTTP_ACCEPT —— 响应可接收的Content-Type。

HTTP_ACCEPT_ENCODING —— 响应可接收的编码。

HTTP_ACCEPT_LANGUAGE —— 响应可接收的语言。

HTTP_HOST —— 客服端发送的HTTP Host 头部。

HTTP_REFERER —— Referring 页面。

HTTP_USER_AGENT —— 客户端的user-agent 字符串。

QUERY_STRING —— 单个字符串形式的查询字符串(未解析过的形式)。

REMOTE_ADDR —— 客户端的IP 地址。

REMOTE_HOST —— 客户端的主机名。

REMOTE_USER —— 服务器认证后的用户。

REQUEST_METHOD —— 一个字符串,例如"GET""POST"。

SERVER_NAME —— 服务器的主机名。 SERVER_PORT —— 服务器的端口(是一个字符串)。

   

从上面可以看到,除 CONTENT_LENGTH 和 CONTENT_TYPE 之外,请求中的任何 HTTP 首部转换为 META 的键时, 都会将所有字母大写并将连接符替换为下划线最后加上 HTTP_ 前缀。 所以,一个叫做 X-Bender 的头部将转换成 META 中的 HTTP_X_BENDER 键。

{'PATH': '/Users/mengjuncheng/PycharmProjects/venv/bin:/Library/Frameworks/Python.framework/Versions/3.6/bin:/opt/local/bin:/opt/local/sbin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Applications/VMware Fusion.app/Contents/Public:/Applications/Wireshark.app/Contents/MacOS', 'PYTHONPATH': '/Applications/PyCharm.app/Contents/helpers/pycharm_matplotlib_backend:/Users/mengjuncheng/PycharmProjects/python/django_test/my_class', 'SHELL': '/bin/bash', 'PYTHONIOENCODING': 'UTF-8', 'VERSIONER_PYTHON_PREFER_32_BIT': 'no', 'USER': 'mengjuncheng', 'TMPDIR': '/var/folders/w3/18sj0m9d69s7pn63r9mkz90r0000gn/T/', 'PS1': '(venv) ', 'SSH_AUTH_SOCK': '/private/tmp/com.apple.launchd.ElXsHyn4eH/Listeners', 'DJANGO_SETTINGS_MODULE': 'my_class.settings', 'VIRTUAL_ENV': '/Users/mengjuncheng/PycharmProjects/venv', 'XPC_FLAGS': '0x0', 'PYTHONUNBUFFERED': '1', 'VERSIONER_PYTHON_VERSION': '2.7', '__CF_USER_TEXT_ENCODING': '0x1F5:0x19:0x34', 'Apple_PubSub_Socket_Render': '/private/tmp/com.apple.launchd.IYYi3NTT5K/Render', 'LOGNAME': 'mengjuncheng', 'LC_CTYPE': 'zh_CN.UTF-8', 'XPC_SERVICE_NAME': 'com.jetbrains.pycharm.6972', 'PWD': '/Users/mengjuncheng/PycharmProjects/python/django_test/my_class', 'PYCHARM_HOSTED': '1', 'HOME': '/Users/mengjuncheng', 'PYCHARM_MATPLOTLIB_PORT': '50503', '__PYVENV_LAUNCHER__': '/Users/mengjuncheng/PycharmProjects/venv/bin/python', 'TZ': 'UTC', 'RUN_MAIN': 'true', 'SERVER_NAME': '1.0.0.127.in-addr.arpa', 'GATEWAY_INTERFACE': 'CGI/1.1', 'SERVER_PORT': '8000', 'REMOTE_HOST': '', 'CONTENT_LENGTH': '4962955', 'SCRIPT_NAME': '', 'SERVER_PROTOCOL': 'HTTP/1.1', 'SERVER_SOFTWARE': 'WSGIServer/0.2', 'REQUEST_METHOD': 'POST', 'PATH_INFO': '/test/', 'QUERY_STRING': '', 'REMOTE_ADDR': '127.0.0.1', 'CONTENT_TYPE': 'multipart/form-data; boundary=----WebKitFormBoundaryeIuoGNwKyBSt4WBZ', 'HTTP_HOST': '127.0.0.1:8000', 'HTTP_ACCEPT': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'HTTP_ACCEPT_ENCODING': 'gzip, deflate', 'HTTP_ACCEPT_LANGUAGE': 'zh-cn', 'HTTP_ORIGIN': 'http://127.0.0.1:8000', 'HTTP_USER_AGENT': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0 Safari/605.1.15', 'HTTP_CONNECTION': 'keep-alive', 'HTTP_UPGRADE_INSECURE_REQUESTS': '1', 'HTTP_REFERER': 'http://127.0.0.1:8000/test/', 'HTTP_COOKIE': 'sessionid=or3j83c6ve9jq9mrns415t96ft9cad41; csrftoken=DGHcCwbCjmny2XTznEXUWyWo1c2qeSLQRGIGpEQxH4TuqlWWelNvbK36tM2Cvi7L', 'wsgi.input': <_io.BufferedReader name=6>, 'wsgi.errors': <_io.TextIOWrapper name='<stderr>' mode='w' encoding='UTF-8'>, 'wsgi.version': (1, 0), 'wsgi.run_once': False, 'wsgi.url_scheme': 'http', 'wsgi.multithread': True, 'wsgi.multiprocess': False, 'wsgi.file_wrapper': <class 'wsgiref.util.FileWrapper'>}

11、HttpRequest.user

一个 AUTH_USER_MODEL 类型的对象,表示当前登录的用户。   如果用户当前没有登录,user 将设置为 django.contrib.auth.models.AnonymousUser 的一个实例。你可以通过 is_authenticated() 区分它们。

例如:

    if request.user.is_authenticated():
        # Do something for logged-in users.
    else:
        # Do something for anonymous users.
     

       user 只有当Django 启用 AuthenticationMiddleware 中间件时才可用。

     -------------------------------------------------------------------------------------

    匿名用户
    class models.AnonymousUser

    django.contrib.auth.models.AnonymousUser 类实现了django.contrib.auth.models.User 接口,但具有下面几个不同点:

    id 永远为None。
    username 永远为空字符串。
    get_username() 永远返回空字符串。
    is_staff 和 is_superuser 永远为False。
    is_active 永远为 False。
    groups 和 user_permissions 永远为空。
    is_anonymous() 返回True 而不是False。
    is_authenticated() 返回False 而不是True。
    set_password()、check_password()、save() 和delete() 引发 NotImplementedError。
    New in Django 1.8:
    新增 AnonymousUser.get_username() 以更好地模拟 django.contrib.auth.models.User。

12、HttpRequest.session

一个既可读又可写的类似于字典的对象,表示当前的会话。只有当Django 启用会话的支持时才可用。 完整的细节参见会话的文档。

print(request.session)
<django.contrib.sessions.backends.db.SessionStore object at 0x10fe50e10>
----------------------------------
print(request.session.items())
dict_items([('is_login', True)])

一则上传文件实例

def upload(request):
    """
    保存上传文件前,数据需要存放在某个位置。默认当上传文件小于2.5M时,django会将上传文件的全部内容读进内存。从内存读取一次,写磁盘一次。
    但当上传文件很大时,django会把上传文件写到临时文件中,然后存放到系统临时文件夹中。
    :param request: 
    :return: 
    """
    if request.method == "POST":
        # 从请求的FILES中获取上传文件的文件名,file为页面上type=files类型input的name属性值
        filename = request.FILES["file"].name
        # 在项目目录下新建一个文件
        with open(filename, "wb") as f:
            # 从上传的文件对象中一点一点读
            for chunk in request.FILES["file"].chunks():
                # 写入本地文件
                f.write(chunk)
        return HttpResponse("上传OK")

(二)request对象方法

1、HttpRequest.get_host()   

根据从HTTP_X_FORWARDED_HOST(如果打开 USE_X_FORWARDED_HOST,默认为False)和 HTTP_HOST 头部信息返回请求的原始主机。 如果这两个头部没有提供相应的值,则使用SERVER_NAME 和SERVER_PORT,在PEP 3333 中有详细描述。   USE_X_FORWARDED_HOST:一个布尔值,用于指定是否优先使用 X-Forwarded-Host 首部,仅在代理设置了该首部的情况下,才可以被使用。   例如:"127.0.0.1:8000"   注意:当主机位于多个代理后面时,get_host() 方法将会失败。除非使用中间件重写代理的首部。

2、HttpRequest.get_full_path()   

返回 path,如果可以将加上查询字符串, 和属性path_info的结果一样    例如:"/music/bands/the_beatles/?print=true"

3、HttpRequest.get_signed_cookie(key, default=RAISE_ERROR, salt='', max_age=None)   

返回签名过的Cookie 对应的值,如果签名不再合法则返回django.core.signing.BadSignature。   如果提供 default 参数,将不会引发异常并返回 default 的值。   可选参数salt 可以用来对安全密钥强力攻击提供额外的保护。max_age 参数用于检查Cookie 对应的时间戳以确保Cookie 的时间不会超过max_age 秒。

     >>> request.get_signed_cookie('name')
        'Tony'
        >>> request.get_signed_cookie('name', salt='name-salt')
        'Tony' # 假设在设置cookie的时候使用的是相同的salt
        >>> request.get_signed_cookie('non-existing-cookie')
        ...
        KeyError: 'non-existing-cookie'    # 没有相应的键时触发异常
        >>> request.get_signed_cookie('non-existing-cookie', False)
        False
        >>> request.get_signed_cookie('cookie-that-was-tampered-with')
        ...
        BadSignature: ...    
        >>> request.get_signed_cookie('name', max_age=60)
        ...
        SignatureExpired: Signature age 1677.3839159 > 60 seconds
        >>> request.get_signed_cookie('name', False, max_age=60)
        False

4.HttpRequest.is_secure()

如果请求时是安全的,则返回True;即请求通是过 HTTPS 发起的。

 5、HttpRequest.is_ajax()

如果请求是通过XMLHttpRequest 发起的,则返回True,方法是检查 HTTP_X_REQUESTED_WITH 相应的首部是否是字符串'XMLHttpRequest'。   大部分现代的 JavaScript 库都会发送这个头部。如果你编写自己的 XMLHttpRequest 调用(在浏览器端),你必须手工设置这个值来让 is_ajax() 可以工作。   如果一个响应需要根据请求是否是通过AJAX 发起的,并且你正在使用某种形式的缓存例如Django 的 cache middleware, 你应该使用 vary_on_headers('HTTP_X_REQUESTED_WITH') 装饰你的视图以让响应能够正确地缓存。

 注意:键值对的值是多个的时候,比如checkbox类型的input标签,select标签,需要用:

request.POST.getlist("hobby")

三、Response对象

与由Django自动创建的HttpRequest对象相比,HttpResponse对象是我们的职责范围了。我们写的每个视图都需要实例化,填充和返回一个HttpResponse。

HttpResponse类位于django.http模块中。

(一)使用

传递字符串

from django.http import HttpResponse
response = HttpResponse("Here's the text of the Web page.")
response = HttpResponse("Text only, please.", content_type="text/plain")

删除或设置响应头信息

response = HttpResponse()
response['Content-Type'] = 'text/html; charset=UTF-8'
del response['Content-Type']

(二)属性

HttpResponse.content:响应内容

HttpResponse.charset:响应内容的编码

HttpResponse.status_code:响应的状态码

四、JsonResponse对象

JsonResponse是HttpResponse的子类,专门用来生成JSON编码的响应。

from django.http import JsonResponse

response = JsonResponse({'foo': 'bar'})
print(response.content)

b'{"foo": "bar"}'

默认只能传递字典类型,如果要传递非字典类型需要设置一下safe关键字参数

response = JsonResponse([1, 2, 3], safe=False)

五、Django shortcut functions

(一)render()

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

参数:

  • request: 用于生成响应的请求对象。
  • template_name:要使用的模板的完整名称,可选的参数
  • context:添加到模板上下文的一个字典。默认是一个空字典。如果字典中的某个值是可调用的,视图将在渲染模板之前调用它。
  • content_type:生成的文档要使用的MIME类型。默认为 DEFAULT_CONTENT_TYPE 设置的值。默认为'text/html'
  • status:响应的状态码。默认为200。
  • useing: 用于加载模板的模板引擎的名称。

一个简单的例子:

from django.shortcuts import render

def my_view(request):
    # 视图的代码写在这里
    return render(request, 'myapp/index.html', {'foo': 'bar'})

上面的代码等于:

from django.http import HttpResponse
from django.template import loader

def my_view(request):
    # 视图代码写在这里
    t = loader.get_template('myapp/index.html')
    c = {'foo': 'bar'}
    return HttpResponse(t.render(c, request))

(二)redirect()

参数可以是:

  • 一个模型:将调用模型的get_absolute_url() 函数
  • 一个视图,可以带有参数:将使用urlresolvers.reverse 来反向解析名称
  • 一个绝对的或相对的URL,将原封不动的作为重定向的位置。

默认返回一个临时的重定向;传递permanent=True 可以返回一个永久的重定向。

示例:

你可以用多种方式使用redirect() 函数。

传递一个具体的ORM对象(了解即可)

将调用具体ORM对象的get_absolute_url() 方法来获取重定向的URL:

from django.shortcuts import redirect
 
def my_view(request):
    ...
    object = MyModel.objects.get(...)
    return redirect(object)

传递一个视图的名称

def my_view(request):
    ...
    return redirect('some-view-name', foo='bar')

传递要重定向到的一个具体的网址

def my_view(request):
    ...
    return redirect('/some/url/')

当然也可以是一个完整的网址

def my_view(request):
    ...
    return redirect('http://example.com/')

默认情况下,redirect() 返回一个临时重定向。以上所有的形式都接收一个permanent 参数;如果设置为True,将返回一个永久的重定向:

def my_view(request):
    ...
    object = MyModel.objects.get(...)
    return redirect(object, permanent=True)  

扩展阅读: 

临时重定向(响应状态码:302)和永久重定向(响应状态码:301)对普通用户来说是没什么区别的,它主要面向的是搜索引擎的机器人。

A页面临时重定向到B页面,那搜索引擎收录的就是A页面。

A页面永久重定向到B页面,那搜索引擎收录的就是B页面。

猜你喜欢

转载自www.cnblogs.com/mjc69213/p/9691522.html