在“owner_id”列中的/ new null值处的Django IntegrityError违反非空限制 [英] Django IntegrityError at /new null value in column "owner_id" violates not-null constraint
问题描述
我正在尝试使用CreateView跟踪创建对象的用户,而且我完全像在文档中完成( https://docs.djangoproject.com/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 (https://docs.djangoproject.com/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.com).
为什么会出现此错误?只有我想要做的事情是,所有者在创建时自动添加到对象。
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_id”列中的/ new null值处的Django IntegrityError违反非空限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!