在Django中设置表单字段的值

时间:2015-11-05 04:59:00

标签: django

我尝试在用户提交表单后修改字段。我在网上发现了几段代码,但似乎都没有。以下是我在views.py中的尝试。任何指导都将不胜感激。

def newlisting(request):
    if request.method == "POST":
        form = ListingsForm(request.POST)
        if form.is_valid():
            form.cleaned_data['condition'] = 1   #form.condition = 1 also fails
            form.save()
            return redirect('/listings/')
        else:
            form = ListingsForm()
            return render(request, 'newlisting/newlisting.html', {'form':form})

1 个答案:

答案 0 :(得分:2)

你可以这样做:

def newlisting(request):
    if request.method == "POST":
        form = ListingsForm(request.POST)
        if form.is_valid():
            obj = form.save(commit=False)
            obj.condition = 1
            obj.save()
            return redirect('/listings/')
    else:
        form = ListingsForm()
    return render(request, 'newlisting/newlisting.html', {'form':form})