[Answered ]-Angular -Js $http.post not working in django

2๐Ÿ‘

โœ…

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 ๐Ÿ™‚

๐Ÿ‘คJohn Moutafis

Leave a comment