0

我有一个代码,有一个错误,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')
4

2 回答 2

1

您收到此错误是因为您没有返回RequestContext实例。要解决此问题,您可以使用Suhail 建议的render快捷方式;或者您可以将请求上下文作为第三个参数传递给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>
于 2013-08-26T12:38:56.310 回答
0

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

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')
于 2013-08-26T12:22:38.500 回答