对于DJANGO如何才能使只有所有者的职位编辑和删除

lxkprmvk  于 2023-03-20  发布在  Go
关注(0)|答案(1)|浏览(118)

对不起,糟糕的英语,我的阿拉伯语和第一个我新来这里,我想知道如何“Django”如何才能使只有业主的职位编辑和删除,谢谢

`class Book(models.Model):
    username = models.ForeignKey(User , on_delete=models.CASCADE)
    title = models.CharField(max_length=40)
    descriptions = models.TextField(blank=True , null=True)
    image = models.ImageField(upload_to='books_pic' , blank=True , null=True , default='images/genericBookCover.jpg')
    bookauthor = models.CharField(max_length=18 , null=True , blank=True)
    downloadlink = models.URLField()
    created = models.DateTimeField(auto_now_add=timezone.now)
    updated = models.DateTimeField(auto_now=True)
    active = models.BooleanField(default=False)
    slug = models.SlugField(null=True , blank=True)`

`def book_edit(request , id):
    update = Book.objects.get(id=id)
    form = AddBookForm(instance=update)
    if request.method == 'POST':
        form = AddBookForm(request.POST or None , request.FILES or None , instance=update)
        if form.is_valid():
            form.save()
            #return redirect('')
    context = {'form':form}
    return render(request , 'pages/edit_book.html' , context)`

`def book_delete(request , id):
    delete = Book.objects.get(id=id)
    if request.method == 'POST':
        delete.delete()
        return redirect('/')
    context = {'delete':delete}
    return render(request , 'pages/delete_book.html' , context)`
7d7tgy0s

7d7tgy0s1#

您总是可以考虑创建一个定制的装饰器,但这是一种快速而又不方便的方法

def book_edit(request , id):
    update = Book.objects.get(id=id)

    if request.user != update.username:
        # User Object doesn't match, redirect to Permission Denied page
        from django.core.exceptions import PermissionDenied
        raise PermissionDenied()

    form = AddBookForm(instance=update)
    if request.method == 'POST':
        form = AddBookForm(request.POST or None , request.FILES or None , instance=update)
        if form.is_valid():
            form.save()
            #return redirect('')
    context = {'form':form}
    return render(request , 'pages/edit_book.html' , context)`

潮汐位:Book.username实际上存储的是用户的PK/id/row_num,而不是用户名。所以当你比较的时候,就像上面一样,Django是在比较PK--它本质上就是User对象本身
无关建议

  • 将视图的参数从id中去掉,因为这是Python中的一个保留字,会让Linters很生气,请尝试pkrow_num
  • update|delete = Book.objects.get(id=id)改为book_obj =/bookObj =将使其更加一致
  • 请使用get_obj_or_404()而不是.get(id=id),这样在找不到它的情况下也不会崩溃!
from django.shortcuts import get_object_or_404
book_obj = get_object_or_404(Book, id=pk)

相关问题