如何排除表单上的默认值?

时间:2010-09-29 18:52:15

标签: django

我尝试了3种不同的方法,似乎没有任何效果。这是我的观点:

def my_view(request):
    if request.method == 'POST':
        form = DealershipForm(request.POST)
        if form.is_valid():
            dealership = form.save(commit=False)
            dealership.entered_by = User(id=2)
            dealership.save()
            messages.success(request, 'Dealership added.')
    else:
        form = DealershipForm()
    return response(request, template='misc/my_template.html',
                    vars={'form':form})

我也尝试在cleaned_data之后修改form.is_valid,我尝试设置initialinstance,似乎没有任何效果!

1 个答案:

答案 0 :(得分:4)

DealershipForm(request.POST, instance=Dealership(my_field="my_value"))

应该工作。

修改

修改后的代码:

def my_view(request):
    if request.method == 'POST':
        form = DealershipForm(request.POST, instance=Dealership(entred_by=User(id=2))
        if form.is_valid():
            form.save()
            messages.success(request, 'Dealership added.')
    else:
        form = DealershipForm()
    return response(request, template='misc/my_template.html',
                    vars={'form':form})

在评论后修改:

def my_view(request):
    if request.method == 'POST':
        instance = Dealership()
        instance.entered_by_id = 2
        form = DealershipForm(request.POST, instance=instance)
        if form.is_valid():
            form.save()
            messages.success(request, 'Dealership added.')
    else:
        form = DealershipForm()
    return response(request, template='misc/my_template.html',
                    vars={'form':form})