Mr G
Mr G

Reputation: 268

Generating files after adding model instance through django admin interface

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?

Upvotes: 0

Views: 100

Answers (1)

philoj
philoj

Reputation: 488

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

Upvotes: 1

Related Questions