Reputation: 10950
How would I write a view with a single form to add a new person, and on that same form, be able to add 0 or 1 or 2 or ... 68757857 images of that same person?
Please refer to the code below.
In models.py:
class Person(models.Model):
name = models.CharField(max_length=50)
class Image(models.Model):
person = models.ForeignKey(Person)
image = models.ImageField(upload_to='images/')
In forms.py:
class PersonForm(forms.ModelForm):
class Meta:
model = Product
fields = ['name']
class ImageForm(forms.ModelForm):
class Meta:
model = Image
fields = ['person', 'image']
From what I have seen, formsets are used. I have looked at many examples on SO, read the documentation and I am still confused.
I would appreciate it if someone can provide an example of a views.py that fulfils the specification at the beginning of this question.
Upvotes: 0
Views: 1739
Reputation: 47374
You could use Inline formsets.
In view.py
firt of all you have to create a new person instance and then use this instance with formset:
from django.forms import inlineformset_factory
ImageFormSet = inlineformset_factory(Person, Image, fields=('image',))
def my_view(request):
form = PersonForm(request.POST or None)
if form.is_valid():
new_person = form.save()
formset = ImageFormSet(request.POST or None, request.FILES or None, instance=new_person)
if formset.is_valid():
formset.save()
return redirect('persons:main')
else:
formset = ImageFormSet(request.POST or None, request.FILES or None)
return render(request, 'my_template.html', {'formset': formset, 'form': form})
In my_template.html
:
<form action="" method="post" enctype="multipart/form-data">
{{ form.as_p }}
{{ formset.management_form }}
{% for frm in formset %}
{{ frm.as_p }}
{% endfor %}
<input type="submit" value="Create">
</form>
Upvotes: 1