简体   繁体   中英

Forbidden (CSRF token missing or incorrect.) Django + AngularJs

When I try to render to my second page in my django framework I get following error. I think that there is something wrong with my url page and views.py but can't figure it out, nothing gives a step forward..

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

this is my html/django form

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

Views.py python file:

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)

my urls:

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')

]

The issue is not with your urls or your views, but with your template. Try adding {% csrf_token %} nested under your <form></form> tags in your template.

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

See the docs for more details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM