Always including the user in the django template context

前端 未结 8 640
一向
一向 2020-12-04 14:22

I am working on a small intranet site for a small company, where user should be able to post. I have imagined a very simple authentication mechanism where people just enter

8条回答
  •  庸人自扰
    2020-12-04 15:10

    @Ryan: Documentation about preprocessors is a bit small

    @Staale: Adding user to the Context every time one is calling the template in view, DRY

    Solution is to use a preprocessor

    A: In your settings add

    TEMPLATE_CONTEXT_PROCESSORS = (
        'myapp.processor_file_name.user',
    )
    

    B: In myapp/processor_file_name.py insert

    def user(request):
        if hasattr(request, 'user'):
            return {'user':request.user }
        return {}
    

    From now on you're able to use user object functionalities in your templates.

    {{ user.get_full_name }}
    

提交回复
热议问题