How to pass request/user to Django model

Question:

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

Asked By: Mehdi Aria

||

Answers:

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)
Answered By: Robert Lujo

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)
Answered By: Ranjeet Singh
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.