'set the logged in user to created_by for django CreateView

Apart from form_valid() method what are the other efficient ways i can set the user to created by.

views.py

class CreatEEView(LoginRequiredMixin, CreateView,):
    form_class =  ''
    template_name = ''
    success_url = ''

    def form_valid(self, form):
       instance = form.instance
       instance.created_by = Model.objects.get(user=self.request.user)
       instance.save()
       return super().form_valid(form)


Solution 1:[1]

You should use self.request.user itself. Furthermore you should not save the instance, that will be handled by the super().form_valid(form) call, so:

class CreatEEView(LoginRequiredMixin, CreateView):
    form_class = …
    template_name = …
    success_url = …

    def form_valid(self, form):
       form.instance.created_by = self.request.user
       return super().form_valid(form)

You could wrap this in a mixin, for example:

class SetUserMixin(LoginRequiredMixin):
    user_field = 'created_by'

    def form_valid(self, form):
        setattr(form.instance, self.user_field, self.request.user)
        return super().form_valid(form)

and then use the SetUserMixin with:

class CreatEEView(SetUserMixin, CreateView):
    form_class = …
    template_name = …
    success_url = …

Solution 2:[2]

I have come up with something like this but it is not setting in the model.

admin.py

    def save_model(self, request, obj, form, change):
        obj.created_by = request.user
        print('********')
        print(obj.created_by)
        obj.save()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Willem Van Onsem
Solution 2