Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django autoupdate user; save() got an unexpected keyword argument 'force_insert'

I'm trying to implement an auto update for the user who creates a record using ModelAdmin save_model as described here. I wasn't able to work out how to get around the kwarg error "save() got an unexpected keyword argument 'force_insert'".

admin.py
from myapp.myproj.models import Activity
from django.contrib import admin

class ActivityAdmin(admin.ModelAdmin):
    exclude = ('cruser',)
    list_display = ('activity_nm', 'activity_desc', 'startdt', 'enddt','upddt','crdt')

    def save_model(self, request, obj, form, change):
        if not change:
            obj.cruser = request.user
        obj.save()

admin.site.register(Activity, ActivityAdmin)

The documentation states that

"The save_model method is given the HttpRequest, a model instance, a ModelForm instance and a boolean value based on whether it is adding or changing the object."

Is this something automatic or do I need to pass it in from the view? If that's not the issue, then what else could it be?

EDIT: changed code back to match example.

like image 752
jabs Avatar asked Oct 06 '12 13:10

jabs


2 Answers

update

If you have overridden save() method of Activity or some other Models that get saved in meanwhile, but forgotten to accept force_insert as keyword argument, this error could happen:

def save(self):
   ...
# should be
def save(self, force_insert=False, force_update=False, using=None):
    ...
# or at least
def save(self, **kwargs):
    ...

Check the trackback to locate the failed save


Your code does not fully follow the code from b-list.org, try:

def save_model(self, request, obj, form, change): 
    if not change:
        obj.cruser = request.user
    obj.save() 
like image 71
okm Avatar answered Oct 19 '22 05:10

okm


As a general rule, you should only override the save() method in the model itself, not in some model admin.

When overriding the save() method in a model, you should always use (*args, **kwargs) to be safe. You have no way of knowing which specific parameters are being used when a specific model is being saved.

Your Activity model should contain a method like this:

def save(self, *args, **kwargs):
    '''do your custom stuff here'''
    return super(Activity, self).save(*args, **kwargs)
like image 4
Blairg23 Avatar answered Oct 19 '22 04:10

Blairg23