Django登录名重定向到登录页面

时间:2020-04-24 18:45:35

标签: django django-views django-templates

在开发过程中,我可以登录和注销。但是在生产中,我遇到了一些麻烦。当我登录页面时,只是重新加载。

我已将其设置为登录后重定向到主页,而我所需要的只是以下内容:

urls.py

urlpatterns = [
    path("", include('main.urls')),
    path('admin/', admin.site.urls),
    path('accounts/', include('django.contrib.auth.urls')), # For /accounts/login page
]  + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

templates / registration / login.html

{% extends "base.html" %}

{% block content %}

<div class="container">
 <div class="card">

    {% if form.errors %}
    <p>Your username and password didn't match. Please try again.</p>
    {% endif %}

    {% if next %}
    {% if user.is_authenticated %}
    <p>Your account doesn't have access to this page. To proceed,
      please login with an account that has access.</p>
    {% else %}
    <p>Please login to see this page.</p>
    {% endif %}
    {% endif %}

    <form method="post" action="{% url 'login' %}">
      {% csrf_token %}
      {{ form|crispy }}
      <button type="submit" class="btn btn-success"><i class="fas fa-sign-in-alt"></i> Login</button>
      <input type="hidden" name="next" value="{{ next }}" />
    </form>

    {# Assumes you setup the password_reset view in your URLconf #}
    <p><a href="{% url 'password_reset' %}">Lost password?</a></p>
</div>
</div>

{% endblock content %}

1 个答案:

答案 0 :(得分:0)

我做这样的事情,它在生产中为我服务很好,您不需要在前端而是在视图中进行任何与用户身份验证相关的更改。

class LoginView(FormView):
    form_class = SignInForm
    success_url = 'userhome'
    template_name = 'users/signin.html'

    def form_valid(self, form):
        request = self.request
        next_ = request.GET.get('next')
        next_post = request.POST.get('next')
        redirect_path = next_ or next_post or None
        email = form.cleaned_data.get("email")
        password = form.cleaned_data.get("password")
        user = authenticate(request, username=email, password=password)
        if user is not None:
            login(request, user)
            try:
                del request.session['guest_email_id']
            except:
                pass
            if is_safe_url(redirect_path, request.get_host()):
                return redirect(redirect_path)
            else:
                return redirect("userhome")
        return super(LoginView, self).form_invalid(form)