Django学习笔记第七篇--实战练习三--关于更有层级的url请求、404错误以及其他响应函数

一、关于更有层级的URL:

可以实现每一个APP一个子URL目录,例如app1的所有操作都在http://www.localhost1.com:5443/app1/xxxx

在工程主文件夹下的工程同名文件夹下配置主urls.py

 1 from django.conf.urls import include, url
 2 from django.contrib import admin
 3 from myapp1 import views
 4 
 5 urlpatterns = [
 6     # Examples:
 7     # url(r'^$', 'mysite1.views.home', name='home'),
 8     # url(r'^blog/', include('blog.urls')),
 9 
10     url(r'^admin/', include(admin.site.urls)),
11     url(r'^myapp1/', include("myapp1.urls")),
12 ]

在myapp1文件夹下配置urls.py

 1 from django.conf.urls import include, url
 2 from myapp1 import views
 3 
 4 urlpatterns = [
 5     # Examples:
 6     # url(r'^$', 'mysite1.views.home', name='home'),
 7     # url(r'^blog/', include('blog.urls')),
 8     url(r'^register/', "myapp1.views.register"),
 9     url(r'^login/', "myapp1.views.login"),
10     url(r'^mainpage/', "myapp1.views.main"),
11     url(r'^verifycode/', "myapp1.views.verify"),
12 ]

当然html文件和视图函数中的url也要做对应修改。

二、关于404等错误的返回方法:

1、首先在urls.py中加入对应配置

1 #在url.py下面加入以下配置
2 handler404 = view.page_not_found
3 handler500 = view.page_error

2、编写对应的视图函数

1 def page_not_found(request):
2     return render_to_response("404.html")
3 def page_error(request):
4     return render_to_response("500.html")

即可。

三、关于render和render_to_reponse

1、render

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

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

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

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

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

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

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

2、render_to_response

1 #render是render_to_response的一个快捷方式
2 return render_to_response('blog_add.html',{'blog': blog, 'form':form, 'id': id, 'tag': tag},context_instance=RequestContext(request))
3 
4 return render(request, 'blog_add.html', {'blog': blog, 'form': form,'id': id, 'tag': tag})

3、render返回一个html页面:

1 render(request,"welcome.html")
原文地址:https://www.cnblogs.com/KevinGeorge/p/8396012.html