I
I
Ilya Oskin2016-07-28 21:19:41
Django
Ilya Oskin, 2016-07-28 21:19:41

How to write a view to submit form data to it?

Hello! I am making a SPA application with Django + Angular. The task was to make a feedback form in order to further send data from it to Django via Angular's $http service, i.e. so that the page does not reload when sent.
First I tried to implement the form without Angular, with the following view:

def new_message(request):
    if request.method == 'POST':
        form = MessageForm(request.POST)
        if form.is_valid():
            form.save()

    form = MessageForm()
    return render(request, 'main/extra.html', {"form": form})

Everything worked fine, but when I connected Angular, problems started: It should send the message object in json form, but instead, due to the fact that the controller returns , the extra.html page gets into the message object, instead of the data from the form, if you remove render (), then Django will throw an errorrender(request, 'main/extra.html', {"form": form})
var app = angular.module('uniApp', ['ngRoute']);

angular.
  module('uniApp').
  config(['$locationProvider', '$routeProvider',
    function config($locationProvider, $routeProvider) {
      $locationProvider.html5Mode(true);
      $routeProvider.
        when('/', {
          controller : 'mainCtrl',
          templateUrl : 'media/views/main.html'
        }).
        when('/case/:id', {
          controller : 'detailCtrl',
          templateUrl : 'media/views/detail.html'
        }).
        otherwise('/');
    }
  ]);

app.controller('mainCtrl', function ($scope, $http) {
  $http.get('/api/v0/cases/').success(function(data){
    $scope.cases = data;
  });
});
app.controller('detailCtrl', function($scope, $http, $routeParams) {
  var cid = $routeParams["id"]
  $http.get('/api/v0/cases/' + cid + '/').success(function(data){
    $scope.case = data;
  });
});
app.controller('formCtrl', function($scope, $http) {
  $scope.save = function(message, messageForm) {
    console.log($scope.message)
    if (messageForm.$valid){
      $http.post('/message/', message).success(function(message){
        console.log(message)
      });
    }
    else {
      console.log('error')
    }
  };
});

It is clear that the usual view is not suitable for this task, the question is how to implement such functionality?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
sim3x, 2016-07-29
@sim3x

request.is_ajax
return JsonResponse
and in general django is paired with angular via https://github.com/tomchristie/django-rest-framework

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question