Django views 中的 shortcut function】的更多相关文章

shortcut function都在django.shortcuts这个包中,主要包含有:render(), render_to_response(), redirect(), get_objects_or_404(), get_list_or_404() 1. render(request, template_name, context=None, context_instance=_context_instance_undefined, content_type=None, status=…
decorators(装饰器) 1. require_http_methods 在django.views.decorators.http中,可以用来限制请求的权限. require_http_methods(request_method_list), 这样只有request_method_list中的方法可以得到结果,否则view不会接受请求.看下面官方例子,@require_http_methods(["GET","POST"]),结果是只有GET,POST的请…
def message(request): message_list = MessageBoard.objects.all().order_by('-pk') return render(request, 'message_board.html', message_list) 出错的代码位置 实际上views中返回的必须是字典 见http://stackoverflow.com/questions/31105131/django-cannot-convert-dictionary-update-…
关于装饰器 示例: 有返回值的装饰器:判断用户是否登录,如果登录继续执行函数,否则跳回登录界面 def auth(func): def inner(request, *args, **kwargs): username = request.COOKIES.get('username') if not username: # 如果无法获取 'username' COOKIES,就跳转到 '/login.html' return redirect('/login.html') # 原函数执行前 re…
知其然亦要知其所以然 views每个方法的参数都是request,那么问题来了,request为何物? 首先,几乎每个方法都是取数据(无论是从数据库,还是从第三方接口),然后进行一定的处理,之后传给前端.而前端请求数据,就会向后端发送一个http请求,这个请求的请求路径,经过urls,会调用url中指定的方法.此时django就会将HttpRequest对象作为第一个参数传入此方法.故,request即为一个httpRequest对象. 然后,出现了一个新问题,httpRequest是什么,又含…
Django框架中views视图中如果多个函数都有同样的查询语句,例如: allcategory = Category.objects.all() remen = Article.objects.filter(tui__id=2)[:6] tags = Tag.objects.all() 如果不优化,会导致每执行一次函数,都会重新查询一遍数据库,现进行简要优化:步骤如下 第一步,将以上三行语句拷贝出来,重构成一个独立的函数如下: def global_variable(request): all…
在 Django 模板中遍历复杂数据结构的关键是句点字符 ( . ). 实例二 mysit/templates/myhtml2.html修改如下 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {{ time.year }}…
碧玉妆成一树高,万条垂下绿丝绦. 不知细叶谁裁出,二月春风似剪刀. 原文尽在:http://djangobook.com/ 转载请注明出处:http://www.cnblogs.com/A-FM/p/6721382.html Django Views and URLconfs(Django的视图和URL配置) In the previous chapter, I explained how to set up a Django project and run the Django develop…
首先下载plupload插件放在static静态文件下面,官方地址:https://www.plupload.com/ 项目根目录下创建media文件夹用来存放上传的图片,配置settings文件,添加media的文件路径 MEDIA_ROOT = os.path.join(BASE_DIR,'media') 先写前端html页面 {# 引入插件#} <script src="/static/plupload/moxie.js"></script> <sc…
Django的View(视图)简介 一个视图函数(类),简称视图,是一个简单的Python 函数(类),它接受Web请求并且返回Web响应. 响应可以是一张网页的HTML内容,一个重定向,一个404错误,一个XML文档,或者一张图片. 无论视图本身包含什么逻辑,都要返回响应.代码写在哪里也无所谓,只要它在你当前项目目录下面.除此之外没有更多的要求了——可以说“没有什么神奇的地方”.为了将代码放在某处,大家约定成俗将视图放置在项目(project)或应用程序(app)目录中的名为views.py的…