[Django]-Default value for user ForeignKey with Django admin

48👍

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
        )

0👍

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.

Leave a comment