Home > Software design >  Django - uploading files to inline formset
Django - uploading files to inline formset

Time:08-27

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:

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 ?

CodePudding user response:

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

  • Related