Django submit the form without updating the page

advertisements

I'm using Django-Angular and trying to post a form and obtain data in back-end..I'm able to achieve this but found that the page is reloading while saving the form. How can we achieve the same without page render?

forms.py

def home(request):
    if 'application/json' in request.META['CONTENT_TYPE']:
        print 'hi'
        print request.body

    return render(request, 'home.html', {})

home.html

<form name="indexForm" ng-submit="submitForm()">

    <div class="form-group">
        <label>File Path</label>
        <input type="text" name="path" class="form-control" ng-model="file.path">
    </div>
    <div class="form-group">
        <label>File Name</label>
        <input type="text" name="file_name" class="form-control" ng-model="file.file_name">
    </div>
    <div class="form-group">
        <label>ext</label>
        <input type="text" name="ext" class="form-control" ng-model="file.ext">
    </div>
    <button type="submit" class="btn btn-primary">Submit</button>

</form>

script

$scope.submitForm = function() {
    console.log('from submit')
    $http({
        url: 'http://127.0.0.1:8000/',
        data: $scope.file,
        method: 'POST',
        headers: {
            'X-CSRFToken': $cookies['csrftoken']}
    })
    }

Please let me know code above is correct way of posting data? How can we post data from angular to backend(django) without page refresh

Thanks in advance...Any help is much appreciated


In your home request you should not render the page again, but rather return a string or some JSON to the client. If you are using a newish version of django you can do something like this:

from django.http import JsonResponse

def home(request):
if 'application/json' in request.META['CONTENT_TYPE']:
    print 'hi'
    print request.body
    return JsonResponse({'foo':'bar'})

return render(request, 'home.html', {})