Django sets the creator / owner of an object when creating

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

+4
source share
3 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
+3
source

Please provide the exact code of what you tried.

If your opinion requires that the user is logged in, make sure that he is operational. This can be done using the decorator.@login_required

ModelForm Contact, commit=False kwarg (, ). , owner = request.user.

, , owner Contact

0

, form_valid self.object, get_success_url, , .

obj self.object, :

def form_valid(self, form):
    self.object = form.save(commit=False)
    self.object.owner = self.request.user
    self.object.save()
    return HttpResponseRedirect(self.get_success_url())

I found a quick check of the original implementation of the side effects on the Classy Class-Based Views. The website or Django source code on GitHub is useful for identifying any side effects that I need to reproduce in the implementation of the subclass.

0
source

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


All Articles