How can I get the username of the logged-in user in Django?

前端 未结 6 1614
后悔当初
后悔当初 2020-12-13 03:45

How can I get information about the logged-in user in a Django application?

For example:

I need to know the username of the logged-in user to say who posted

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-13 04:12

    if you are using the old way of writting views, in the way of Function-Based-Views...

    in your view, you are creating a new variable called usuario to save the request.user probably...

    but if you returning to the Template a context_instance, passing the value of the Context of the request, you will get the logged user, just by accessing the request.

    // In your views file
    from django.shortcuts import render_to_response
    from django.template import RequestContext
    def your_view(request):
        data = {
            'formulario': Formulario()
            # ...
        }
        return render_to_response('your_template.html',
            data, context_instance=RequestContext(request))
    
    
    // In your template
    

    Publica tu tuit, {{ request.user.username.title }}

    {% csrf_token %} {{ formulario.as_p }}

提交回复
热议问题