CSRF验证失败。请求中止

时间:2013-08-26 12:13:44

标签: python django

我有一个代码,CSRF验证失败,请求中止。 形式:

<form method="POST" action="/jobb/" class="form-horizontal" id="jobform" name="jform" enctype="multipart/form-data" >{% csrf_token %}

在views.py

@csrf_exempt
def jobform(request):
    if request.method == 'POST':
        getintable = job(app_id = request.POST['jobid'],start_on = request.POST['starton'], end_on = request.POST['endon'],timeframe = request.POST['timeframe'],odeskid = request.POST['odeskid'],hourlyrate = request.POST['hourlyrate'],assigne = request.POST['assigne'],clientid = request.POST['clientid'])
        getintable.save()
        return render_to_response('jobsform.html')
    else:
        return render_to_response('interviewform.html')

2 个答案:

答案 0 :(得分:1)

您收到此错误是因为您没有返回RequestContext实例。要解决此问题,您可以使用Suhil建议的render shortcut;或者您可以将请求上下文作为第三个参数传递给render_to_response

此外,你真的应该使用ModelForm,它可以自动化很多可以编写的样板代码。

以下是您的代码的样子:

您可以将此代码放在名为forms.py的文件中,该文件与views.py位于同一目录中:

from myapp.models import Job

class JobForm(forms.ModelForm):
    class Meta:
        model = Job

views.py中,您可以执行以下操作:

from django.shortcuts import render, redirect

from myapp.forms import JobForm

def jobform(request):
    ctx = {'form': JobForm(request.POST or {})}
    if request.method == 'POST':
        if form.is_valid():
           form.save()
           return redirect('/some/url')
        else:
           return render(request, 'interviewform.html', ctx)
    else:
        return render(request, 'interviewform.html', ctx)

interviewform.html

<form method="POST"
      class="form-horizontal"
      id="jobform" name="jform" enctype="multipart/form-data">
      {% csrf_token %}
      {{ form }}
      <button type="submit" class="btn btn-primary"></button>
</form>

答案 1 :(得分:0)

尝试使用渲染,你甚至不需要csrf_exempt装饰器。你在模板({% csrf_token %})中添加了csrf令牌:

from django.shortcuts import render

def jobform(request):
    if request.method == 'POST':
        getintable = job(app_id = request.POST['jobid'],start_on = request.POST['starton'], end_on = request.POST['endon'],timeframe = request.POST['timeframe'],odeskid = request.POST['odeskid'],hourlyrate = request.POST['hourlyrate'],assigne = request.POST['assigne'],clientid = request.POST['clientid'])
        getintable.save()
        return render(request,'jobsform.html')        
    return render(request,'interviewform.html')