gpt4 book ai didi

django - 在 Django 2.0 中如何处理 generic.DeleteView 中的 ProtectedError

转载 作者:行者123 更新时间:2023-12-02 20:30:18 24 4
gpt4 key购买 nike

我有一个通用 View 声明如下:

class CustomerDelete(LoginRequiredMixin,DeleteView):

model = models.Customer
success_url = reverse_lazy('customer-list')

和一个声明如下的模型:

class Order(models.Model):

Customer = models.ForeignKey(Customer, on_delete=models.PROTECT, default=None)
Shop = models.ForeignKey(Shop, on_delete=models.PROTECT, default=None)
Status = models.IntegerField(choices=STATUS);
Reference = models.CharField(max_length=50)
Date = models.DateTimeField(default=None)
LastAuthorizationDate = models.DateTimeField(default=None, null=True)
LastUpdated = models.DateTimeField(auto_now=True)
def get_absolute_url(self):
return reverse_lazy('order-view', None, [self.id])

def type(self):
return 'Order'

def Name(self):
return self.Customer.Name + ' - ' + self.Shop.Name + ' - ' + self.Reference

删除后出现以下异常:

ProtectedError at /customer/2/delete/ ("Cannot delete some instances of model 'Customer' because they are referenced through a protected foreign key: 'Order.Customer'", , , , , ]>)

什么是最好的类方法来覆盖和捕获允许我重定向到附加错误的引荐来源网址的异常?

提前致谢。

最佳答案

您需要覆盖delete 方法,以添加您的自定义逻辑:

class CustomerDelete(LoginRequiredMixin,DeleteView):

model = models.Customer
success_url = reverse_lazy('customer-list')
error_url = reverse_lazy('customer-has-orders-error')

def get_error_url(self):
if self.error_url:
return self.error_url.format(**self.object.__dict__)
else:
raise ImproperlyConfigured(
"No error URL to redirect to. Provide a error_url.")

def delete(self, request, *args, **kwargs):
"""
Call the delete() method on the fetched object and then redirect.
"""
self.object = self.get_object()
success_url = self.get_success_url()
error_url = self.get_error_url()
try:
self.object.delete()
return HttpResponseRedirect(success_url)
except models.ProtectedError:
return HttpResponseRedirect(error_url)

如果您打算经常使用它,您可以使用上述逻辑创建您自己的自定义 mixin。

此外,考虑在您的应用程序中实现软删除,这样记录就不会立即从数据库中删除,而是被标记为稍后删除 - 一旦它们被归档。否则,您的业务逻辑可能会出现问题。

关于django - 在 Django 2.0 中如何处理 generic.DeleteView 中的 ProtectedError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48981748/

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