Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

make the user in a model default to the current user [duplicate]

I have the following:

from django.contrib.auth.models import User

class ClientDetails(models.Model):
    created_by = models.ForeignKey(User)
    ...

How do I make created_by default to the currently logged in user?

(I want to do this so I can hide it in the admin view mainly but also because when I save an instance I don't want to be filling it every time)

like image 478
Robert Johnstone Avatar asked Jan 12 '11 15:01

Robert Johnstone


1 Answers

Since you need to get the currently logged in user from a request object you cannot get it in the model's save-method,but you can eg override the model admin's save_model-method:

class MyAdmin(admin.ModelAdmin):
    def save_model(self, request, instance, form, change):
        user = request.user 
        instance = form.save(commit=False)
        if not change or not instance.created_by:
            instance.created_by = user
        instance.modified_by = user
        instance.save()
        form.save_m2m()
        return instance
like image 107
Bernhard Vallant Avatar answered Oct 13 '22 22:10

Bernhard Vallant