0

I am trying to make a custom middleware class that will check token from cookie with another data (not the point where this data is) and return username or some error.

I guess it should be done in process_request method, but how to give this username further to process_view method?

In my template I want to use smth like this:

{% if logged_in then _show_username else _show_loginform_ %}
massive_dynamic
  • 336
  • 3
  • 5
  • 15
  • If you want to just check in the template whether a user is logged in or not, you may use: {% if user.is_authenticated %} your_code_for_showing_username {% else %} your_code_for_login_form {% endif %} – Yaaaaaaaaaaay Jan 24 '16 at 13:10
  • @Yaaaaaaaaaaaay i guess it works only with session auth process, I am using token instead. Am I wrong? – massive_dynamic Jan 24 '16 at 13:18
  • Yep, it works only with the Django's authetication process. But if you want to still use your own token there would be a conflict with the DRY (don't repeat yourself) concept... – Yaaaaaaaaaaay Jan 24 '16 at 15:16

1 Answers1

1

You can just do the same thing as the standard auth middleware; add the user object to the request.

def process_request(self, requess):
    username = <...get from token...>
    request.username = username

Now you can access it from the template via {{ request.username }} (assuming you've enabled the request context processor).

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • I've tried adding such thin + TEMPLATE_CONTEXT_PROCESSORS = ( 'django.core.context_processors.request', ) But still I get an error while trying to access username in template. What do I have to {% load ... %}? – massive_dynamic Jan 24 '16 at 14:00
  • sorry, i overlooked some typo in my template. now it works, thanks a lot! solved my problem :-) – massive_dynamic Jan 24 '16 at 14:10