在“owner

编程入门 行业动态 更新时间:2024-10-28 07:20:07
本文介绍了在“owner_id”列中的/ new null值处的Django IntegrityError违反非空限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试使用CreateView跟踪创建对象的用户,而且我完全像在文档中完成( docs.djangoproject/en/dev/topics/class-based-views/generic-editing/ ,模型和request.user),除了我不使用login_required()装饰器,而是从django大括号使用LoginRequiredMixin。

I'm trying to track the user that created an object using a CreateView and I'm doing it exactly like it's done in documentation (docs.djangoproject/en/dev/topics/class-based-views/generic-editing/, Models and request.user) except I don't use login_required() decorator but LoginRequiredMixin from django-braces instead.

我的模型:

class Contact(models.Model): owner = models.ForeignKey(User, editable=False) first_name = models.CharField(max_length=255,) last_name = models.CharField(max_length=255,) email = models.EmailField()

我的观点:

class CreateContactView(LoginRequiredMixin, ContactOwnerMixin, CreateWithInlinesView): model = models.Contact template_name = 'contacts/edit_contact.html' form_class = forms.ContactForm inlines = [forms.ContactAddressFormSet] def form_valid(self, form): form.instance.owner = self.request.user return super(CreateContactView, self).form_valid(form)

当我尝试创建一个新对象我收到一个错误:

When I try to create a new object I get an error:

IntegrityError at /new null value in column "owner_id" violates not-null constraint DETAIL: Failing row contains (3, null, John, Smith, john.smith@gmail).

为什么会出现此错误?只有我想要做的事情是,所有者在创建时自动添加到对象。

Why this error happens? Only thing what I'm trying to do is that owner is added automatically to object when it is created.

...编辑...

我注意到这个问题与django extra-views中的 CreateWithInlinesView 有关。当我更改我的视图以使用django的通用 CreateView 而不是一切都没有问题。所以基本的问题是现在为什么这个解决方案不能用 CreateWithInlinesView ?

I noticed that this problem has something to do with that CreateWithInlinesView from django extra-views. When I change my view to use django's generic CreateView instead everything works without problems. So basically question is now that why this solution isn't working with CreateWithInlinesView?

推荐答案

我设法解决了这个问题。只是一个愚蠢的错误,但我提供这个答案,以防万一有人做愚蠢的错误。

I managed to solve this problem. Just a stupid mistake by me but I provide this answer just in case if someone else ever does stupid mistakes.

所以当使用 CreateWithInlinesView 你必须覆盖函数 forms_valid(),而不是 form_valid(),使一切正常。您的 forms_valid()应如下所示:

So when using CreateWithInlinesView you must override function forms_valid() instead of form_valid() to make everything work correctly. Your forms_valid() should look like this:

def forms_valid(self, form, inlines): form.instance.owner = self.request.user return super(CreateContactView, self).forms_valid(form, inlines)

更多推荐

在“owner

本文发布于:2023-10-22 20:55:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1518689.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:owner

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!