我試圖跟蹤使用CreateView創建對象的用戶,我完全按照它在文檔中所做的操作(https://docs.djangoproject.com/en/dev/topics/class-based-views/generic-editing/, Models和request.user),除了我不使用login_required()裝飾器,而是使用django-braces中的LoginRequiredMixin。Django的IntegrityError在列「owner_id」中的/ new null值違反了非null約束
我的模型:
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)
當我嘗試創建一個新的對象,我得到一個錯誤:
IntegrityError at /new
null value in column "owner_id" violates not-null constraint
DETAIL: Failing row contains (3, null, John, Smith, [email protected]).
爲什麼這個錯誤發生?只是我想要做的是,所有者在創建時會自動添加到對象中。
...編輯...
我注意到這個問題有東西從Django的額外意見做與CreateWithInlinesView
。當我改變我的看法,使用Django的通用CreateView
,而不是一切正常工作。所以現在基本上問題是,爲什麼這個解決方案不適用於CreateWithInlinesView
?