Skip to content

Instantly share code, notes, and snippets.

@DataGreed DataGreed/receivers.py
Last active Dec 2, 2019

Embed
What would you like to do?
Django: update audio duration in database if the associated audio file was updated by user
# considering model has audio_field = FileField()
def some_pre_save_receiver(sender, instance, raw, using, update_fields, **kwargs):
file_was_updated = False
if hasattr(instance.audio_file, 'file') and isinstance(instance.audio_file.file, UploadedFile):
file_was_updated = True
if update_fields and "audio_file" in update_fields:
file_was_updated = True
print(f">> pre_save receiver executed, update fields: {update_fields}, file_was_updated: {file_was_updated}")
if file_was_updated:
# read audio file metadata
audio_info = mutagen.File(instance.audio_file).info
# set audio duration in seconds, so we can access it in database
instance.duration_seconds = int(audio_info.length)
print(">> audio duration was was updated")
else:
print(">> file not changed - duration was NOT updated")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.