[英]Angular -Js $http.post not working in django
I have just started Django and what I was trying to implement $http.post method of angular to post form data to my Django database,and my further plan was to update the view to display the results without page refresh.so what i thought to post data in django db and then my view function will return a jsonresponse,of that posted data which i can use to update the view using $http.get method. 我刚开始使用Django,并尝试实现angular的$ http.post方法以将表单数据发布到Django数据库,而我的进一步计划是更新视图以显示结果而无需页面刷新。在django db中发布数据,然后我的视图函数将返回该发布数据的jsonresponse,我可以使用它使用$ http.get方法来更新视图。
But the problem is occuring with me is whenever i post data it is not able to post the data and returning an empty json response. 但是我发生的问题是,每当我发布数据时,它就无法发布数据并返回空的json响应。
Here is my codes which i am working on:- 这是我正在处理的代码:-
urls.py 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 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 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({});
});
}
}]);
My models.py:- 我的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
My forms.py- 我的forms.py-
from django import forms
from .models import Card
class CardForm(forms.ModelForm):
class Meta:
model = Card
fields = ['content']
You have some problems in your view.py
code. 您的view.py
代码中存在一些问题。
You need to return the new data as a response 您需要返回新数据作为响应
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 )
That should return a list of the content
value of your first 15 objects in your Card
table after creating a new object in that table by the content provided, IF your form is valid. 如果您的表单有效,则应该在Card
表中创建的新对象之后,在Card
表中返回前15个对象的content
值的列表。
Also your CardForm
should be defined as follows: 另外,您的CardForm
应该定义如下:
class CardForm(forms.ModelForm): class Meta: model = Card fields = ('content',)
Finally, your $http.post
call is asynchronous, which means that when the .then
is reached, there is a probability (almost a certainty) that the post request has not been resolved yet, thus your json.data
is empty. 最后,您的$http.post
调用是异步的,这意味着到达$http.post
时.then
很有可能(几乎可以确定)尚未解决发布请求,因此json.data
为空。 To solve this problem: 解决此问题的方法:
$http.post('add_card/', in_data) .then((json) => { // Reset the form in case of success. console.log(json.data); $scope.card = angular.copy({}); });
A far better read and solutions on the asynchronous-to-synchronous calls are: ES6 Promises - Calling synchronous functions within promise chain , How do you synchronously resolve a chain of es6 promises? 关于异步到同步调用的更好的阅读方法和解决方案是: ES6承诺-在promise链中调用同步函数 , 您如何同步解析es6 promise链? and Synchronous or Sequential fetch in Service Worker Service Worker中的同步和顺序获取
Good luck :) 祝好运 :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.