[Answered ]-Django. Inline formset with existing instances of model in template

2👍

Did you try using formset?
https://docs.djangoproject.com/en/1.7/topics/forms/modelforms/#model-formsets
Try this. I havent tried it out but I did something similar in my project and it worked. I hope it helps.

forms.py

class AdvForm(ModelForm):
 class Meta:
  model = Adv
  fields = ['title','description']

class ImageFileForm(ModelForm):
 class Meta:
  model = ImageFile
  fields = ['file','adv']

in your views.py,

do something like pass your instance of adv

def getAdv(request, adv_instance_id):
 adv = get_object_or_404(Adv, pk = adv_instance_id)
 ImgFileformSet = modelformset_factory(ImageFile, form = ImageFileForm)

 if request.method == 'POST':
  Adv = AdvForm(request.POST, instance=adv)
  ImgFiles = ImgFileformSet (request.POST, queryset = ImageFile.objects.filter(adv=adv_instance_id), prefix='images', )
 // your code

return render(request, 'yourtemplate', {'adv_instance_id','Adv','ImgFiles'})

and display the data in your template.

Leave a comment