Python 实现js与Django后台的前后台交互

背景:

python小白准备用python写个后台项目,前后台交互的时间遇到一些问题,记录如下:

代码结构:

目录结构:

Python 实现js与Django后台的前后台交互_第1张图片

前台请求:



urls.py中配置:

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^login/', views.login),
    url(r'^regist_url/', views.regist_url),
]

在views.py中定义regist_url方法:

def regist_url(request):
    data = json.loads(request.body)
    username = data["username"]
    password = data["password"]
    print "用户名:"+username
    print "密码:"+password
    return HttpResponse(request.body)

启动项目,执行/regist_url/请求。

后台打印:

Python 实现js与Django后台的前后台交互_第2张图片

同时return HttpResponse(request.body)返回到前台,前台打印:

Python 实现js与Django后台的前后台交互_第3张图片

这样,前后台交互就好了!

注意:

1.Django对Post请求有中间件防御机制csrf,会出现403 Forbidden错误

Python 实现js与Django后台的前后台交互_第4张图片

有两种解决方法:

(1):直接在settings.py中将django.middleware.csrf.CsrfViewMiddleware全局注释,

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    #'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

(2).或者对views.py的方法上新增@csrf_exempt注解,去除csrf防御

from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def regist_url(request):
    data = json.loads(request.body)
    username = data["username"]
    password = data["password"]
    print "用户名:"+username
    print "密码:"+password
    return HttpResponse(request.body)

2.请求报错

RuntimeError: You called this URL via POST, but the URL doesn't end in a slash and you have APPEND_SLASH set. Django can't redirect to the slash URL while maintaining POST data. Change your form to point to 127.0.0.1:8000/regist_url/ (note the trailing slash), or set APPEND_SLASH=False in your Django settings.

Python 实现js与Django后台的前后台交互_第5张图片改为Python 实现js与Django后台的前后台交互_第6张图片,加上“/”

你可能感兴趣的:(问题汇总,其他)