如何在Django CreateView期间处理错误

时间:2017-12-11 23:37:08

标签: python django

使用Django,我有一个基于提供的CreateView类的模型和基于类的视图。一切正常 - 我可以有一个模板,用于呈现表单,验证发生,数据正确保存,success_url重定向到完成。

问题出现在我对两个字段有一个unique_together约束。如果遇到此错误,则表明form_valid()似乎没有捕获它,而是生成错误页面。

我的目标是能够提前捕获并将用户返回到表单 - 从上次尝试填写数据 - 并向他们显示消息。这样的感觉应该很简单,我在视图中添加了form_valid()代码来识别问题,但我不知道下一步该做什么。

重定向不起作用,因为我无法添加上下文(或者我可以吗?)而且我真的不想将所有内容都放在URL中。任何想法在哪里看?

模特:

class Client(BaseModel):
    name = models.CharField(max_length=240, db_index=True, verbose_name='Client Name')
    organization_link = models.ForeignKey(Organization, on_delete=models.PROTECT, verbose_name='Organization')
    client_group_link = models.ForeignKey(ClientGroup, blank=True, on_delete=models.SET_NULL, null=True, verbose_name='Client Group')
    policy_link = models.ManyToManyField(OrganizationPolicy, related_name='attached_clients', verbose_name='Policies')
    active = models.BooleanField(default=True, db_index=True, verbose_name='Active')

    class Meta:
        unique_together = (('name', 'organization_link'),)

观点:

class ClientCreateView(CreateView):
    model = Client
    fields = ['name', 'client_group_link', 'active']
    success_url = reverse_lazy('entities_client_roster')

    def form_valid(self, form):
        organization = get_object_or_404(Organization, id=self.kwargs['organization'])
        form.instance.organization_link_id = organization.id
        return super().form_valid(form)

代码段网址配置:

url(r'^client_create/(?P<organization>[0-9a-f-]+)',
    ClientCreateView.as_view(template_name='entities/client_create.html'),

错误:

IntegrityError at /accept/client_create/xxx
duplicate key value violates unique constraint "app_entities_client_name_organization_link_id_5e612e47_uniq"

1 个答案:

答案 0 :(得分:0)

谢谢@geckos ......这使我指向正确的方向。将以下内容添加到我的View中完成了这项工作:

def post(self, request, *args, **kwargs):
    try:
        super().post(request, *args, **kwargs)
    except IntegrityError:
        messages.add_message(request, messages.ERROR,
                             'You already have registered a Client with this name. ' + \
                             'All of your Client names must be unique.')
        return render(request, template_name=self.template_name, context=self.get_context_data())