django - How to use mixins properly -


please, understand, why following doesn't work me. so, need display information on page logged in user. in order not retype code in every view decided create 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 doesn't show in template.

{{ first_name }} 

there @ least 2 ways of getting these "context variables" template:

  1. your templateview includes contextmixin. override contextmixin's get_context_data method view, 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 you're looking more dry method, not mixin. in case, should use write 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 add these 3 context variables every template in app.


Comments

Popular posts from this blog

yii2 - Yii 2 Running a Cron in the basic template -

asp.net - 'System.Web.HttpContext' does not contain a definition for 'GetOwinContext' Mystery -

mercurial graft feature, can it copy? -