0

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.

1 Answer 1

1

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>
Sign up to request clarification or add additional context in comments.

4 Comments

In your code, if the PersonForm is not valid, the view will not return a HttpResponse object. It will return None instead. How do I deal with this case?
@Flux oops, sorry it just mistake with indent. Check updated answer.
But then, if form.is_valid() returns false, the variable formset may not be defined when you try to render the template.
@Flux to avoid this you could just add else block.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.