Reputation: 477
I have two simple class based generic views which simply render a template. Since they look almost the same and I want to stay dry I wanted to ask you, what would be the smartest and best way to implement this right now:
First View
class Foo(TemplateView):
template_name = "Foo.html"
def get_context_data(self, **kwargs):
user = User.objects.get(username = self.request.user)
context = super(Foo, self).get_context_data(**kwargs)
context['foo_objs'] = Foo.objects.filter(user = user.id)
return context
class Bar(TemplateView):
template_name = "bar.html"
def get_context_data(self, **kwargs):
user = User.objects.get(username = self.request.user)
context = super(Bar, self).get_context_data(**kwargs)
context['bar_objs'] = Bar.objects.filter(user = user.id)
return context
Upvotes: 0
Views: 75
Reputation: 45595
Create intermediate view class with additional attribute model
and then inherit your views from it:
class ModelListTemplateView(TemplateView):
model = None
def get_template_names(self):
return [self.model._meta.model_name + '.html']
def get_context_data(self, **kwargs):
context = super(ModelListTemplateView, self).get_context_data(**kwargs)
user = User.objects.get(username=self.request.user)
context['%s_objs' % self.model._meta.model_name] = \
self.model.objects.filter(user=user.id)
return context
class FooView(ModelListTemplateView):
model = Foo
class BarView(ModelListTemplateView):
model = Bar
Upvotes: 2