Reputation: 1910
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.
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.
Here is my codes which i am working on:-
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({});
});
}
}]);
My 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-
from django import forms
from .models import Card
class CardForm(forms.ModelForm):
class Meta:
model = Card
fields = ['content']
Upvotes: 1
Views: 512
Reputation: 23134
You have some problems in your view.py
code.
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.
Also your CardForm
should be defined as follows:
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. 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? and Synchronous or Sequential fetch in Service Worker
Good luck :)
Upvotes: 2