简体   繁体   中英

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.

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']

You have some problems in your view.py code.

  1. You need to create a new object in your database from the request data
  2. 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.

  3. Also your CardForm should be defined as follows:

     class CardForm(forms.ModelForm): class Meta: model = Card fields = ('content',) 
  4. 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 :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM