Django的使用记录_2


=Start=

缘由:

记录在使用Django的过程中碰到的各种问题,方便以后参考。

正文:

1.碰到「CSRF verification failed. Request aborted.」怎么办?
$.ajax({
    data: {
        somedata: 'somedata',
        moredata: 'moredata',
        csrfmiddlewaretoken: '{{ csrf_token }}'
    },
    ...
})
// http://stackoverflow.com/questions/5100539/django-csrf-check-failing-with-an-ajax-post-request

&

<form action="" method="post">{% csrf_token %}

// https://docs.djangoproject.com/en/1.8/ref/csrf/#how-to-use-it
2.在Django应用中如何返回json数据?
response_data = {}
response_data['result'] = 'error'
response_data['message'] = 'Some error message'

在 Django 1.7 之前的版本中,可以使用下面的方法:

import json
from django.http import HttpResponse

return HttpResponse(json.dumps(response_data), content_type="application/json")

对于 Django 1.7 之后的版本,可以使用Django官方提供的方法:

from django.http import JsonResponse
return JsonResponse({'foo':'bar'})
3.待添加

……

=END=


《“Django的使用记录_2”》 有 11 条评论

  1. 平时可能需要用Python写一个Web Server接收数据,原生的 BaseHTTPServer 和 SimpleHTTPServer 应该是无法处理POST请求,所以考虑借用 Django 实现这个功能,比较轻松。但是高版本的Django对于POST请求会有CSRF校验,这使我在命令行上用curl进行测试不太方便,所以可以临时先用一个装饰器禁用掉CSRF校验:
    `
    from django.views.decorators.csrf import csrf_exempt
    from django.http import HttpResponse

    @csrf_exempt #增加的装饰器
    def my_view(request):
    return HttpResponse(‘Hello world’)
    `
    https://stackoverflow.com/questions/21743232/django-returning-403-error-csrf-cookie-not-set

  2. django-ajax-post请求报错
    https://hhyo.github.io/2017/09/27/django-ajax-post/

    django全局异常捕获保存和输出,logger配置
    https://hhyo.github.io/2018/04/16/django-traceback/

    django获取from表单multiple-select的值
    https://hhyo.github.io/2018/04/16/django-multiple-selecter/

    django+gunicorn+nginx部署时,nginx反向代理非80端口时重定向报错
    https://hhyo.github.io/2018/04/16/django-nginx-gunicorn/

    django-debug设置为False后静态文件获取404
    https://hhyo.github.io/2017/11/30/django-debug/

    django时间格式化显示
    https://hhyo.github.io/2017/11/28/django-date-format/

回复 a-z 取消回复

您的电子邮箱地址不会被公开。 必填项已用*标注