什么时候使用FBVs或者CBVs?
Keep view Logic out of URLconfs# Similar to the Polls example from django.conf.urls import patterns, url from django.views.generic import DetailView from tastings.models import Tasting urlpatterns = patterns('', url(r'^(?P<pk>\d+)/$', DetailView.as_view( model=Tasting, template_name='tastings/detail.html'), name='detail'), url(r'^(?P<pk>\d+)/results/$', DetailView.as_view( model=Tasting, template_name='tastings/results.html'), name='results'), )
# tastings/views.py from django.views.generic import DetailView from .models import Tasting class TasteDetailView(DetailView): model = Tasting class TasteResultsView(TasteDetailView): template_name = 'tastetests/results.html'
# tastings/urls.py from django.conf.urls import patterns, url from .views import TastingDetailView, TastingResultsView urlpatterns = patterns('', url( regex=r'^(?P<pk>\d+)/$', view=TastingDetailView.as_view(), name='detail' ), url( regex=r'^(?P<pk>\d+)/results/$', view=TastingResultsView.as_view(), name='results' ), )好处:DRY,松耦合原则等
from django.views.generic import TemplateView class FreshFruitMixin(object): def get_context_data(self, **kwargs): context = super(FreshFruitMixin, self).get_context_data(**kwargs) context["has_fresh_fruit"] = True return context class FruityFlavorView(FreshFruitMixin, TemplateView): template_name = "fruity_flavor.html"
django.views.generic?是什么??
声明:图片和代码均引用自 《two-scoops-django-best-practics》