Question

I am using django 1.5.1, I have to use {% csrf_token %} on each POST to work.RequestContext did not work for me, here is my settings, view code and template code.

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
)

def show_rates(request, doc_id, template_name='rate.html'):
    doc = get_object_or_404(Doctor, id=doc_id)
    hos = doc.hospital
    docts = hos.doctor_set.all()
    page_title = doc.name
    hos_name = hos.name
    if request.method == "POST":
        postdata = request.POST.copy()
        form = AddToRateForm(postdata)
    else:
        form = AddToRateForm()
    return render(request, template_name, locals())

<form method="POST" action=".">
    {{ form.as_table }}
    <div class="row-fluid">
        <div class="span10">
        </div>
        <div class="span2">
            <button class="btn btn-block btn-primary" type="submit">Rate</button>
        </div>
    </div>
</form>

RequestContext didn't work for me. I am confused.

Was it helpful?

Solution

The MIDDLEWARE_CLASSES look's good.

This is the basic code you should use for csrf.

from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt, csrf_protect

@csrf_protect
#@csrf_exempt says to make an exemption on csrf, but of course is not secure.
#@csrf_exempt
def show_rates(request, doc_id, template_name='rate.html'):
    ...
    #I suppose  that locals() returns a dict()
    return render(request, template_name, locals())


<form method="POST" action="">
    {# Don't forget the following line #}
    {% csrf_token %}
    {{ form.as_table }}
    <div class="row-fluid">
        <div class="span10">
        </div>
        <div class="span2">
            <button class="btn btn-block btn-primary" type="submit">Rate</button>
        </div>
    </div>
</form>

OTHER TIPS

Try changing your view definition to add this decorator:

@csrf_protect
def show_rates(request, doc_id, template_name='rate.html'):

And update your return response to not include the context_instance. No need for that really.

return render_to_response(template_name, locals())
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top