0

I've got a small app with DefaultRouter used to handle basic operations at certain models.

The problem is, that I need to override the create and update method for standard DefaultRouter, to handle problem without using Django Admin.

Models, etc. are nothing special, but important thing is that I want to override method for all models using specific abstract model as a parent. If I've created save() and update() methods in model, DefaultRouter crashes.

from django.db import models

"""
    Class contains common fields for all models
"""


class AbstractOurModel(models.Model):
    add_user = models.ForeignKey(
        'User', 
        models.PROTECT,
        blank=False,
        null=False,
        related_name='%(class)s_add_user'
    )
    add_date = models.DateTimeField(auto_now_add=True)
    mod_user = models.ForeignKey(
        'User', 
        models.PROTECT,
        blank=False,
        null=False,
        related_name='%(class)s_mod_user'
    )
    mod_date = models.DateTimeField(auto_now=True)

    def save(request):
        self.add_user = request.user 
        self.mod_user = request.user 

    def update(request):
        self.mod_user = request.user

    class Meta:
        abstract = True

Thanks for help!

Rallyholic
  • 317
  • 1
  • 3
  • 21
  • 1
    you need to show us the code that produces the crash. Every question needs a [mcve]. – dirkgroten Mar 11 '19 at 19:13
  • Sorry, my mistake, I was sure that I pasted it. Edited. And I know that I propably can't pass request from DefaultRouter without any other actions, but that is also the point where i need to look for help. Or maybe i must use another Router, or build my own... – Rallyholic Mar 11 '19 at 19:15
  • But what causes the crash? Adding a `save()` method that takes a request on your models without calling `super().save()` will never work, since Django's `Model` save method expects other kwargs (like `using`, `force_insert`, etc...) and by default doesn't pass a `request` object to `save()`. You're basically making it impossible to save your models because you break the default save. – dirkgroten Mar 11 '19 at 19:20
  • So, there is any way to pass request to these methods, after adding super()? Or any way to automatically fill these fields... – Rallyholic Mar 11 '19 at 19:26
  • 1
    You should override the `create()` and `update()` methods on your `Views` or `ViewSets`. They derive the functionality from the `CreateModelMixin` and the `UpdateModelMixin` so you'd have to subclass those mixins and then make sure all `Views` or `ViewSets` use your mixins instead of the default DRF ones. Use [this documentation](http://www.cdrf.co) to find out how the various classes inherit from each other. – dirkgroten Mar 11 '19 at 19:32

0 Answers0