gpt4 book ai didi

python - Django:DeleteView 将外键模型中的参数传递给 get_success_url

转载 作者:太空宇宙 更新时间:2023-11-04 09:40:04 24 4
gpt4 key购买 nike

在用户删除一个 PieceInstance 后,我想将他重定向到 PieceInstance 所属的 Piece。我使用默认的 DeleteView 并希望将 Piece id(通过 ForeignKey 引用的 PieceInstance 的 Piece)传递给 get_success_url 方法。 self.piece.pk 好像没有获取到对应Piece的id。

模型.py

class PieceInstance(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text='Unique ID for this particular Piece across whole system')
piece = models.ForeignKey('Piece', on_delete=models.SET_NULL, null=True)
...

class Piece(models.Model):
title = models.CharField(max_length=200)
...

views.py

class PieceInstanceDelete(LoginRequiredMixin, DeleteView):
model = PieceInstance
def get_success_url(self):
return reverse_lazy('piece-detail', kwargs={'pk': self.piece.pk})

urls.py

path('piece/<int:pk>', views.PieceDetailView.as_view(), name='piece-detail')

最佳答案

根据源代码,对象在被删除之前存储在 self.object 中。因此,您可以重定向到相关 piece 的主键:

class PieceInstanceDelete(LoginRequiredMixin, DeleteView):
model = PieceInstance

def get_success_url(self):
return reverse_lazy('piece-detail', kwargs={'pk': <b>self.object.piece_id</b>})

然而,问题是这是未记录的,因此 Django View 稍后可能会在没有此类行为的情况下被重写。

如果此行为不再发生,可能值得修补 delete 函数:

#  probably not necessary, but there is no "contract" that the above will
# always work

class PieceInstanceDelete(LoginRequiredMixin, DeleteView):
model = PieceInstance

def delete(self, *args, **kwargs):
<b>self.object = self.get_object()</b>
super().delete(*args, **kwargs)

def get_success_url(self):
return reverse_lazy('piece-detail', kwargs={'pk': self.object.piece_id})

关于python - Django:DeleteView 将外键模型中的参数传递给 get_success_url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52065046/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com