Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 707
M. Gar Avatar asked Jan 30 '16 00:01

M. Gar


People also ask

How do you override the Save method of a model?

save() method from its parent class is to be overridden so we use super keyword. slugify is a function that converts any string into a slug.

What is Auth_user_model in Django?

Django allows you to override the default user model by providing a value for the AUTH_USER_MODEL setting that references a custom model. Method 2 – AUTH_USER_MODEL : AUTH_USER_MODEL is the recommended approach when referring to a user model in a models.py file.

How do I save changes in Django model?

To save data in Django, you normally use . save() on a model instance. However the ORM also provides a . update() method on queryset objects.


1 Answers

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.

like image 115
Ahmad Alzoughbi Avatar answered Nov 15 '22 09:11

Ahmad Alzoughbi