0

在 django 中制作视图时,是否允许将 POST 数据作为上下文传递?那是:

def view( request ):
    #view operations here
    #...

    c = Context({
        'POST':request.POST,
    })
    return render_to_response("/templatePath/", c, context_instance=RequestContext(request))

我的目标是维护已经填写的字段中的数据,而不必将它们保存到数据库中。也就是说,当您单击添加其他字段条目的选项时,您输入的数据将被保留并自动填充回表单中。我觉得这可能是草率或不安全的。有什么理由这是一种不好或不安全的技术吗?有没有更好的方法来维护数据?

4

1 回答 1

4

尽管将变量传递给模板本身并没有什么坏处request.POST,但您尝试实现的一切都已由典型的表单视图处理。如果你沿着当前的路径前进,你最终会得到一个在 Django 中处理表单的推荐方法的错误版本。

请参阅Django 文档中的在视图中使用表单。

def contact(request):
    if request.method == 'POST': # If the form has been submitted...
        form = ContactForm(request.POST) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            # Process the data in form.cleaned_data
            # ...
            return HttpResponseRedirect('/thanks/') # Redirect after POST
    else:
        form = ContactForm() # An unbound form
    return render_to_response('contact.html', {
        'form': form,
    })

在您的情况下,您需要确保重定向 URL 重定向到相同的表单。见django.shortcuts.redirect()

于 2011-06-01T14:10:53.367 回答