Django Admin Model Field Set To Current User
I have a model with field: class MyModel(models.Model): name = models.CharField(max_length=50) created_by = models.ForeignKeyField(User) In my admin: class MyModelAdmin(ad
Solution 1:
You have already set fields
so that created_by
does not appear in form in the Django admin.
Now you need to override save_model
, and set the user before saving new objects.
classMyModelAdmin(admin.ModelAdmin):
fields = ("name",)
defsave_model(self, request, obj, form, change):
ifnotchange:# the object is being created, so set the user
obj.created_by = request.user
obj.save()
Solution 2:
To do that override the save_model
method and set the created_by
field to the current user.
classMyModelAdmin(admin.ModelAdmin):
list_display= ("name",)
fields = ("name",)
defsave_model(self, request, obj, form, change):
ifnotchange:# can use this condition also to set 'created_by' # if not getattr(obj, 'created_by', None):
obj.created_by = request.user
obj.save()
Post a Comment for "Django Admin Model Field Set To Current User"