Reputation: 3793
I have models like this:
class NameReplacements(models.Model):
excel_file = models.FileField(upload_to='excel_files')
class NameReplacement(models.Model):
name_to_replace = models.CharField(max_length=255, default='')
name_to_replace_with = models.CharField(max_length=255, default='')
I am uploading the file for NameReplacements
through admin panel.
Elsewhere in my app I have some code that reads the file from the latest instance of this model and saves data from each row of this file as NameReplacement
instance:
def remove_old_name_replacements():
'''Removes all instances of NameReplacement from database'''
replacements = NameReplacement.objects.all()
replacements.delete()
def import_name_replacements():
'''Imports name replacements to database from last uploaded Excel file'''
remove_old_name_replacements()
replacements = NameReplacements.objects.last()
df = pd.read_excel(replacements.excel_file.path)
for i in range(len(df)):
name_to_replace=str(df.loc[i, 'managers']),
name_to_replace_with=str(df.loc[i, 'best_matches'])
name_replacement = NameReplacement(name_to_replace, name_to_replace_with)
name_replacement.save()
Currently I just run import_name_replacements
manually from the Django shell whenever I upload a new file.
Is there a way to tell Django to run this code automatically whenever I upload the file via admin panel?
Upvotes: 0
Views: 532
Reputation: 26
I'm not sure to well understand how the uploading process works. But what you could do is to call the import_name_replacements method each time you create a NameReplacements object, to do this, you need to override the save method, here is an example:
def save(self, **kwargs):
super(NameReplacements, self).save(**kwargs)
import_name_replacements()
Upvotes: 0
Reputation: 498
Add the following method to your NameReplacements model, which will override the save() method.
def save(self, *args, **kwargs):
super(NameReplacements, self).save(*args, **kwargs)
import_name_replacements()
Upvotes: 1