Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django set creator/owner for the object when created

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 set owner (request.user, logged in user) for the object automatically when it is created. I've searched a lot of different options but most of them are related to how you do it in admin side and other ones 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 I've tried many ways to override save method or some kind of pre_save signal stuff. Nothing seems to do the trick, I just get an error

IntegrityError at /new
null value in column "owner_id" violates not-null constraint

What is the right way to do that? I know that this is simple think to do but I just can't find the way to do it.

...EDIT... My create view looks like this:

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

That is just one way I tried to solve that problem so far. I found that solution from http://blog.jvc26.org/2011/07/09/django-automatically-populate-request-user

like image 680
m5seppal Avatar asked Mar 03 '14 16:03

m5seppal


1 Answers

Assuming you are using ContactForm ModelForm:

def contact(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            contact = form.save(commit=False)
            contact.owner = request.user
            contact.save()
            return HttpResponseRedirect('/thanks/')
    else:
         # do stuff
like image 113
almalki Avatar answered Sep 23 '22 23:09

almalki