Django IntegrityError at /new null value in column "owner_id" violates not-null constraint
Asked Answered
P

1

4

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.

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

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, [email protected]).

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

...EDIT...

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?

Parthia answered 3/3, 2014 at 19:16 Comment(0)
P
5

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.

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)
Parthia answered 4/3, 2014 at 12:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.