首页 > 解决方案 > Django - 成功消息混合在登录时不起作用

问题描述

我正在尝试使用 SuccessMessageMixin 在登录时显示成功消息,但未显示该消息。有什么理由会发生这种情况吗?

设置.py

LOGIN_REDIRECT_URL = 'home'
LOGIN_URL = 'login'

LOGOUT_REDIRECT_URL = 'home'
LOGOUT_URL = 'logout'

网址.py

from .views import HomeView, LoginFormView

urlpatterns = [
    path('admin/', admin.site.urls),
    path('home/', HomeView.as_view(), name = 'home'),
    path('login/', LoginFormView.as_view(), name = 'login'),
]

视图.py

class HomeView(FormView):
    template_name = 'home.html'

class LoginFormView(auth_views.LoginView, SuccessMessageMixin):
    template_name = 'login.html'
    success_url = 'home/'
    success_message = "You were successfully logged in."

登录.html

<h4>Login to your Account:</h4>
<div>
    <form action "" method = "POST">
        {% csrf_token %}
        {{form}}
        <button type = "submit">Login</button>
    </form>
</div>

主页.html

{% if messages %}
        {% for message in messages %}
            {{ message }}
        {% endfor %}
{% endif %}

标签: htmldjango

解决方案


SuccessMessageMixin需要在继承顺序中首先(或至少在通用视图之前),即它应该LoginFormView(SuccessMessageMixin, auth_views.LoginView)代替LoginFormView(auth_views.LoginView, SuccessMessageMixin)

class LoginFormView(SuccessMessageMixin, auth_views.LoginView):
    template_name = 'login.html'
    success_url = 'home/'
    success_message = "You were successfully logged in."

推荐阅读