Django:POST表单需要CSRF? GET不? [英] Django: POST form requires CSRF? GET doesn't?

查看:155
本文介绍了Django:POST表单需要CSRF? GET不?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否需要使用POST方法的表单具有CSRF保护?我正在跟着一本书,代码示例抛出403错误。我做了一些搜索,似乎我需要启用所有形式的CSRF。



我的问题是:


  1. Django是否现在要求所有POST表单受到CSRF的保护?


  2. 我需要做的完成这个是添加'django.middleware.csrf.CsrfViewMiddleware',返回render_to_response(template,dictionary,context_instance = RequestContext(request),并在相应的表单中添加'{%csrf_token%}'?我在这里缺少什么? p>


当我这样做时,表单工作正常,当任何这些作品丢失时,它不能到403.我只是想要确保我正在这样做。:)



提前感谢



编辑: / p>

由于某种原因,此代码对我没有意义,但它不会返回任何错误。请忽略原始验证,因为我没有看到本书的部分,它显示了更有效的方法。

  def contact(request):
errors = []

如果request.method =='POST':
如果没有request.POST.get('subject' ,''):
errors.append('输入主题')
如果没有request.POST.get('message',''):
errors.append('输入一个消息')
如果request.POST.get('email','')和'@'不在request.POST ['email']:
errors.append('输入有效的电子邮件地址')
如果没有错误:
send_mail(
request.POST ['subject'],
request.POST ['message'],
request.POST。 get('email','noreply@example.com'),['siteownder@example.com'],)
return HttpResponseRedirect('/ contact / thanks /')

return render_to_response('contact_form.html',{'errors':errors},context_instance = RequestContext(request))



我的问题是这个视图函数的最后一行。只有在request.method!= POST时才调用它。这对我来说似乎完全错了。在做POST时不应该调用context_instance = RequestContext(request)?

解决方案

POST应该用于敏感信息,如密码和django需要使用csrf_token来保护它; GET应该用于不需要保护的书签的东西,如搜索。你正在这样做。



编辑



你不应该打电话 context_instance = RequestContext(request)当它执行 POST 时,无论请求类型如何,都应该调用它。看这样:




  • 这是一个 POST ?这意味着表单已提交。我们验证表单,如果表单可以,将用户重定向到另一个页面,或者再次向用户显示表单,并显示错误

  • 是它是一个 GET ?这意味着表单没有提交,但是其他的东西正在发生,我们不在乎(一些引用链接或其他东西)。 显示表单



斜体的操作是由上一次返回完成的,不管if。 / p>

Are forms that use the POST method required to have CSRF protection? I'm following a book and the code examples throw 403 errors. I did some searching and it seems as if I need to enable CSRF in all my forms.

My questions are:

  1. Does Django now require that all POST forms be protected from CSRF?

  2. All I need to do to accomplish this is add 'django.middleware.csrf.CsrfViewMiddleware', return render_to_response(template,dictionary,context_instance=RequestContext(request), and add '{% csrf_token %}' in the corresponding form? Am I missing anything here?

When I do this, the form works fine. When any of these pieces are missing, it fails to 403. I just want to make sure I'm doing it RIGHT. :)

Thanks in advance.

edit:

For some reason this code doesn't make sense to me but it doesnt return any error. Please ignore the primitive validation as I haven't gotten to the section of the book where it shows the more efficient way to do it yet.

def contact(request):
    errors = []

    if request.method == 'POST':
        if not request.POST.get('subject',''):
            errors.append('Enter a subject')
        if not request.POST.get('message',''):
            errors.append('Enter a message')
        if request.POST.get('email', '') and '@' not in request.POST['email']:
            errors.append('Enter a valid email address')
        if not errors:
            send_mail(
                request.POST['subject'],
                request.POST['message'],
                request.POST.get('email', 'noreply@example.com'), ['siteownder@example.com'],)
            return HttpResponseRedirect('/contact/thanks/')

    return render_to_response('contact_form.html', { 'errors': errors }, context_instance=RequestContext(request))

My issue is with the very last line of this view function. It is only called if the request.method != POST. This seems completely wrong to me. Shouldn't I be calling "context_instance=RequestContext(request)" when it's doing a POST?

解决方案

POST should be used for sensitive information, such as passwords, and django requires securing it with csrf_token; GET should be used for bookmarkable stuff which doesn't need to be secured, like searches. You ARE doing it RIGHT.

EDIT

You shouldn't be calling context_instance=RequestContext(request) when it's doing a POST, you should be calling it regardless of the request type. Look at it like this:

  • Is it a POST? this means the form was submitted. we validate the form, and redirect the user to another page if the form is OK, or show the form again to the user, with the errors.
  • Is it a GET? this means the form was not submitted, but other stuff is happening which we don't care about (some referrer link or other stuff). Show the form anyway

Actions in italic are done by the last return, regardless of the if.

这篇关于Django:POST表单需要CSRF? GET不?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆