python - 如何在 Django 1.3 中获取 POST 数据

标签 python django http-post django-1.3

嘿,我正在按照本教程学习使用 Django 制作 wiki 页面。但是,它是在 django 0.96 中制作的,而我使用的是 Django 1.3,所以有些地方有所不同。有些我已经自己修复了,但是这个我似乎无法让它工作。

我制作了一个向 View 提交数据的表单。 这是表格:

<form method="post" action"/wikicamp/{{page_name}}/save/">{% csrf_token %}
    <textarea name="content" rows="20" cols="60">{{content}}</textarea><br>
    <input type="submit" value="Save Page"/>
</form>

并且/wikicamp/{{page_name}}/save/url 重定向到 save_page View :

from django.http import HttpResponseRedirect
from django.core.context_processors import csrf

def save_page(request, page_name):
    c = {}
    c.update(csrf(request))
    content = c.POST["content"]
    try:
        page = Page.objects.get(pk=page_name)
        page.content = content
    except Page.DoesNotExist:
        page = Page(name=page_name, content=content)
    page.save()
    return HttpResponseRedirect("wikicamp/" + page_name + "/")

但是问题是我得到了这个错误:

Help

Reason given for failure:

    CSRF token missing or incorrect.


In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django's CSRF mechanism has not been used correctly. For POST forms, you need to ensure:

    The view function uses RequestContext for the template, instead of Context.
    In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL.
    If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as those that accept the POST data.

You're seeing the help section of this page because you have DEBUG = True in your Django settings file. Change that to False, and only the initial error message will be displayed.

You can customize this page using the CSRF_FAILURE_VIEW setting.

所以我通读了一些文档,比如 http://docs.djangoproject.com/en/dev/ref/contrib/csrf/#how-to-use-it .然而,我尝试这样做,但它仍然给出了同样的错误。

那么:有人知道如何使用 Django 1.3 很好地处理表单发布数据吗?

我认为这与以下内容有关: View 函数使用 RequestContext 作为模板,而不是 Context。但我现在不知道它是什么。

顺便说一句,在我的显示本地主机的 http 请求的终端中,它是这样说的:模板中使用了 {% csrf_token %},但上下文没有提供值。这通常是由于没有使用 RequestContext 造成的。

最佳答案

您需要在标签之间添加 {% csrf_token %} 模板标签并包含

   django.middleware.csrf.CsrfViewMiddleware
   django.middleware.csrf.CsrfResponseMiddleware

在应用程序 settings.py 的 MIDDLEWARE_CLASSES 中

添加一些示例发布数据处理:

这是我在 View 中使用 POST 数据的一个例子。我通常会依靠表单类通过 cleaned_data 数组进行验证。

if request.method == 'POST':
        form = ForgotPassword(data=request.POST)
        if form.is_valid():
            try:
                new_user = backend.forgot_password(request, **form.cleaned_data)
            except IntegrityError:
                context = {'form':form}
                form._errors[''] = ErrorList(['It appears you have already requested a password reset, please \
                check ' + request.POST['email2'] + ' for the reset link.'])
                return render_template(request,'passwordReset/forgot_password.html',context)
            if success_url is None:
                to, args, kwargs = backend.post_forgot_password(request, new_user)
                return redirect(to, *args, **kwargs)
            else:
                return redirect(success_url)

关于python - 如何在 Django 1.3 中获取 POST 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6020928/

相关文章:

python - 金字塔在主包之外运行测试

python - 轮廓检测 : reduce glare on image opencv/python

django - 类型对象没有属性 'get_or_create'

php - 如何编写PHP代码以执行两个功能

ios - 使用 Google Vision API 发出请求 - 收到无效的 JSON 有效负载且 INVALID_ARGUMENT

javascript - Angular.JS HTTP POST 数据未发送

python - 是否可以向 QCheckBox 添加 onclick 监听器?

python - 如何在数据框中批量滞后列

python - Django ModelForm Imagefield 上传

Django - 调试设置为 True,实际上不是