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

前端 未结 6 1597
后悔当初
后悔当初 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 03:55

    request.user.get_username() or request.user.username, former is preferred.

    Django docs say:

    Since the User model can be swapped out, you should use this method instead of referencing the username attribute directly.

    P.S. For templates, use {{ user.get_username }}

    0 讨论(0)
  • 2020-12-13 04:06

    You can use the request object to find the logged in user

    def my_view(request):
        username = None
        if request.user.is_authenticated():
            username = request.user.username
    

    According to https://docs.djangoproject.com/en/2.0/releases/1.10/

    In version Django 2.0 the syntax has changed to

    request.user.is_authenticated
    
    0 讨论(0)
  • 2020-12-13 04:09

    For classed based views use self.request.user.id

    0 讨论(0)
  • 2020-12-13 04:09

    request.user.get_username() will return a string of the users email.

    request.user.username will return a method.

    0 讨论(0)
  • 2020-12-13 04:12

    'request.user' has the logged in user.
    'request.user.username' will return username of logged in user.

    0 讨论(0)
  • 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
    <form id='formulario' method='POST' action=''>
        <h2>Publica tu tuit, {{ request.user.username.title }} </h2>
        {% csrf_token %}
        {{ formulario.as_p }}
        <p><input type='submit' value='Confirmar' /></p>
    </form>
    
    0 讨论(0)
提交回复
热议问题