6

I am attempting to create a page that includes two forms: one that is visible when the page loads (a signin form), and a second that appears in a modal if the user clicks a button (a signup form).

I am using Django, and, although I am still figuring out how I will handle these forms, my largest concern is how the CSRF token will play into all of this. For example, should I use {% csrf_token %} inside of only one of my <form></form> tags, or should I place it in both?

Further, if I do use it in both forms, will this affect my POSTS to the server in any way? Currently, I am taking the data in a form (depending on which submit button is clicked) and POSTing this way:

var data={
    'username':$('#username').val(), 
    'password':$('#password').val(),
    'csrfmiddlewaretoken': '{{ csrf_token }}'
}

$.post("/", signin_data);
4

1 回答 1

5

csrf_token应该放在两种形式中,只要两者都在服务器端通过GETor访问POST,是的,您可以在两种形式中使用相同csrf_token的形式而不会出现任何问题。

你可以做类似的事情

<form action="." >{% csrf_token %}
    {{form1.as_p}}
</form>

当你这样做时data=form.serialize(),令牌会在 ajax 请求csrf中自动序列化。data

多个{% csrf_token %}工作的原因是因为令牌所做的所有事情都是为验证表单请求来自有效(未篡改)用户会话提供信息。

于 2013-07-09T04:02:04.643 回答