D
D
Dauren S2017-01-30 15:46:30
Django
Dauren S, 2017-01-30 15:46:30

When saving in the admin panel, write down the user id?

It is necessary in the admin panel when saving the object to also save the user id,
how to do this?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
javedimka, 2017-01-30
@dauren101

In general, I reached the house, I will write in more detail. If you have a field for the user defined in the model, then you can generally select it manually, and if you are too lazy to do this, then you can do this.
Let's say you have an application for publishing articles "articles", in articles/models.py there is an article model that has a field with the user who added it, you can add another field for the user who last edited it, or you can not add it if only the user who added the article is needed:

# остальные импорты опущены 
from django.conf import settings


class Article(models.Model):
    ...
    added_by = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True,
                                 related_name="articles_added")
    last_edited_by = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True,
                                       related_name="articles_edited")
    ...

Since the two fields refer to the same model, you need to define a related_name for them so that later you can use it to work with the ORM, like to get all the articles added by the user: * object_of_the_desired_user
*.articles_added.all( ) you define a new model to "administer" this object:
from django.contrib import admin 
from .models import Article


class ArticleAdmin(admin.ModelAdmin):
    readonly_fields = ("last_edited_by",) # делаем полем рид онли, чтобы нельзя было его отредактировать

    def save_model(self, request, obj, form, change):
        if change: # True если изменяется уже существующий объект, False если добавляется новый
            # определяем и записываем пользователя если изменяется существующий объект
            obj.last_edited_by = request.user 
        else:
            # определяем и записываем пользователя если добавляется новый объект
            obj.added_by = request.user 
        super(ArticleAdmin, self).save_model(request, obj, form, change)


admin.site.register(Article, ArticleAdmin)

Everyone, try. If the user who edited the article is not needed, then, I hope, you will figure out what needs to be deleted?
More about save_model() :
https://docs.djangoproject.com/en/1.10/ref/contrib...
More about request :
https://docs.djangoproject.com/en/1.10/ref/request...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question