Django - Messages functionality not working in Class based view

十年热恋 提交于 2021-02-11 14:02:43

问题


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 %}

回答1:


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


来源:https://stackoverflow.com/questions/62500284/django-messages-functionality-not-working-in-class-based-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!