2

My original issue was that I was trying to attach the current user to new entries, so I override the save_model method under admin.ModelAdmin to do

def save_model(self, request, obj, form, change):
    obj.submit_usr = request.user
    super().save_model(request, obj, form, change)

This works great when I try to create new object or new entry in my db, but when I try to edit the existing one, it still creates a new entry

my model looks like (I took out all the settings to avoid being messy here)

class AppUser(models.Model):
    app_name = model.CharField()
    submit_usr = models.ForeignKey()
    submit_date = model.DateTimeField()

I know that the change arg indicates if there's a change in existing entry, but I still don't have a way to tell Django that I only want to modify the current entry instead of creating a new one.

Any ideas how to achieve that?

JChao
  • 2,178
  • 5
  • 35
  • 65
  • Which button you clicking in Django admin to teste it? because your code is right, but maybe you clicking to Save a new one at django instando ok clicking save the currenty object – Diego Vinícius Jul 06 '18 at 16:15
  • is the code right though? Shouldn't it be `super(AppUserAdmin, self).save_model(request, obj, form, change)`? or is that unnecessary in modern django/python? – Nicholas Claude LeBlanc Jul 06 '18 at 16:22
  • @DiegoVinícius I do not see an "OK" button. the "Save", "Save and add another" and "Save and continue editing" are the only buttons I see – JChao Jul 06 '18 at 16:47
  • @NicholasClaudeLeBlanc I actually tried both. Both have the same effect. I'm not sure if things work inherently different in this case. I'm using django 2.0 btw – JChao Jul 06 '18 at 16:59
  • hmmm, I'm just looking through the source. I don't have time to run my own tests right now. try printing `form.is_valid()` `change` and `obj.id` and see what you get – Nicholas Claude LeBlanc Jul 06 '18 at 17:27
  • @NicholasClaudeLeBlanc `form.is_valid()` = `True`, `change` = `True`, `obj` doesn't have `id` attribute, from the database, it seems like there's no autoincrementing value for id. `PrimaryKey` is linked to `app_name`. Does this make editing `app_name` impossible? – JChao Jul 06 '18 at 17:39
  • I'm not sure I follow, can you post the rest of the model? – Nicholas Claude LeBlanc Jul 09 '18 at 16:47

1 Answers1

5

You can try

def save_model(self, request, obj, form, change):
    if not change:
        obj.submit_usr = request.user
    super().save_model(request, obj, form, change)
Kholdarbekov
  • 973
  • 1
  • 10
  • 28