blog: archive / rss

Save Me

I recently had a need to modify the files associated with a ManyToManyField while saving the model in one of my django-based projects. I did some googling to see how to go about doing that, and realized that the ManyToMany data is saved after the save method is called. So, I thought I would outline what I did to work around that. I’m sure the code could be cleaned up a bit. So, suggestions are welcome.

Here are some code samples:

# models.py
class Collection(models.Model):
    title = models.CharField(max_length=200)
    slug = models.SlugField()
    description = models.TextField(blank=True)
    image = models.ImageField('Collection Image', 
        upload_to="path/to/collection/", blank=True)
    sermons = models.ManyToManyField(Sermon)
    archive = models.FileField('zipped archive',
        upload_to="path/to/file/", blank=True)
# admin.py
class CollectionAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):

    # Call the save method to save the data.
    obj.save()

    # Call the save_m2m to save the ManyToMany data.
    form.save_m2m()

    # Now we can grab the ManyToMany items
    sermons = obj.sermons.all()

    # And iterate through them.
    for m in sermons:
        mp3_file = '%s/%s' % (settings.MEDIA_ROOT, m.mp3) 
        ... # Do stuff to the files.

    # Zip it up as an archive
    zip_file = 'location/of/archives/%s.zip' % (obj.slug)
    tpath = '%s/%s' % (settings.MEDIA_ROOT, zip_file)

    tfile = zipfile.ZipFile(tpath, "w")

    for name in sermons:
        mp3_file = '%s/%s' % (settings.MEDIA_ROOT, name.mp3) 
        tfile.write(
            mp3_file, 
            os.path.basename(mp3_file), 
            zipfile.ZIP_DEFLATED
        )

    tfile.close()

    # Associate the new zipped file with the 
    # Model's archive field.
    obj.archive = zip_file

    # Go ahead and save the Model again to save 
    # the change to the archive link.
    obj.save()
    
    
« Previous | Next »

Comments

Comments no longer accepted for this entry.

To prevent spam, comments are no longer allowed after 60 days.

Google Analytics Alternative