tags:

views:

53

answers:

1

Hi all,

This is my very first post on this awesome site, from which I have been finding answers to a handful of challenging questions. Kudos to the community!

I am new to the Django world, so am hoping to find help from some Django experts here. Thanks in advance.


Item model:

class Item(models.Model):
    name = models.CharField(max_length=50)

ItemImage model:

class ItemImage(models.Model):
    image = models.ImageField(upload_to=get_unique_filename)
    item = models.ForeignKey(Item, related_name='images')

As you can tell from the model definitions above, every Item object can have many ItemImage objects.


My requirements are as followings:

  1. A single web page that allows users to create a new Item while uploading the images associated with the Item. The Item and the ItemImages objects should be created in the database all together, when the "Save" button on the page is clicked.
  2. I have created a variable in a custom config file, called NUMBER_OF_IMAGES_PER_ITEM. It is based on this variable that the system generates the number of image fields per item.

Questions:

  1. What should the forms and the template be like? Can ModelForm be used to achieve the requirements?
  2. For the view function, what do I need to watch out other than making sure to save Item before ItemImage objects?
A: 

Considering that you are using file upload fields, I'm not sure that it's a right approach for web application. What if Item name validation fails? If you re-display the form again all file upload fields become empty and user has to fill them again.

Re technical side - ModelForm will do for the Item model but you should also use model formset for ItemImage's. See http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#using-an-inline-formset-in-a-view for details.

Yaroslav
Thanks Yaroslav. I was able to experiment inline formset a little and I think it's exactly what I need. Additional resources/examples on inline formset:http://stackoverflow.com/questions/1113047/creating-a-model-and-related-models-with-inline-formsetshttp://djangosnippets.org/snippets/1246/#commentsAs for the details on image upload, it's a separate issue that I need to look into on my own.
ahmoo