problems with csrf_token

折月煮酒 提交于 2019-12-02 05:45:14

问题


I'm doing wiki in django tutorial and in tutorial earlier version of django is used where csrf token is not compulsory. I've added {% csrf_token %} to the form, however I'm not sure what to do in the views. Please help.

Here's the form:

<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>

views.py:

def view_page(request, page_name):
    try:
        page = Page.objects.get(pk=page_name)
    except Page.DoesNotExist:
        return render_to_response("create.html", {"page_name" : page_name})

    return render_to_response("view.html", {"page_name" : page_name,
                                            "content" : page.content})

def edit_page(request, page_name):
    c = {}
    c.update(csrf(request))
    try:
        page = Page.objects.get(pk=page_name)
        contents = page.content
    except Page.DoesNotExist:
        content = ""
    return render_to_response("edit.html", {"page_name" : page_name,
                                            "content" : content}, c)


def save_page(request, page_name):
    content = request.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 + "/")

here's the error

TypeError at /wikicamp/start/edit/
pop expected at least 1 arguments, got 0

回答1:


You haven't quite understood step 3 here: you need to use RequestContext to ensure that the context processor is run.

return render_to_response("edit.html", {"page_name" : page_name,
                                        "content" : content},
                           context_instance=RequestContext(request))

With that, you don't need the c.update(csrf(request)) bit.




回答2:


You don't need to do anything more.

Just place {% csrf_token %} into your form and send it via POST.

All other stuff will be done inside django.middleware.csrf.CsrfViewMiddleware.

You should enable it in your settings.py (if you haven't done this):

MIDDLEWARE_CLASSES += (`django.middleware.csrf.CsrfViewMiddleware`,)
TEMPLATE_CONTEXT_PROCESSORS += (`django.core.context_processors.csrf`,)

Last line is not required if you use RequestContext (not a simple Context) in your templates (Note: render_to_response() uses Context when direct_to_template() uses RequestContext)



来源:https://stackoverflow.com/questions/7678231/problems-with-csrf-token

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!