Question

So I have this class which is an abstract parent class to a bunch of other classes, let's call it ActivityModel (representing some sort of latest activity/or change done to that object) and I want to override the save method to take another argument every time the object is saved so I define it as follows.

class ActivityModel(models.Model):
    last_updated = models.DateTimeField(auto_now=True)
    updater = models.ForeignKey(UserProfile)
    change = models.CharField(max_length=255)

    def save(self, updater, change, *args, **kwargs):
        self.updater = updater
        self.change = change
        super(ActivityModel, self).save(*args, **kwargs)

    class Meta:
        abstract = True

But now all the models that I make inherit this class can't use ModelForms because I've changed the save method to require this second field (the UserProfile corresponding to the authenticated user which must be supplied every time it is saved) so I was wondering if it is possible for me to subclass the ModelForm class to override it's save method so that it will call the new ParentModel.save method and fill in the currently logged in user that has been supplied to it. I figure I can just supply the UserProfile on the forms init, but the big question I have is whether it is possible to subclass the ModelForm class and create like a ParentModelForm class which can then be subclassed for each of ParentModel's child classes. Is this possible and if so, how would I go about doing it?

All help is very much appreciated! Thanks for your time!

Was it helpful?

Solution

ModelForm is also a python class with a similar behavior as the other classes.

#Inherits from ModelForm class
class ParentModelForm(forms.ModelForm):
...
...
   def save(self, *args, **kwargs):
     ...
     ...
#Inherits from ParentModelForm
class ChildModelForm(ParentModelForm):
..
..
  #You would have to override the Meta class
  class Meta:
      model = Child
  def save(self, *args, **kwargs):
       #Calling the parent model form save method
       super(ChildModelForm, self).save(*args, **kwargs)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top