2015-12-29 59 views
2

我有许多意见,每次调用相同的函数,我想知道在我继续这种方法之前,如果无论如何我可以使它更干。Django如何写DRY视图

例如,我在网站上有许多页面,在左侧菜单上有相同文章和照片的列表。因此,每个我的意见我执行以下操作:

context_dict = {'articles': get_articles(blogger.id), 'photos': get_photos(blogger.id)} 

return render_to_response('...', context_dict, context) 

它必须存在,我没有,因为他们被要求在网页的90%,每次重复自己的一种方式。

+0

看看“上下文处理器”和“中间件” – Sayse

+0

这些选项的问题是我需要传递blogger_id并且它在请求中不可用。 – Yannick

+1

它来自你已经显示的代码的来源? – Sayse

回答

1

你的意思是这样

def get_extra_context(blog_id): 
    return {'articles': get_articles(blogger.id), 'photos': get_photos(blogger.id)} 

的调用get_extra_context在过程的每一个观点作出。

2

重复查看功能的问题是为什么许多人喜欢基于类的视图的一部分。您可以实现一种方法,将这些变量添加到基类,然后让其他视图继承该基类,或提供标准的“渲染”方法。例如:

class BaseView(View): 
    template = 'public/base_template.html' 

    def get(self, *args, **options): 
     return render_to_response(self.template, self.render_view()) 

    def render_view(self, *args, **options): 
     context = {"photos": Photo.objects.all()} 
     return context 

class OtherView(BaseView): 
    template = 'public/other_template.html' 

    def render_view(self, *args, **options): 
     context = super(OtherView, self).render_view(*args, **options) 
     context['additional_context'] = True 
     return context 

...或类似的东西。然后,您不必担心使用已包含的变量调用渲染。

我能想到的一些方法与基于函数的观点来做到这一点,但我觉得基于类的借自己很好地DRY原则,所以我想我传福音:)

https://docs.djangoproject.com/en/1.9/topics/class-based-views/intro/

1

正如Robert Townley所说,基于类的视图对于遵循DRY原则非常有帮助。我经常使用一些简单的mixin在不同视图之间共享一些逻辑。如果他们需要这个功能,那么你的基于类的视图可以继承自这个mixin。例如:

class BloggerMixin(object): 
    articles_context_name = 'articles' 
    photos_context_name = 'photos' 

    def get_blogger(self): 
     """ I'm just assumming your blogger is the current user for simplicity.  
     (And I'm assuming they're logged in already)""" 
     return self.request.user 

    def get_articles(self): 
     return Article.objects.filter(blogger=self.get_blogger()) 

    def get_photos(self): 
     return Photo.objects.filter(blogger=self.get_blogger()) 

    def get_context_data(self, **kwargs): 
     context = super(BloggerMixin, self).get_context_data(**kwargs) 
     context[self.articles_context_name] = self.get_articles() 
     context[self.photos_context_name] = self.get_photos() 
     return context 

这将让你继承就需要它基于类的观点这个额外的功能:

class ExampleView(BloggerMixin, ListView): 
    model = SomeOtherModel 

我们很简单ExampleView类现在将有文章,照片和SomeOtherModel列表在其上下文中。