禁止(CSRF令牌丢失或不正确。)Django + AngularJs

时间:2016-09-05 22:29:31

标签: python angularjs django

当我尝试在我的django框架中渲染到我的第二页时,我得到以下错误。我认为我的网页和views.py有问题,但无法弄明白,没有任何进展。

Forbidden (CSRF token missing or incorrect.): /renderbonds
[06/Sep/2016 00:21:55] "POST /renderbonds HTTP/1.1" 403 2502

这是我的html / django表格

<form action="{% url 'renderbonds'%}" method="post" >
                <input type="submit" value="calculate bonds" class='button expand radius'/>
            </form>

Views.py python文件:

def home(request):
    tmpl_vars = {
        'all_posts': Post.objects.reverse(),
        'form': PostForm()
    }
    return render(request, 'pricing/bonds.html', tmpl_vars)

def renderbonds(request):
    """render shortcut : http://stackoverflow.com/questions/10388033/csrf-verification-failed-request-aborted"""
    if request.method == 'POST':
        post_text = request.POST.get('the_post')
        response_data = {}

        post = Post(text=post_text, author=request.user)
        post.save()

        """DATA MEEGEVEN"""
        response_data['year'] = post.year
        response_data['cashflow'] = post.cashflow

        return HttpResponse(
            json.dumps(response_data),
            content_type="application/json"
        )
    else:
        tmpl_vars = {
            'all_posts': Post.objects.reverse(),
            'form': PostForm()
        }
        return render(request,'pricing/bonds.html', tmpl_vars)

我的网址:

urlpatterns = [
    url(r'^$', views.calc,name='calc'),
    url(r'^$', views.home,'home'),
    url(r'^create_post/$',views.create_post,'create_post'),
    url(r'^renderbonds', views.home, name='home'),
    url(r'^/renderbonds', views.home, name='home'),
    url(r'^renderbonds/', views.home, name='home')

]

1 个答案:

答案 0 :(得分:2)

问题不在于您的网址或您的观看次数,而在于您的模板。尝试在模板中添加嵌套在{% csrf_token %}标记下的<form></form>

<form action="{% url 'renderbonds'%}" method="post" >
    <input type="submit" value="calculate bonds" class='button expand radius'/>
    {% csrf_token %}
</form>

有关详细信息,请参阅the docs