Django IntegrityError at / new null value in column "owner_id" violates non-empty constraint

I try to track the user who created the object using CreateView, and I do it exactly the same as in the documentation ( https://docs.djangoproject.com/en/dev/topics/class-based-views/generic-editing/ , Models and request.user), except that I do not use login_required () decorator, but LoginRequiredMixin instead of django-braces.

My model:

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()

My opinion:

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 message:

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 is this error occurring? The only thing I'm trying to do is that the owner is automatically added to the object when it is created.

... EDIT ...

, - CreateWithInlinesView django. - CreateView, . , CreateWithInlinesView?

+4
1

. , , - .

CreateWithInlinesView forms_valid() form_valid(), . forms_valid() :

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

Source: https://habr.com/ru/post/1529839/


All Articles