Django generic views

Category: /knowledge /django
Tags: django

我个人觉得Django里的generic views和generic field是其最大亮点. 这两个特点很好地诠释了Django的原则–“make easy things easier, make hard things possible”. 在官方的Topic guideReference里有很好的解释, 还有一个migration的帮助文档.

Tutorial part 4 部分有例子说明ListViewDetailView. 但关于create/update/delete views的文档说明却很少. 还有一个问题是我还不理解Class-based generic views比function-based generic views好在哪里.

这个slide解释了一些

StackOverflow也有讨论, 总结一下就是单写一view/template不省时间和代码, 当给不同template传不同参数时, 通过subclass可以使代码更加清晰和短小.

Built-in views

django.views.generic.base.TemplateView
django.views.generic.base.RedirectView
django.views.generic.list.ListView
django.views.generic.detail.DetailView
django.views.generic.edit.CreateView
django.views.generic.edit.UpdateView
django.views.generic.edit.DeleteView
django.views.generic.dates.ArchiveIndexView
django.views.generic.dates.YearArchiveView
django.views.generic.dates.MonthArchiveView
django.views.generic.dates.WeekArchiveView
django.views.generic.dates.DayArchiveView
django.views.generic.dates.TodayArchiveView
django.views.generic.dates.DateDetailView

How to access parameters in URL

in urls.py, 
(r'^categories/(\w+)/P<pk>/$', CategoryListView.as_view()),

then, in views.py, get the parameters such as 
self.kwargs['pk'] and self.args[0]
 
for request.user
self.request.user

How to add decorator

in urls.py

from django.contrib.auth.decorators import login_required
from django.views.generic import TemplateView

urlpatterns = patterns('',
    (r'^about/',login_required(TemplateView.as_view(template_name="secret.html"))),
)

in class view definition

from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.views.generic import TemplateView

class ProtectedView(TemplateView):
    template_name = 'secret.html'

    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
        return super(ProtectedView, self).dispatch(*args, **kwargs)

work on as_view(),

from django.contrib.auth.decorators import login_required
from django.utils.decorators import classonlymethod
from django.views.generic import TemplateView

class ProtectedView(TemplateView):

    @classonlymethod
    def as_view(cls, **initargs):
        return login_required(super(ProtectedView, cls).as_view(**initargs))

also, try view_decorator(), source code

How to add extra content

  • self.object is the instance in DetailView.
  • self.object_list is the instance in ListView.
  • Use self.kwargs['key_string'] to get parameters in URL.
  • To add extra contect to templates,

     class SongDetailView(DetailView):
       model=Song
       def get_context_data(self, **kwargs):
         context = super(DetailView, self).get_context_data(**kwargs)
         context['tags'] = Tag.objects.get_for_object(self.object)
         return context
    

Related blogs

关于每个类的小抄

讨论

提示

  • 如果看不到讨论部分, 请暂时关掉adblock in Firefox/Chrome
  • 本网站使用Javascript实现评论功能, 此处外链对提高您的网站PR没有帮助. (潜台词: 请不要灌水, 谢谢)