javascript - Angular -Js $http.post 在 Django 中不起作用

标签 javascript python angularjs django

我刚刚启动了 Django 并且我正在尝试实现 Angular $http.post 方法以将表单数据发布到我的 Django 数据库,我进一步的计划是更新 View 以显示结果而不刷新页面。所以呢我想在 Django 数据库中发布数据,然后我的 View 函数将返回一个 jsonresponse,我可以使用 $http.get 方法更新 View 。

但我遇到的问题是,每当我发布数据时,它都无法发布数据并返回一个空的 json 响应。

这是我正在处理的代码:-

urls.py

from django.conf.urls import url
from . import views
app_name='demo'
urlpatterns=[
    url(r'^$',views.index,name="index"),
    url(r'^add_card/$',views.add_card,name="add_card")

]

views.py

from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
from .forms import CardForm
from .models import Card
# Create your views here.

def add_card(request):
    saved = False
    if request.method == 'POST':
        #print('hi')
        form = CardForm(request.POST)
        #print('hi')
        if form.is_valid():
            #print('hi')
            card = Card()
            #print('hi')
            card.content = form.cleaned_data['content']
            #print('hi')
            saved = True
            card.save()
            #print('hi')
        return JsonResponse({'body':list(q.content for q in Card.objects.order_by('-id')[:15])})

    else:
        return HttpResponse(
            json.dumps({"nothing to see": "this isn't happening"}),
            content_type="application/json"
        )

def index(request):
    return render(request,'demo/index.html',{'form':CardForm()})

controller.js

var nameSpace = angular.module("ajax", ['ngCookies']);

nameSpace.controller("MyFormCtrl", ['$scope', '$http', '$cookies',
function ($scope, $http, $cookies) {
    $http.defaults.headers.post['Content-Type'] = 'application/json';
    // To send the csrf code.
    $http.defaults.headers.post['X-CSRFToken'] = $cookies.get('csrftoken');

    // This function is called when the form is submitted.
    $scope.submit = function ($event) {
        // Prevent page reload.
        $event.preventDefault();
        // Send the data.
        var in_data = jQuery.param({'content': $scope.card.content,'csrfmiddlewaretoken': $cookies.csrftoken});
        $http.post('add_card/', in_data)
          .then(function(json) {
            // Reset the form in case of success.
            console.log(json.data);
            $scope.card = angular.copy({});
        });
    }
 }]);

我的模型.py:-

from django.db import models

# Create your models here.
class Card(models.Model):
    content = models.TextField()
    date = models.DateTimeField(auto_now_add=True)
    def __str__(self):
        return self.content

我的forms.py-

from django import forms
from .models import Card

class CardForm(forms.ModelForm):
    class Meta:
        model = Card
        fields = ['content']

最佳答案

您的 view.py 代码中存在一些问题。

  1. 您需要根据请求数据在您的数据库中创建一个新对象
  2. 您需要将新数据作为响应返回

    if form.is_valid():
        new_content = form.cleaned_data['content']
        card = Card.objects.create(content=new_content)
        return JsonResponse(
               list(Card.objects.all().order_by('-id').values('content')[:15]),
               safe=False
        )
    

    在根据提供的内容在该表中创建新对象后,应该返回 Card 表中前 15 个对象的 content 值列表,如果您表格有效。

  3. 此外,您的 CardForm 应定义如下:

    class CardForm(forms.ModelForm):
        class Meta:
            model = Card
            fields = ('content',)
    
  4. 最后,你的$http.post调用是异步的,也就是说当到达.then时,有一个概率(几乎是确定的)发布请求尚未解决,因此您的 json.data 为空。解决这个问题:

    $http.post('add_card/', in_data)
        .then((json) => {
            // Reset the form in case of success.
            console.log(json.data);
            $scope.card = angular.copy({});
    });
    

    关于异步到同步调用的更好的阅读和解决方案是:ES6 Promises - Calling synchronous functions within promise chain , How do you synchronously resolve a chain of es6 promises?Synchronous or Sequential fetch in Service Worker

祝你好运:)

关于javascript - Angular -Js $http.post 在 Django 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43473374/

相关文章:

javascript - 如何在 ReactJS 上以 JSON 格式从 API 获取数据并填充下拉列表

javascript - 如何使用 jQuery UI 工具提示在打开时更改工具提示颜色?

Windows 64 上的 Python、GEOS 和 Shapely

AngularJS - 模板不起作用

JavaScript 到 Java 到 MYSQL 查询

php - 是否可以使用 JS 显示已由 php mysql 填充的新下拉列表?

javascript - 如何使用jquery将ajax数据加载到div中?

python - 打开 'at' 标志我搞砸了吗?

python - 未知编码 : idna in Python Requests

javascript - AngularJS 如何在函数之外正确调用函数