简体   繁体   中英

One single page to create a Parent object and its associated child objects

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM