Putting a django login form on every page

后端 未结 4 925
执念已碎
执念已碎 2020-11-27 11:35

I\'d like the login form (AuthenticationForm from django.contrib.auth) to appear on every page in my site if the user is not logged in. When the user logs in, they will be r

4条回答
  •  遥遥无期
    2020-11-27 12:03

    Based on the answer of asciitaxi, i use these Middleware Classes to to login and logout:

    class LoginFormMiddleware(object):
        def process_request(self, request):
            from django.contrib.auth.forms import AuthenticationForm
            if request.method == 'POST' and request.POST.has_key('base-account') and request.POST['base-account'] == 'Login':
                form = AuthenticationForm(data=request.POST, prefix="login")
                if form.is_valid():
                    from django.contrib.auth import login
                    login(request, form.get_user())
                request.method = 'GET'
            else:
                form = AuthenticationForm(request, prefix="login")
            request.login_form = form
    
    class LogoutFormMiddleware(object):
        def process_request(self, request):
            if request.method == 'POST' and request.POST.has_key('base-account') and request.POST['base-account'] == 'Logout':
                from django.contrib.auth import logout
                logout(request)
                request.method = 'GET'
    

    An this in my base template:

    {% if not request.user.is_authenticated %}
        
    {% csrf_token %}

    {{ request.login_form.non_field_errors }} {% for field in request.login_form %} {{ field.errors }} {{ field.label_tag}}: {{ field }} {% endfor %}

    {% else %}
    {% csrf_token %}

    Logged in as {{ request.user.username }}.

    {% endif %}

    Remarks:

    • The request.method = 'GET' lines are needed for sites with other forms. Seems a little but akward, but it works fine.
    • Since this is displayed on every page, i don't need the the logout special case any more, because i simply don't need a separate logout page
    • I need some distinction of my login/logout form BEFORE checking if its valid (thus calling the AuthenticationForm Class. Otherwise, there will be errors when it comes to pages with more forms. Therfore, i use the value of the Submit Button to pick out the relevant cases

提交回复
热议问题