I have 2 models Listing
and Image
, where a listing can have multiple images.
class Listing(models.Model):
title = models.CharField(max_length=100, blank=False)
class ListingImage(models.Model):
listing = models.ForeignKey(Listing, on_delete=models.CASCADE, related_name='images')
image = models.ImageField(blank=True)
Ideally, I wanted to create such listings on a single page e.g. fill in all form information AND add images on the same page.
It seems that this is not possible (if it's please let me know, but note that dropzone.js is Ajax) to handle 2 forms with a single view and I have made the following workarounds:
- Create listings first, add 2nd step to add listings to created model
- Create a placeholder listing, add images to it (via Ajax) and on form submit, change the placeholder information.
Which method is better?
views.py
def add_image(request):
# process images: problem we have no listing_instance to add them to
if request.method == 'POST':
form = ListingImageForm(request.POST, request.FILES)
if form.is_valid():
ListingImage.objects.create(pk=None, listing=listing_instance)
return HttpResponse(
json.dumps({
"result": True,
}),
content_type="application/json"
)
I'm looking for methodology advice. For example, to create a listing with images, do I need to first create the listing and then add images (2 steps) or add images first and listing information? My problem is that if I do that, the listing is not yet created when I add the images using Ajax.