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
?