我遵循了有关CBV的spapas教程,并尝试将mixin应用于创建视图。但是看起来它无法正确评估用户外键的if。form.invoice.requester,因为它始终显示:RelatedObjectDoesNotExist,它指向在 if 行中评估的字段。>
有什么问题吗?
class AuditableMixin(object, ):
def form_valid(self, form, ):
if not form.instance.requester:
form.instance.requester = self.request.user
form.instance.modified_by = self.request.user
return super().form_valid(form)
class NewOrderView(LoginRequiredMixin, PermissionRequiredMixin, AuditableMixin, generic.CreateView):
permission_required = 'orders.add_order'
form_class = NewOrderForm
model = Order
title = 'New Order'
extra_context = {'title': title}
class NewOrderForm(forms.ModelForm):
class Meta:
model = Order
widgets = {
'order_details': forms.Textarea,
}
exclude = (
'status',
'invoice',
'requester',
'modified_by',
)
class Order(models.Model):
STATUS_CHOICES = (
('open', 'Open'),
('inprogress', 'In Progress'),
('rejected', 'Rejected'),
('closed','Closed'),
('resolved','Resolved'),
)
subject = models.CharField(
max_length=30,
)
requester = models.ForeignKey(
User,
on_delete=models.PROTECT,
related_name='orders',
)
order_details = models.TextField(
)
created = models.DateTimeField(
auto_now_add=True,
)
updated = models.DateTimeField(
auto_now=True,
)
status = models.CharField(
max_length=12,
default='open',
choices= STATUS_CHOICES,
)
invoice = models.ForeignKey(
Invoice,
on_delete=models.PROTECT,
blank= True,
null=True,
related_name='orders',
)
modified_by = models.ForeignKey(
User,
on_delete=models.PROTECT,
related_name='orders_modified',
)
def __str__(self):
return self.subject
def get_absolute_url(self):
return reverse('Order_Detail', args=[str(self.pk)])
class Meta:
ordering = ['-created']
谢谢。
答案 0 :(得分:0)
在模型上调用ForeignKey对象时,实际上是在告诉Django执行查询以获取相关对象。要检查该关系是否存在,您应该检查<fieldname>_id
,它是字段的实际名称:
if not form.instance.requester_id:
form.instance.requester = self.request.user
这样,如果requester_id
是None
,则您将不会执行查询,而会出现RelatedObjectDoesNotExist
错误。