[Fixed]-Form data not clearing after submit in django

1👍

Redirecting to the same page will solve the problem

if form.is_valid():
        instance = form.save(commit=False)
        book = form.cleaned_data.get("book")
        author = form.cleaned_data.get("author")
        price = form.cleaned_data.get("price")
        cat = form.cleaned_data.get("cat")
        image = form.cleaned_data.get("image")
        instance.book = book
        instance.author = author
        instance.price = price
        instance.cat = cat
        instance.image = image
        instance.save()
        messages.add_message(request, messages.INFO,'Product Added')
        return redirect("add_prod")
👤Kiran

0👍

define action parameter in form tag and no need of javascript to clear form fields

<form method="POST" action='your url or simply place dot(.) to redirect current url' enctype="multipart/form-data" name="myform" id="myform" onSubmit="clearField();">
    {% csrf_token %}
    <table>
        {{form.as_table}}
    </table>
    <input type="submit" value="Add"/>
    <input type="reset" value="Cancel"/>    
    <input type="hidden" name="next" value="{{next}}">  
</form>
👤Pavan

0👍

When the page is loaded, you don’t need to render the empty form, as described in else part.

def add_prod(request):

if request.method == 'POST':
    form = ProdForm(request.POST or None, request.FILES or None)
    my_products = Add_prod.objects.all()
    context = {
            "form":form,
            "products":my_products
    }

    if form.is_valid():
        instance = form.save(commit=False)
        instance.book = form.cleaned_data.get("book")
        instance.author = form.cleaned_data.get("author")
        instance.price = form.cleaned_data.get("price")
        instance.cat = form.cleaned_data.get("cat")
        instance.image = form.cleaned_data.get("image")
        instance.save()

        form = ProdForm()
        messages.add_message(request, messages.INFO,'Product Added')
else:
    form = ProdForm()

return render(request,"add-prod.html",context)

Leave a comment