クラスベースのビューを使用してモデルを更新します。
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
get_context_data
DRY の原則に従い、すべてのビュー関数で繰り返さないようにしたいと考えています。質問はこれとほぼ同じです。@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'])