I’m working on a Django app that has a Members model related to the built-in User class from django.contrib.auth.models. It looks like this:
class Members(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
member_image = models.ImageField(upload_to='unknown')
member_position = models.CharField(max_length=255)
...
The problem is: when I add a member_image in the admin, I also have to manually select the user.
That doesn’t make sense to me because I want the logged-in user to be automatically detected and set as the user.
I tried something like this:
class Members(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, default=request.user.id)
And then, in the admin, I removed the user field so that it doesn’t have to be selected manually:
class MembersAdmin(admin.ModelAdmin):
fields = ('member_image', 'member_position', ...)
My goal:
If the user field isn’t explicitly set in the admin, it should default to the currently logged-in user.
But since request isn’t available outside views.py, this doesn’t work.
I’ve also tried solutions from:
but I still haven’t figured it out.
How can I set the logged-in user automatically in this model/admin setup?
Modify MembersAdmin save_model method and attach request.user to the object prior to saving.
class MembersAdmin(admin.ModelAdmin):
fields = ('member_image', 'member_position', ...)
def save_model(self, request, obj, form, change):
obj.user = request.user
super().save_model(request, obj, form, change)