在用户删除了PieceInstance之后,我想将他重定向到PieceInstance所属的Piece。我使用默认的DeleteView,并希望将部件ID(通过ForeignKey引用的PieceInstance的部件)传递给get_success_url方法。 self.piece.pk
似乎没有获得相应作品的ID。
models.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')
答案 0 :(得分:2)
根据源代码,对象被删除之前存储在self.object
中。因此,您可以使用以下命令重定向到相关piece
的主键:
class PieceInstanceDelete(LoginRequiredMixin, DeleteView):
model = PieceInstance
def get_success_url(self):
return reverse_lazy('piece-detail', kwargs={'pk': self.object.piece_id})
但是问题是这是 undocumented ,因此以后可能会重写Django视图而没有这种行为。
万一这种行为不再发生,可能值得修补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):
self.object = self.get_object()
super().delete(*args, **kwargs)
def get_success_url(self):
return reverse_lazy('piece-detail', kwargs={'pk': self.object.piece_id})
答案 1 :(得分:1)
使用以下答案得到它: DeleteView with a dynamic success_url dependent on id
此处为DeleteView类:
class PieceInstanceDelete(LoginRequiredMixin, DeleteView):
model = PieceInstance
def get_success_url(self):
piece = self.object.piece
return reverse_lazy('piece-detail', kwargs={'pk': piece.pk})