简体   繁体   中英

Django submit form without page refresh

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', {})

Replace type="submit with type="button" . Then you can just call any method in the backend with ng-click="ctrl.foo()"

At least that is what I have been doing so far. Looking at the docs however indicates that is not the issue.

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