如何让用户只删除他们在Django中创建的对象?

时间:2017-07-06 18:44:37

标签: python django

他们可以通过发布帖子ID来绕过链接。我不知道如何解决它。

/ borrar / ID

模板按钮:

{% if user == post.user %}
    <a class="close pull-right" href="{% url 'post_borrar' post.id %}"><span aria-hidden="true">&times;</span></a>
{% endif %}

模板帖子/ posts_mod_borrar.html:

<form method="post">
    {% csrf_token %}
    ¿Estás seguro que deseas borrar el post "{{ object }}"?
    <input type="submit" value="Submit" />
</form>

views.py

class PostDeleteView(generic.DeleteView):
    model = Post
    template_name = 'posts/posts_mod_borrar.html'
    success_url = reverse_lazy('timeline')

model.py

class Post(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    texto = models.CharField(max_length=200)
    imagen = models.ImageField(upload_to='posts', blank=True)
    video = models.URLField(blank=True)
    creado = models.DateTimeField(auto_now_add=True)
    actualizado = models.DateTimeField(auto_now=True)

class Meta:
    ordering = ["-creado"]

def __str__(self):
    return self.texto

1 个答案:

答案 0 :(得分:3)

您可以obj.user方法检查request.user是否为dispatch

from django.core.exceptions import PermissionDenied

class PostDeleteView(generic.DeleteView):
    ...

    def user_passes_test(self, request):
        if request.user.is_authenticated():
            self.object = self.get_object()
            return self.object.user == request.user
        return False

    def dispatch(self, request, *args, **kwargs):
        if not self.user_passes_test(request):
            raise PermissionDenied
        return super(PostDeleteView, self).dispatch(
            request, *args, **kwargs)

如果用户未通过user_passes_test PermissionDenied将被提出