我使用基于类的视图来更新我的模型:
class BlogUpdateView(UpdateView):
model=Blog
def get_context_data(self, **kwargs):
context = super(BlogUpdateView, self).get_context_data(**kwargs)
context['author'] = get_object_or_404(User,
username__iexact=self.kwargs['username'])
return context
我想遵循DRY原则,避免在每个视图函数中重复get_context_data
。问题与this one几乎相同。依靠@Jj给出的答案,我想我的班级看起来像这样:
class BlogMixin(object):
def get_author(self):
# How to get author?
return author
def get_context_data(self, **kwargs):
context = super(BlogMixin, self).get_context_data(**kwargs)
context['author'] = self.get_author()
return context
我的问题是:如何在mixin类中访问对象?
更新
mongoose_za评论中给出了答案。我可以通过这一行获得作者:
author = User.objects.get(username__iexact=self.kwargs['username'])
答案 0 :(得分:1)
你的遗嘱会出现这样的事情:
class BlogMixin(object):
def get_author(self):
# How to get author?
# Assuming user is logged in. If not you must create him
author = self.request.user
return author
class BlogUpdateView(BlogMixin, UpdateView):
model=Blog
def get_context_data(self, **kwargs):
context = super(BlogUpdateView, self).get_context_data(**kwargs)
context['author'] = self.get_author()
return context
当您执行context = super(BlogUpdateView, self).get_context_data(**kwargs)
时,上下文将成为您的对象。
首先,将mixin添加到类构造函数中。
如你所见:
class BlogUpdateView(BlogMixin, UpdateView):
现在,您的def get_context_data(self, **kwargs):
将从BlogMixin mixin中覆盖基础def get_context_data(self, **kwargs):
。
但您还在def get_context_data(self, **kwargs):
中指定了class BlogUpdateView(UpdateView):
,最后这将是get_context_data
生效。
编辑:意识到也许我没有正确回答你的问题。如果你想访问mixin中的对象,你必须将其传入。例如,我将上下文对象传递给mixin:
class BlogMixin(object):
def get_author(self, context):
# This is how to get author object
author = User.objects.get(username__iexact=self.kwargs['username'])
return context
class BlogUpdateView(BlogMixin, UpdateView):
model=Blog
def get_context_data(self, **kwargs):
context = super(BlogUpdateView, self).get_context_data(**kwargs)
return self.get_author(context)
代码未经过测试,但想法应该是正确的