Reputation: 69
I use Django 1.7.11 and python 2.7. I have two models:
class Adv(models.Model):
title = models.CharField(max_length=255, blank=True)
description = models.TextField(blank=True)
class ImageFile(models.Model):
file = models.ImageField(upload_to=generate_imgname, max_length=50, blank=True)
adv = models.ForeignKey(Adv)
Instance of Adv can have 10 image files. ImageFile is inline in admin. I need in the template show the instance of Adv with all it's image files and image files must be with form to delete or chance it. What is the best way to do it? I tryed inlineformset_factory but it show only form with file input without existing image files.
Upvotes: 1
Views: 1483
Reputation: 138
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.
Upvotes: 2