ImageField and edit_inline revisited
A while back I wrote about using edit inline with image and file fields. Specifically, I suggested adding an uneditable
BooleanField as the
core field of the related model. This means you don’t have to set the
FileField to be
core (which would cause confusing behaviour).
Removing the related model
The downside to having an uneditable core field is that you can’t remove the related model instance using admin. At the time, I wasn’t trouble by this so I just left it. In a recent project I needed to associate photos with articles, use
edit_inline for the photos and be able to remove them. So here’s an extended workaround.
As well as the uneditable
BooleanField (“keep”) which keeps the
ArticlePhoto from being deleted, we now have a “remove”
BooleanField which the user can tick in admin to cause the
ArticlePhoto to be deleted. The check for this is in the
class ArticlePhoto(models.Model): article = models.ForeignKey(Article, related_name='photos', edit_inline=models.TABULAR, min_num_in_admin=5) keep = models.BooleanField(core=True, default=True, editable=False) remove = models.BooleanField(default=False) image = CustomImageField() def save(self): if not self.id and not self.image: return if self.remove: self.delete() else: super(ArticlePhoto, self).save()
It’s a pretty easy way to work around the problem and gives a sensible looking “remove” checkbox in the admin interface. The database table will have a “remove” column that never gets used, but it’s a pretty small price to pay.
This gem and your previous tip just saved me hours of searching and frustration! Thanks for taking the time to write up these up!
Comment by David — 6 April 2008 @ 9:13 am
Thanks for the effort. Would of taken me a while to work that one out.
Comment by David McGettigan — 30 April 2008 @ 2:47 pm