Karen Galstyan
Karen Galstyan

Reputation: 149

How to use mixins properly

Please, help to understand, why the following doesn't work for me. So, I need display information on a page from logged in user. In order not to retype code in every view I decided to create a mixin.

class MyMixin(object):
  def my_view(self):
    args = {}
    args['username'] = auth.get_user(request).username
    args['first_name'] = auth.get_user(request).first_name
    args['last_name'] = auth.get_user(request).last_name
    return args

class someview (TemplateView, LoginRequiredMixin, MyMixin):
  template_name = 'index.html

But this doesn't show anything in a template.

{{ first_name }}

Upvotes: 2

Views: 49

Answers (1)

YPCrumble
YPCrumble

Reputation: 28692

There are at least two ways of getting these "context variables" into your template:

  1. Your TemplateView already includes ContextMixin. So you could simply override ContextMixin's get_context_data method for that view, like this:

    class someview (TemplateView, LoginRequiredMixin):
        template_name = 'index.html
    
        def get_context_data(self, **kwargs):
            context = super(someview, self).get_context_data(**kwargs)
            context['username'] = self.request.user.username
            context['first_name'] = self.request.user.first_name
            context['last_name'] = self.request.user.last_name
            return context
    
  2. It seems that what you're actually looking for is a more DRY method, not necessarily a mixin. In that case, you should use write your own context_processor:

    context_processors.py:

    def extra_context(request):                                                         
        args = {}
        args['username'] = auth.get_user(request).username
        args['first_name'] = auth.get_user(request).first_name
        args['last_name'] = auth.get_user(request).last_name
        return args
    

    settings.py:

    TEMPLATE_CONTEXT_PROCESSORS += (your_app.context_processors.extra_context,)
    

    This second method will add these three context variables to every template in your app.

Upvotes: 1

Related Questions