Django - 消息功能在基于 Class 的视图中不起作用

Django - Messages functionality not working in Class based view

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

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 方法似乎是个好地方

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