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

I need the current user to register in the save method for one of my models, as well as request.userfrom the views, but in the save model method, is this possible? and if so, how can I do this?

+4
source share
1 answer

if you have a 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 delete editable=Falseif you want to allow the user to assign to created_byanother user.

+12
source

Source: https://habr.com/ru/post/1626608/


All Articles