在django中提交后,表单数据不会清除

时间:2016-05-10 13:23:01

标签: django django-templates

单击提交按钮后,表单数据仍然存在 我的views.py文件,

def add_prod(request):

    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)
        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()

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

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

Add_prod是模型类的名称

ProdForm是表单文件

中定义的类的名称

3 个答案:

答案 0 :(得分:0)

在表单标记中定义action参数,无需使用javascript清除表单字段

<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>

答案 1 :(得分:0)

加载页面时,您不需要渲染空表单,如else部分所述。

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)

答案 2 :(得分:0)

重定向到同一页面将解决问题

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")