简体   繁体   English

为在 Django 管理面板中创建的对象保存创建者

[英]Save creator for objects created in the Django admin panel

I want to create a few objects directly in Django's admin panel, and in that object automatically save the username of the administrator that have been creating it.我想直接在 Django 的管理面板中创建一些对象,并在该对象中自动保存创建它的管理员的用户名。

Any suggestions of how to do this in the easiest way?有关如何以最简单的方式执行此操作的任何建议?

Cheers,干杯,

Peter彼得


class UserMessage(models.Model):
    reciever_id = models.OneToOneField(
        User,
        on_delete=models.CASCADE,
        primary_key=True,
    )
    heading = models.CharField(max_length=60)
    message = models.TextField(blank=True)
    time_created = models.DateTimeField(auto_now_add=True)

    creator_id = models.ForeignKey(User)

You need to add a save_model method to your model admin:您需要向模型管理员添加save_model方法:

def save_model(self, request, obj, form, change):
    if not obj.creator_id:  # if obj does not have a creator
        obj.creator_id = request.user
    super().save_model(request, obj, form, change)

More details here更多细节在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM