在赋值之前引用成功变量消息

时间:2014-04-21 15:30:25

标签: django forms

我试图在表单上发布一些数据后显示成功消息。

def addcostumer(request):
    form = CostumerForm(request.POST or None)
    if form.is_valid():
        save_it = form.save(commit=False)
        save_it.save()
        message = "Data sent!"

    return render_to_response('nuevocliente.html', {'message': message}, context_instance=RequestContext(request),)

1 个答案:

答案 0 :(得分:1)

您需要检查请求是否确实是POST,然后在提交的form确实有效时显示消息。

此外,您似乎忘记在上下文中发送实际表单。

def addcostumer(request):
    form = CostumerForm()
    message = None #Set the message to None by default

    if request.method == 'POST':
        form = CustomerForm(request.POST)
        if form.is_valid():
            save_it = form.save(commit=False) 
            save_it.save()
            message = "Data sent!" #Set message if the object was saved successfully.

    return render_to_response('nuevocliente.html', {'message': message, 'form': form}, context_instance=RequestContext(request))