开发者

Default value for user ForeignKey with Django admin

开发者 https://www.devze.com 2023-02-25 10:38 出处:网络
author = models.ForeignKey(User) Is there any way I can set the default value of this field to automatically select the logged in user? I know you can do this in the save method but my client has re
author = models.ForeignKey(User)

Is there any way I can set the default value of this field to automatically select the logged in user? I know you can do this in the save method but my client has requested that it automatically defaults to the logged in user at edit time to avoid confusion.

This 开发者_StackOverflow中文版article goes into how to update it during save, just not at edit time.


class MyModelAdmin(admin.ModelAdmin):
    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == 'author':
            kwargs['initial'] = request.user.id
        return super(MyModelAdmin, self).formfield_for_foreignkey(
            db_field, request, **kwargs
        )


You could override the Admin part of your model to not display the author if the object that you are editing is new because it should be set to the current user and only if you are editing an object does the field show?

You would do this by overriding the get_form method of ModelAdmin.

0

精彩评论

暂无评论...
验证码 换一张
取 消