Let's say I have a simple 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()
I would like to automatically set the owner (request.user, registered user) for the object when it is created. I was looking for a lot of different options, but most of them are related to how you do this in the admin panel, while others just don't work for me. I tried this, for example, http://blog.jvc26.org/2011/07/09/django-automatically-populate-request-user , and then tried many ways to override the save method or some kind of pre_save stuff. Seems nothing does the trick, I just get the error message
IntegrityError at /new
null value in column "owner_id" violates not-null constraint
What is the right way to do this? I know that it’s just thinking, but I just can’t find a way to do it.
... EDIT ... My kind of creation is as follows:
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):
obj = form.save(commit=False)
obj.owner = self.request.user
obj.save()
return HttpResponseRedirect(self.get_success_url())
def get_success_url(self):
return reverse('contacts-list')
def get_context_data(self, **kwargs):
context = super(CreateContactView, self).get_context_data(**kwargs)
context['action'] = reverse('contacts-new')
return context
This is the only way I tried to solve this problem. I found this solution from http://blog.jvc26.org/2011/07/09/django-automatically-populate-request-user
source
share