Home > Software engineering >  How to pass request/user to Django model
How to pass request/user to Django model

Time:08-24

Here is my model:

class Exam(BaseModel):
    ...
    STATE_CHOICES = (
        (PASS, PASS),
        (FAILED, FAILED),
        (GREAT, GREAT),
    state = models.CharField(max_length=15, choices=STATE_CHOICES, default=PASS)
    ...

        def save(self, *args, **kwargs):
            request = kwargs.get('request', None)
            print(f'user {request.user} saved the model')
            super().save(*args, **kwargs)

    ...

And here is my admin model, I override the save_model method to pass request to my model:

@admin.register(Exam)
class ExamModelAdmin(admin.ModelAdmin):
    ...
    fields = ('state',)
    list_display = ('state',)
    form = ExamForm
    ...

    def save_model(self, request, obj, form, change):
        obj.save(request=request)

But I get an error:

save() got an unexpected keyword argument 'request'

Django = 3.2

CodePudding user response:

This will need overide/modification of models save() method, for instance:

class Exam(models.Model):
    ...
    def save(self, *args, **kwargs):
        request = kwargs.pop('request', None)
        # print(f'user {request.user} saved the model')
        ...
        super().save(*args, **kwargs)

CodePudding user response:

Try like this, might you can get in kwargs in save method of the model.

def save_model(self, request, obj, form, change):
    obj.save({"request": request})
    super().save_model(request, obj, form, change)
  • Related