2👍
Your will land up something like this:
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
When you do context = super(BlogUpdateView, self).get_context_data(**kwargs)
then context will be your object.
First you add your mixin into the class constructor.
As you see here:
class BlogUpdateView(BlogMixin, UpdateView):
Now the base def get_context_data(self, **kwargs):
will be overridden by your def get_context_data(self, **kwargs):
from the BlogMixin mixin.
BUT you have also specified a def get_context_data(self, **kwargs):
in your class BlogUpdateView(UpdateView):
and in the end this is the get_context_data
that will take effect.
Mixins are tricky to get the hang of. I feel it’s best to learn by viewing other peoples examples. Take a look here
Edit: Realised that perhaps I didn’t answer your question properly. If you want to have access to an object within your mixin you have to pass it in. For example I’ll pass the context object to the 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)
The code isn’t tested but the idea should be right