Django-消息功能在基于类的视图中不起作用 [英] Django - Messages functionality not working in Class based view

查看:42
本文介绍了Django-消息功能在基于类的视图中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

无法在基于类的视图中显示消息.在另一个应用程序的views.py中,在我使用基于函数的视图的地方它可以正常工作.

Unable to display messages in class based view. In another app's views.py, it is working fine where I used function based view.

views.py:

class PostDeleteView(LoginRequiredMixin, UserPassesTestMixin, SuccessMessageMixin, DeleteView):
        model = Post
        success_url = '/user-profile/'
        success_message = "Your post has been deleted sucessfully!"
    
        def test_func(self):
            post = self.get_object()
            if self.request.user == post.author:
                return True
            return False
            

urls.py:

path('user-profile/', user_views.user_profile, name='user_profile'),

html:

{% if messages %}
        {% for message in messages %}
        <div class="alert alert-{{ message.tags }}">
            {{ message }}
        </div>
        {% endfor %}
{% endif %}

推荐答案

DeleteView 不继承 FormView 的子类,因此 SuccessMessageMixin 不会做任何事情.您将需要自己添加消息,覆盖 delete 方法似乎是个好地方

DeleteView does not subclass FormView so SuccessMessageMixin will not do anything. You will have to add the message yourself, overriding the delete method seems like a good place

def delete(self, request, *args, **kwargs):
    response = super().delete(request, *args, **kwargs)
    messages.success(self.request, 'Your post has been deleted sucessfully!')
    return response

这篇关于Django-消息功能在基于类的视图中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆