Reputation: 1
I have just recently started learning Django. I have a problem with the password change page
403 Reason given for failure: CSRF token missing or incorrect.
My users/urls.py
urlpatterns = [
path(
'logout/',
LogoutView.as_view(template_name='users/logged_out.html'),
name='logout'
),
path(
'login/',
LoginView.as_view(template_name='users/login.html'),
name='login'
),
path(
'password_change/',
PasswordChangeView.as_view(template_name='users/password_change_form.html'),
name='password_change_form'
),
path(
'password_change/done/',
PasswordChangeDoneView.as_view(template_name='users/password_change_done.html'),
name='password_change_done'
),
...,
]
And My Form in Template starts
<form method="post"
{% if action_url %}
action="{% url action_url %}"
{% endif %}
>
{% csrf_token %}
<input type="hidden" name="csrfmiddlewaretoken" value="">
With this form, I get the error 403 and "CSRF token missing or incorrect."
Without this string everythink works
<input type="hidden" name="csrfmiddlewaretoken" value="">
everythink works. 1)Could you please explain me why? And what is it? What is the best way to use csrf? 2) I also used to write like
<form method="post" action="{% url 'users:password_change_form' %}">
But founded this example using action_url. What is action_url? What way is better?
Upvotes: 0
Views: 1156
Reputation: 65
action is the attribute in the form tag. and "action_url" is the URL(a page) it goes to when you click on submit button. So you need to define that URL there. and the correct syntax in Django is :
<form action={% url 'process' %} method="POST">
So here process is name of that URL you define in urls.py file. Something like this :
path('process/', views.process, name='process')
And in order to work you need to have that file in your app.
So in your case type the name of your URL you've defined in ulrs.py file in if condition.
Upvotes: 1
Reputation: 1
Try to use only:
{% csrf_token %}
instead of
{% csrf_token %}
<input type="hidden" name="csrfmiddlewaretoken" value="">
I'm afraid that the second line of code overwritten the csrf_token value.
Upvotes: 0