get current user for 'created_by' field in model class

ubisun picture ubisun · Oct 18, 2018 · Viewed 8.2k times · Source

I'm currently working on a Django app, and I'm trying to set the current user as default on a model, but it doesn't work.

created_by = models.ForeignKey(User, default=request.user, null=True, blank=True, on_delete=models.DO_NOTHING, related_name='created_by')

I tried to override the save() method but it doesn't work either, anyone has any experience on this matter ?

Thanks a lot in advance for your help

Answer

a_k_v picture a_k_v · Oct 18, 2018

Refer official doc. It explained it pretty well. An example is also there

from django.views.generic.edit import CreateView
from myapp.models import Author

class AuthorCreate(CreateView):
    model = Author
    fields = ['name']

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

https://docs.djangoproject.com/en/2.1/topics/class-based-views/generic-editing/#models-and-request-user