models.py:
class Item(models.Model):
name = models.CharField(max_length=50)
class ItemImage(models.Model):
image = models.ImageField(upload_to='item_pics')
item = models.ForeignKey(Item, related_name='images')
With the above defined models, Item has a one-to-many relationship to ItemImage. I am working on a django form that enables user to create a new Item instance, along with the choice of uploading up to two ItemImage. Note that the Item and the associating ItemImage objects need to be created at the same stage.
forms.py:
class ItemForm(ModelForm):
img_1 = fields.ImageField()
img_2 = fields.ImageField()
class Meta:
model = Item
fields = ('name', 'description', 'circles', 'location', 'rental_fee', 'rental_time_unit', 'deposit', 'rental_rules',)
On a second thought, instead of adding the image fields to ItemForm, I am guessing it might be a better approach to create a ModelForm for ItemImage and use inline formset. I have never used inline formset and thus my concept of it is still vague. I want to know if this is a right scenario to use inline formset.
Yes, this would be a very typical situation in which you would use a ModelFormSet.
The approach used in your forms.py would be appropriate if img_1 and img_2 were actual fields of class Item, but a ModelFormSet is a better choice when dealing with a set of related models.
Consider the future case where you wish to allow users three images rather than two. Using a ModelFormSet, this would be a one character code alteration. If you want to collect ancillary information on the ItemImage class, this would also be a trivial change.