M. Gar
M. Gar

Reputation: 885

get current user to use it in the save method for one of my models

I need to get the current user logged in the save method for one of my models, just like the request.user from the views but in the save model method, is this posible? and if it is, how can I do it?

Upvotes: 7

Views: 6175

Answers (1)

Ahmad Alzoughbi
Ahmad Alzoughbi

Reputation: 474

if you have model like this in your models.py:

class Post(models.Model):
    title = models.CharField(max_length=100)
    created_by = models.ForeignKey(User, editable=False)

Then in your admin.py it should be:

class PostAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):
        if not change:
            obj.created_by = request.user
        obj.save()
admin.site.register(Post, PostAdmin);

You can also remove the editable=False if you want to allow the user to assign the created_by to another user.

Upvotes: 17

Related Questions