Django - CSRF marker generation - render_to_response vs render

I tried a simple user registration form in Django. CSRF icon is not generated when I use render_to_response

return render_to_response ('registration / register.html', RequestContext (request, {'form': RegistrationForm ()}))

where as, the CSRF token is generated when I use render

return render (request, 'registration / register.html', {'form': RegistrationForm ()})

I am doing something wrong with render_to_response

Below is the corresponding code block

views.py

 @csrf_protect def register(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): user = User.objects.create_user( username=form.cleaned_data['username'], password=form.cleaned_data['password1'], email=form.cleaned_data['email'] ) return HttpResponseRedirect('/register_success/') else: return render_to_response('registration/register.html', RequestContext(request, {'form': RegistrationForm()})) 

register.html

 {% extends "base.html" %} {% block title %}User Registration{% endblock %} {% block content %} <form method="post" action="."> {% csrf_token %} <table border="0"> {{ form.as_table }} </table> <input type="submit" value="Register" /> </form> {% endblock %} 
+5
source share
1 answer

The recommended approach is to use render instead of render_to_response . The code is simpler and the CSRF token will work because render will use the request context to render the template.

 return render(request, 'registration/register.html', {'form': RegistrationForm()}) 

Documents recommend not using render_to_response . Before Django 1.10, you can manually pass RequestContext as the third argument, but this is not possible in Django 1.10+. You use RequestContext as the second argument, which is incorrect - the second argument should be a regular dictionary.

Finally, note that you are not returning an answer when the form is invalid. You can fix this by slightly changing the code:

 if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): ... return HttpResponseRedirect('/register_success/') else: form = RegistrationForm() return render(request, 'registration/register.html', {'form': form}) 
+8
source

Source: https://habr.com/ru/post/1262678/


All Articles