我刚刚开始使用Django和我试图实现$ http.post方法的角度来将表单数据发布到我的Django数据库,我的进一步计划是更新视图以显示结果而不刷新页面。所以我想在django db中发布数据然后我的view函数将返回一个jsonresponse,发布的数据可用于使用$ http.get方法更新视图。
但是问题出现在我身上的每当我发布数据时都无法发布数据并返回空的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({});
});
}
}]);
我的models.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']
答案 0 :(得分:2)
您的view.py
代码存在一些问题。
您需要将新数据作为回复
返回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
)
如果您的表单有效,那么在通过提供的内容在该表中创建新对象后,应返回content
表中前15个对象的Card
值列表。
此外,您的CardForm
应定义如下:
class CardForm(forms.ModelForm):
class Meta:
model = Card
fields = ('content',)
最后,您的$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