Home > OS >  Django form and formset are not valid
Django form and formset are not valid

Time:08-29

I'm trying to make a view containing one form and one formset but something does not work. both form and formset after checking if .is_valid returns false. I do not really undersand why it is like that

def ProductCreateView(request):

    context = {}
    created_product = None
    form = ProductForm()
    if request.method == 'POST':
        form = ProductForm(request.POST)
        if form.is_valid():
            created_product = form.save()
            print("Successfully created new product: {}".format(created_product))
        else:
            print("form is not valid")
            #print(request.POST) returns csrfmiddlewaretoken ...
            #print(request.FILES) returns file : inmemoryuploadedfile ...
            #print(list(request.POST.items()))
    context['form'] = form

    formset = ProductPhotoInlineFormset()
    if request.method=='POST':
        formset = ProductPhotoInlineFormset(request.POST or None, request.FILES or None, instance=created_product)
        if formset.is_valid():
            created_images = formset.save()
            print("Successfully created new imagest: {}".format(created_images))
        else:
            print("formset is not valid")
    context['formset'] = formset

    return render(request, "Ecommerce/create_product_test.html", context)

my template - create_product_test.html

{% extends 'base.html' %}
{% block content %}
    <div id="alert-box">
        
    </div>

    <div id="image-box" >
        
    </div>
    <div id="image-box"></div>

    <div >
        
        <button  id="confirm-btn">confirm</button>
        <form method="POST" enctype="multipart/form-data" action="" id="image-form">
            {% csrf_token %}
            <div>
                {{form}}
                
                {{formset.management_form}}
                {{formset.as_p}}
                
            </div>
        
            
        </form>
        
    </div>

    
{% endblock content %}

forms.py file

ProductPhotoInlineFormset = inlineformset_factory(
    Product,
    Photo,
    fields=('file',),
    form=PhotoForm,
    extra=1,

    )

where is the problem ?

CodePudding user response:

You can find out what's wrong with the form with:

print(form.errors)
print(form.non_field_errors())

and for a formset:

print(formset.errors)
print(formset.non_form_errors())

This way, you can easily find out why the form is not valid.

  • Related