0

クラスベースのビューを使用してモデルを更新します。

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_dataDRY の原則に従い、すべてのビュー関数で繰り返さないようにしたいと考えています。質問はこれとほぼ同じです。@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'])
4

1 に答える 1

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)コンテキストがオブジェクトになります。


まず、ミックスインをクラス コンストラクターに追加します。

ご覧のとおり、次のとおりです。

class BlogUpdateView(BlogMixin, UpdateView):

これで、ベースはBlogMixin mixin からdef get_context_data(self, **kwargs):オーバーライドされます。def get_context_data(self, **kwargs):

しかし、あなたはあなたにもaを指定def get_context_data(self, **kwargs):してclass BlogUpdateView(UpdateView):おり、最終的にはこれがget_context_data有効になります。

ミックスインは、コツをつかむのが難しいです。他の人の例を見て学ぶのが一番だと思います。こちらをご覧ください

編集:おそらくあなたの質問に適切に答えていないことに気づきました。ミックスイン内のオブジェクトにアクセスしたい場合は、それを渡す必要があります。たとえば、コンテキスト オブジェクトをミックスインに渡します。

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)

コードはテストされていませんが、アイデアは正しいはずです

于 2012-06-28T12:10:37.830 に答える