sara
sara

Reputation: 169

Django - {% csrf_token %} was used in a template

After submission, I get error 400 and the following message:

create_foo.html:

<form class="modal-form" method="post" action="{% url 'create_foo'> %}">
    {% csrf_token %}    
    {{ forms }} 
</form>

create_foo.py:

@require_POST
@login_required(login_url='/login/')
def create_foo(request):
#
#
if form.is_valid():
        return HttpResponse('Success', status=201)
return JsonResponse({'html': render_to_string('create_foo.html', {'forms': form}), 'message': 'Failed'}, status=400)

I have problem when is error 400 I have a form with a message error.

I can not improve the data on the form and go on, and i have a error:

/usr/local/lib/python2.7/dist-packages/django/template/defaulttags.py:67: UserWarning: A {% csrf_token %} was used in a template, but the context did not provide the value.  This is usually caused by not
       using RequestContext.
         "A {% csrf_token %} was used in a template, but the context "

Upvotes: 1

Views: 1206

Answers (1)

Alasdair
Alasdair

Reputation: 309039

The warning is because you are not including the request when you call render_to_string. Change it to:

render_to_string('create_foo.html', {'forms': form}, request=request)

Upvotes: 3

Related Questions