开发者

How to pass the logged in user to direct_to_template?

开发者 https://www.devze.com 2023-02-05 07:59 出处:网络
I\'m using direct_to_template for a 开发者_StackOverflow社区url but I need the logged in user to display the page. How do I pass it to direct_to_template?If your TEMPLATE_CONTEXT_PROCESSORS variable i

I'm using direct_to_template for a 开发者_StackOverflow社区url but I need the logged in user to display the page. How do I pass it to direct_to_template?


If your TEMPLATE_CONTEXT_PROCESSORS variable in settings.py is set to include 'django.contrib.auth.context_processors.auth', it will already be on the page context. (This is configured by default).

The direct_to_template generic view uses RequestContext, so there will be a context variable called user that will provide the currently logged in user (or an AnonymousUser if there is no logged in user).

For example, to display the username in your template: {{ user.username }}.

For more details see the django docs on the auth context processor.


put following in your login view before GET method

def custom_proc(request):

        return {
            'app': 'myapp',
            'user': request.user,
            'ip_address': request.META['REMOTE_ADDR']
        }

in login view in post

......some code here......

return render(request, 'html file name',
              context_instance=RequestContext(request,processors=custom_proc]))

in setting.py

TEMPLATE_CONTEXT_PROCESSORS = (                         'django.contrib.auth.context_processors.auth',
'django.core.context_processors.request',
)

and in html file

Hello, username = {{ user.username }} id ={{ user.id }}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号