我有一个页面,其中显示所有用户的帖子,并且用户只能删除其帖子。 代码如下:
class PostDelete(generic.DeleteView):
model = Post
template_name = 'dashboard/post_delete.html'
success_url = reverse_lazy('dashboard:posts')
post_delete.html:
{% extends 'dashboard/sidebar.html' %}
{% block title %}Confirmation{% endblock %}
{% block mainpage %}
<div id="page-wrapper" align="center">
<div id="page-inner">
<h1>New post</h1>
<form method="post">
{% csrf_token %}
Are you sure you want to delete?
<br>
<button class="btn btn-danger">Yes</button>
<a href="{% url 'dashboard:posts' %}" class="btn btn-primary">No</a>
</form>
</div>
</div>
{% endblock %}
Urls.py:
path('delete/<int:pk>',views.PostDelete.as_view(),name='delete'),
如何添加用户验证码? 如果它是一个函数,我会使用“ if request.user.is_authenticated” 但是我不知道如何在课堂上实现这一目标。如果您需要其他代码的摘录,请发表评论。谢谢!
答案 0 :(得分:3)
尝试使用UserPassesTestMixin
:
from django.contrib.auth.mixins import UserPassesTestMixin
class PostDelete(UserPassesTestMixin, generic.DeleteView):
model = Post
template_name = 'dashboard/post_delete.html'
success_url = reverse_lazy('dashboard:posts')
raise_exception = True
def test_func(self):
self.object = self.get_object()
return self.object.user == self.request.user