Django笔记2

使用templates模板

1、在app项目目录下新建templates文件夹

2、在templates下创建app名字的文件夹。进入后再创建index.html    结构/app/templates/app/index.html

3、在2中创建的index.html中写入页面代码.插入python语句,使用{% xxx %}


Django笔记2_第1张图片

4、把3中创建的index.html添加到app的views.py 文件中    #使用loader.get_template方法

首先导入template的loader方法

from django.template import loader

template = loader.get_template('路径')

context={字典数据}

return HttpResponse(template.render(context,request))  使用render方法把数据从request传输到response中返回给用户


render()方法:

It’s a very common idiom to load a template,

fill a context and return an HttpResponse object with the result of the rendered template.

The render() function takes the request object as its first argument,

a template name as its second argument and a dictionary as its optional third argument.

It returns an HttpResponse object of the given template rendered with the given context.

使用这个方法可以替代4步骤中导入loader跟使用HttpResponse()方法

template = loader.get_template('路径')

return HttpResponse(template.render(context,request))

这两句代码可直接变为

return render(request,'路径',context)


404异常处理

使用try 来对数据库查找不到结果时进行异常处理

需要   from django.http import Http404

Django笔记2_第2张图片

这里有更简单的方法.使用短语(A shortcut:get_object_or_404())

上面图片的代码可修改为

Django笔记2_第3张图片

The get_object_or_404()function takes a Django model as its first argument and an arbitrary number of keyword arguments, which it passes to the get()function of the model’s manager. It raises Http404 if the object doesn’t exist.

There’s also a get_list_or_404() function, which works just as get_object_or_404()– except using filter() instead of get(). It raises Http404 if the list is empty.

对detail.html 页面的构建


Django笔记2_第4张图片

{{  这是用于存放变量的}}

{% 这是用于存放python代码的%}

在templates中.如果html页面源码

像这样的代码显得太过厚重.可以利用在urls.py中对url起名字来代替href 的如 '' /polls ''  拼接


Django笔记2_第5张图片

views中的命名空间

当django项目中有很多不同的app时,不同的app项目中有不同的urls.py文件,这是要在templates中的html页面中运用{% url 'detail' question.id %}

时要注意命名空间问题.

方法:

1.在urls.py中添加app_name 参数

2.在相应的页面添加{%url xxx%}代码来获得对应的url参数构造


Django笔记2_第6张图片


Django笔记2_第7张图片

你可能感兴趣的:(Django笔记2)