- 浏览: 20548 次
- 性别:
- 来自: TW
文章分类
最新评论
以下代碼節錄自 Django Book - Chapter 3 & 8
default in django:
use imported function:
use views.py:
use by string:
mutiple:
special-casing URLs:
use named group:
Passing Extra Options to View Functions(1):
Passing Extra Options to View Functions(2):
Faking Captured URLconf Values:
Making a View Generic:
View Configuration Options:
Using Default View Arguments
Special-Casing Views
Capturing Text in URLs:
Higher-Level Abstractions of View Functions
Python function parameter
Wrapping View Functions:
Including Other URLconfs
How Captured Parameters Work with include():
How Extra URLconf Options Work with include()
default in django:
from django.conf.urls.defaults import * # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover() urlpatterns = patterns('', # Example: # (r'^mysite/', include('mysite.foo.urls')), # Uncomment the admin/doc line below and add 'django.contrib.admindocs' # to INSTALLED_APPS to enable admin documentation: # (r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: # (r'^admin/', include(admin.site.urls)), )
use imported function:
from django.conf.urls.defaults import * from mysite.views import hello, current_datetime urlpatterns = patterns('', ('^hello/$', hello), ('^time/$', current_datetime), )
use views.py:
from django.conf.urls.defaults import * from mysite import views urlpatterns = patterns('', (r'^hello/$', views.hello), (r'^time/$', views.current_datetime), (r'^time/plus/(d{1,2})/$', views.hours_ahead), )
use by string:
from django.conf.urls.defaults import * urlpatterns = patterns('', (r'^hello/$', 'mysite.views.hello'), (r'^time/$', 'mysite.views.current_datetime'), (r'^time/plus/(d{1,2})/$', 'mysite.views.hours_ahead'), ) urlpatterns = patterns('mysite.views', (r'^hello/$', 'hello'), (r'^time/$', 'current_datetime'), (r'^time/plus/(d{1,2})/$', 'hours_ahead'), )
mutiple:
from django.conf.urls.defaults import * urlpatterns = patterns('mysite.views', (r'^hello/$', 'hello'), (r'^time/$', 'current_datetime'), (r'^time/plus/(\d{1,2})/$', 'hours_ahead'), ) urlpatterns += patterns('weblog.views', (r'^tag/(\w+)/$', 'tag'), )
special-casing URLs:
from django.conf import settings from django.conf.urls.defaults import * from mysite import views urlpatterns = patterns('', (r'^$', views.homepage), (r'^(\d{4})/([a-z]{3})/$', views.archive_month), ) if settings.DEBUG: urlpatterns += patterns('', (r'^debuginfo/$', views.debug), )
use named group:
from django.conf.urls.defaults import * from mysite import views urlpatterns = patterns('', (r'^articles/(?P<year>\d{4})/$', views.year_archive), (r'^articles/(?P<year>\d{4})/(?P<month>\d{2})/$', views.month_archive), ) #the same request would result in this function call: views.month_archive(request, year='2006', month='03')
Passing Extra Options to View Functions(1):
# urls.py from django.conf.urls.defaults import * from mysite import views urlpatterns = patterns('', (r'^(foo)/$', views.foobar_view), (r'^(bar)/$', views.foobar_view), ) # views.py from django.shortcuts import render_to_response from mysite.models import MyModel def foobar_view(request, url): m_list = MyModel.objects.filter(is_new=True) if url == 'foo': template_name = 'template1.html' elif url == 'bar': template_name = 'template2.html' return render_to_response(template_name, {'m_list': m_list})
Passing Extra Options to View Functions(2):
# urls.py from django.conf.urls.defaults import * from mysite import views urlpatterns = patterns('', (r'^foo/$', views.foobar_view, {'template_name': 'template1.html'}), (r'^bar/$', views.foobar_view, {'template_name': 'template2.html'}), ) # views.py from django.shortcuts import render_to_response from mysite.models import MyModel def foobar_view(request, template_name): m_list = MyModel.objects.filter(is_new=True) return render_to_response(template_name, {'m_list': m_list})
Faking Captured URLconf Values:
#/mydata/jan/01/ #/mydata/jan/02/ #/mydata/jan/03/ ## ... #/mydata/dec/30/ #/mydata/dec/31/ # URLconf urlpatterns = patterns('', (r'^mydata/(?P<month>\w{3})/(?P<day>\d\d)/$', views.my_view), ) # view function def my_view(request, month, day): # ....
Making a View Generic:
# urls.py from django.conf.urls.defaults import * from mysite import models, views urlpatterns = patterns('', (r'^events/$', views.object_list, {'model': models.Event}), (r'^blog/entries/$', views.object_list, {'model': models.BlogEntry}), ) # views.py from django.shortcuts import render_to_response def object_list(request, model): obj_list = model.objects.all() template_name = 'mysite/%s_list.html' % model.__name__.lower() return render_to_response(template_name, {'object_list': obj_list})
View Configuration Options:
def my_view(request, template_name): var = do_something() return render_to_response(template_name, {'var': var}) # default value def my_view(request, template_name='mysite/my_view.html'): var = do_something() return render_to_response(template_name, {'var': var})
Using Default View Arguments
# urls.py from django.conf.urls.defaults import * from mysite import views urlpatterns = patterns('', (r'^blog/$', views.page), (r'^blog/page(?P<num>\d+)/$', views.page), ) # views.py def page(request, num='1'): # Output the appropriate page of blog entries, according to num. # ...
Special-Casing Views
#URLpattern urlpatterns = patterns('', # ... ('^([^/]+)/([^/]+)/add/$', views.add_stage), # ... ) # views.py def add_stage(request, app_label, model_name): if app_label == 'auth' and model_name == 'user': # do special-case code else: # do normal code # more elegant solution: urlpatterns = patterns('', # ... ('^auth/user/add/$', views.user_add_stage), ('^([^/]+)/([^/]+)/add/$', views.add_stage), # ... )
Capturing Text in URLs:
# urls.py from django.conf.urls.defaults import * from mysite import views urlpatterns = patterns('', (r'^articles/(\d{4})/(\d{2})/(\d{2})/$', views.day_archive), ) # views.py import datetime def day_archive(request, year, month, day): date = datetime.date(int(year), int(month), int(day))
Higher-Level Abstractions of View Functions
# views.py from django.http import Http404, HttpResponseRedirect from django.shortcuts import render_to_response # old solution: def method_splitter(request, GET=None, POST=None): if request.method == 'GET' and GET is not None: return GET(request) elif request.method == 'POST' and POST is not None: return POST(request) raise Http404 # better solution: # using pop() with a default value of None to avoid KeyError if one or the other isn’t defined. def method_splitter(request, *args, **kwargs): get_view = kwargs.pop('GET', None) post_view = kwargs.pop('POST', None) if request.method == 'GET' and get_view is not None: return get_view(request, *args, **kwargs) elif request.method == 'POST' and post_view is not None: return post_view(request, *args, **kwargs) raise Http404 def some_page_get(request): assert request.method == 'GET' do_something_for_get() return render_to_response('page.html') def some_page_post(request): assert request.method == 'POST' do_something_for_post() return HttpResponseRedirect('/someurl/') # urls.py from django.conf.urls.defaults import * from mysite import views urlpatterns = patterns('', # ... (r'^somepage/$', views.method_splitter, {'GET': views.some_page_get, 'POST': views.some_page_post}), # ... )
Python function parameter
def foo(*args, **kwargs): print "Positional arguments are:" print args print "Keyword arguments are:" print kwargs foo(1, 2, 3) #Positional arguments are: #(1, 2, 3) #Keyword arguments are: #{} foo(1, 2, name='Adrian', framework='Django') #Positional arguments are: #(1, 2) #Keyword arguments are: #{'framework': 'Django', 'name': 'Adrian'}
Wrapping View Functions:
# urls.py from django.conf.urls.defaults import * from mysite.views import requires_login, my_view1, my_view2, my_view3 urlpatterns = patterns('', (r'^view1/$', requires_login(my_view1)), (r'^view2/$', requires_login(my_view2)), (r'^view3/$', requires_login(my_view3)), ) # views.py def requires_login(view): def new_view(request, *args, **kwargs): if not request.user.is_authenticated(): return HttpResponseRedirect('/accounts/login/') return view(request, *args, **kwargs) return new_view
Including Other URLconfs
from django.conf.urls.defaults import * urlpatterns = patterns('', (r'^weblog/', include('mysite.blog.urls')), (r'^photos/', include('mysite.photos.urls')), (r'^about/$', 'mysite.views.about'), )
引用
There’s an important gotcha here: the regular expressions in this example that point to an include() do not have a $ (end-of-string match character) but do include a trailing slash. Whenever Django encounters include(), it chops off whatever part of the URL matched up to that point and sends the remaining string to the included URLconf for further processing.
How Captured Parameters Work with include():
# root urls.py from django.conf.urls.defaults import * urlpatterns = patterns('', (r'^(?P<username>\w+)/blog/', include('foo.urls.blog')), ) # foo/urls/blog.py from django.conf.urls.defaults import * urlpatterns = patterns('', (r'^$', 'foo.views.blog_index'), (r'^archive/$', 'foo.views.blog_archive'), )
How Extra URLconf Options Work with include()
###example 1: # urls.py from django.conf.urls.defaults import * urlpatterns = patterns('', (r'^blog/', include('inner'), {'blogid': 3}), ) # inner.py from django.conf.urls.defaults import * urlpatterns = patterns('', (r'^archive/$', 'mysite.views.archive'), (r'^about/$', 'mysite.views.about'), (r'^rss/$', 'mysite.views.rss'), ) ### example 2: # urls.py from django.conf.urls.defaults import * urlpatterns = patterns('', (r'^blog/', include('inner')), ) # inner.py from django.conf.urls.defaults import * urlpatterns = patterns('', (r'^archive/$', 'mysite.views.archive', {'blogid': 3}), (r'^about/$', 'mysite.views.about', {'blogid': 3}), (r'^rss/$', 'mysite.views.rss', {'blogid': 3}), )
相关推荐
Chapter 15: Django Templates and Jinja2 Chapter 16: Building REST APIs with Django REST Framework (NEW) Chapter 17: Consuming REST APIs Chapter 18: Tradeoffs of Replacing Core Components Chapter 19: ...
django教程:基本操作笔记整理.png
Django实践:学生管理系统(web网页版)代码
Chapter 2: Django Urls and Views Chapter 3: Django Templates Chapter 4: Jinja Templates in Django Chapter 5: Django Application Management Chapter 6: Django Forms Chapter 7: Django Models Chapter 8: ...
【Django框架基础教程】 Django是一个用Python语言编写的开源Web应用框架,它遵循Model-View-Controller(MVC)的设计模式。Django因其强大的功能和高效性,在Python Web开发领域占据着重要地位,被广泛应用于众多...
给大家分享一套课程——Django+Vue:Python Web全栈开发(基于Django4.1),已完结10章,附源码。
**Django教程:基本操作笔记整理** Django是一款高级的Python Web框架,它鼓励快速开发和清洁、实用的设计。这个教程将带你深入了解Django的基本操作,包括安装、项目创建、应用构建、数据库交互以及视图和模板的...
django:Django框架详解,Django的优缺点.zip django:Django框架详解,Django的优缺点.zip django:Django框架详解,Django的优缺点.zip django:Django框架详解,Django的优缺点.zip django:Django框架详解,...
Python Django Web典型模块开发实战_用Django设计大型电商的类别表_编程项目案例实例详解课程教程.pdf
Python Django Web开发教程 第3课 Django入门基础教程:views 和地址 共9页.pptx
Django:Django高级特性:RESTful API开发.docx
Django:Django高级特性:自定义管理后台.docx
Django:Django实战项目:在线商城系统开发.docx
Django:Django高级特性:WebSocket与实时通信.docx
Python Django Web典型模块开发实战_用Django实现百度开发者认证业务模型_编程项目案例实例详解课程教程.pdf
Along the way you’ll learn core Django features and best practices around models, views, templates, urls, custom user models, permissions, authorizations, user registration, testing, and deployment. ...
6. Django URLs:学习URLconfs,如何定义URL模式,以及如何将URL映射到视图函数。 7. Django Forms:了解如何使用Django表单处理用户输入,包括模型表单、自定义表单以及验证规则。 8. Django中间件:理解中间件的...
TypeError at /add_atr/ add_atr() takes 0 positional arguments but 1 was given Request Method: GET ...Django Version: 3.0.3 Exception Type: TypeError ...Exception Location: E:\env\django9\lib
7. URL路由:Django的URLconfs负责将URL映射到视图函数,使用户能够访问到网站的不同页面。 8. 用户认证和权限:Django提供了内置的用户认证系统,可以处理注册、登录、权限检查等功能,对于后台管理系统尤为重要。...