0

I'm writing a model for a website. When a user adds an instance of the model through the Django admin, I want to catch the event and automatically generate files, including adding a reference path field for those created files.

The model form (used for the admin site) has a clean method that can be overridden. I can create and update files and fields through this.

def clean(self):
    info = self.cleaned_data.get('info')

    ... #Generate IO paths from info

    self.cleaned_data['template_path'] = template_path
    self.instance.template_path = template_path

    return self.cleaned_data

I need to create a distinction between add and change events, so I'm not writing files and changing the pathing post object creation. Is there a way to do this within clean, or should I be looking elsewhere to create fields & update fields?

Mr G
  • 244
  • 3
  • 10
  • Here's how to differentiate between new and existing objects in a custom save() method: https://stackoverflow.com/a/35647389/8893667 – Endre Both Jan 27 '19 at 10:56

1 Answers1

1

Cleaning a ModelForm doesn't necessarily mean that the Model instance will get saved.

You can do this in the Model's save() method or pre_save signal so that it is certain.

That being said, to distinguish between add and change, you may first query the database for an instance with same id prior to saving.

if instance.pk and instance.__class__.objects.filter(pk=instance.pk):
    # Editing existing instance, skip
    pass
else:
    # New instance. do whatever you want

In your case instance becomes self.instance

philoj
  • 468
  • 2
  • 13
  • Also you can save that database query by using instance._state. See @Endre Both's comment in the question – philoj Jan 30 '19 at 06:58
  • I implemented this through the save method. Much better workflow, but I just had to make sure I was calling super().save() _after_ my conditional check and updating of custom fields. Works well. – Mr G Feb 03 '19 at 11:14