对不起,糟糕的英语,我的阿拉伯语和第一个我新来这里,我想知道如何“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)`
1条答案
按热度按时间7d7tgy0s1#
您总是可以考虑创建一个定制的装饰器,但这是一种快速而又不方便的方法
潮汐位:Book.username实际上存储的是用户的PK/id/row_num,而不是用户名。所以当你比较的时候,就像上面一样,Django是在比较PK--它本质上就是
User
对象本身无关建议:
id
中去掉,因为这是Python中的一个保留字,会让Linters很生气,请尝试pk
或row_num
update|delete = Book.objects.get(id=id)
改为book_obj =
/bookObj =
将使其更加一致get_obj_or_404()
而不是.get(id=id)
,这样在找不到它的情况下也不会崩溃!