我收到“ CSRF令牌丢失或不正确”的信息。

我已经检查了Stack Overflow的答案,但没有任何效果。我仔细检查了我的消息来源,真的不知道我做错了什么。它仅在用MIDDLEWARE_CLASSES注释CsrfViewMiddleware行时有效,但是我认为这是我不需要做的事情。

以下是我认为相关的代码:

settings.py

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


views.py

from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404, render_to_response
from django.template import RequestContext
from sitfin.models import Balanta, Conturi, BalantaForm, ConturiForm
from django.forms.formsets import formset_factory

def render_to_response(req,*args,**kwargs):
    kwargs['context_instance']=RequestContext(req)
    return render_to_response(*args,**kwargs)

def conturi_index(request):
    return render_to_response('sitfin/conturi_index.html',{'conturi_list':Conturi.objects.all()})

def conturi_introducere(request):
    ConturiFormSet=formset_factory(ConturiForm)
    if request.method=='POST':
        #form=ConturiForm(data=request.POST)
        formset=ConturiFormSet(request.POST, request.FILES)
        #if form.is_valid():
        if formset.is_valid():
            #new_entry=form.save()
            new_entry=formset.save()
            return HttpResponseRedirect("sitfin/conturiok")
    else:
        #form=ConturiForm()
        formset=ConturiFormSet()
    #return render_to_response('sitfin/conturi_introducere.html',{'form':form})
    return render_to_response('sitfin/conturi_introducere.html',{'formset':formset})


模板

<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8">

    <title>Conturi_introducere</title>

</head>
<body>
    <p>BAGA CONTURILE</p>
    <form action="" method="post">{% csrf_token %}
        {{ formset.management_form }}
        <!--<p><label for="id_cont">cont:</label>{{ form.cont }}</p>
        <p><label for="id_cont_debit">cont debit:</label>{{ form.cont_debit }}</p>
        <p><label for="id_cont_credit">cont credit:</label>{{ form.cont_credit }}</p>
        -->
        <table border="0">
            {% for form in formset %}
            {{ form }}
            {% endfor %}
        </table>

    <p><input type="submit" value="Submit"></p>
    </form>
</body>
</html>


我究竟做错了什么?

最佳答案

您需要确保在响应中包括RequestContext。

return render_to_response('sitfin/conturi_introducere.html',{'formset':formset},
context_instance=RequestContext(request))

10-04 11:05