开发者

problems with csrf_token

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


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.


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)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜