问题
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