Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Django – uploading files to inline formset

I’m trying to make inline form by using inlineformset_factory but my Image object is not getting saved

models:

class Product(models.Model):
    name = models.CharField(max_length=200)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    availability = models.IntegerField()
    price = models.DecimalField(max_digits=5, decimal_places=2)

    def __str__(self):
        return self.name

class Image(models.Model):
    file = models.ImageField(upload_to="products_images/", default="static/default.png")
    uploaded = models.DateTimeField(auto_now_add=True)
    product = models.ForeignKey(Product, on_delete=models.CASCADE)

views:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

def CreateNewProductView(request):
    context = {}
    ProductObj = None
    form=ProductForm()
    
    if request.method=='POST':
        form = ProductForm(request.POST)
        if form.is_valid():
            ProductObj = form.save()
            print('form is valid, product has been created')
        else:
            print("form is not valid")
        
    ImageFormset = inlineformset_factory(Product, Image, fields=('file',), extra=1, can_delete=False)


    if request.method=='POST':
        formset = ImageFormset(request.POST, request.FILES, instance=ProductObj)
        if formset.is_valid():
            formset.save()
            print('formset is valid, product has been created')
        else:
            print("formset is not valid")
    else:
        formset = ImageFormset(instance=ProductObj)

        
    if form.is_valid() and formset.is_valid():
        return redirect('home')

    context = {'form': form, 'formset':formset}
    return render(request, 'Ecommerce/test.html', context)

template test.html

{% extends 'base.html' %}
{% block content %}
    <form method="POST" action="" id="image-form" style="padding-top:10px;">
        
        {% csrf_token %}
        {{form.as_p}}
        {{formset}}
        {{formset.management_form}}
        <button type="submit">submit</button>
    </form>
{% endblock content %}

In console I can see "formset is valid, product has been created"
When I printed (request.FILES) i saw <MultiValueDict: {}>. Should it be like that ? In django admin pannel there is no Image objects
What am I doing wrong ?

>Solution :

Add this to your HTML form tag to send files to the server:

enctype="multipart/form-data"

Easy to forget.

Your form will then look like:

    <form method="POST" enctype="multipart/form-data" action="" id="image-form" style="padding-top:10px;">
        ...

Link to Django-docs

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading