0

am using AngularJS/Django/Python for my project. One of my page taking inputs from the users through input fields and radio buttons and need to store those values to the database. How can I do that by using AngularJS? Thanks in advance.

html and JS:

{% extends "base.html" %}
{% load static %}
{% block stylesheets %}
<!--<html ng-app="ui.bootstrap.demo">-->
<link href="{% static 'bootstrap-v3.3.2/css/bootstrap.min.css' %}" rel="stylesheet" xmlns="http://www.w3.org/1999/html">
<link href="{% static 'bootstrap-v3.3.2/css/bootstrap-theme.min.css' %}" rel="stylesheet">
<link href="{% static 'css/screen.css' %}" rel="stylesheet">
<link href="{% static 'css/project.css' %}" rel="stylesheet">
<link href="{% static 'css/jquery-ui.css' %}" rel="stylesheet">
<link href="{% static 'css/ss.css' %}" rel="stylesheet">
<link href="{% static 'css/check_binning.css' %}" rel="stylesheet">


{% endblock %}

{% block mainbody %}
{%  include 'orc_navigation_section.html' %}

<br><br>
<h1> <b>Check Binning Setup</b></h1><br>
<div class="well">
        <div class="well" ng-controller="LayerCtrl">
            <table>
                <tr>
                    <td>
                        <div class="input-group">
                            <span class="input-group-addon">Fab</span>
                            <select class="form-control" name="fab">
                                {% for f in fab %}
                                <option value="{{f}}">{{f}}</option>
                                {% endfor %}
                            </select>
                        </div>
                    </td>

                    <td>
                        <div class="input-group">
                            <span class="input-group-addon">Technode</span>
                            <select class="form-control" ng-model="selected_technode" ng-options="l.value as l.label for l in technodes"></select>
                        </div>
                    </td>

                    <td>
                        <div class="input-group">
                            <span class="input-group-addon">Layer</span>
                            <!--<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">-->
                            {%verbatim%}
                            <!--<select class="form-control"  name="layer" >-->
                            <!--<option ng-repeat="l in layer_list" value="{{l}}">{{l}}</option>-->
                            <!--</select>-->
                            <select class="form-control" ng-model="selected_layer" ng-options="l as l for l in layerlist"></select>
                            {%endverbatim%}
                        </div>
                    </td>
                </tr>
            </table>
        </div>

        <div><h3>ORC binning setup history:</h3></div>
        <br/><br/>

        <!--Check fields and Radio Buttons-->
        <div ng-controller="AlertDemoCtrl">

            <table class="table">

                {% verbatim %}

                <tr>

                    <td class="input-group" ng-repeat="(k,v) in alerts">

                        <span class="input-group-addon" ng-hide="v.hide">Check {{ k }}</span>
                    <span ng-hide="v.hide">
                    <input type="text" class="form-control" placeholder="Add Check here" ng-model="v.input">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    <b>Functional check</b>&nbsp;&nbsp;&nbsp;<input type="radio" name="{{ k }}" value="fc" ng-model="v.props">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    <b>CFM issue</b>&nbsp;&nbsp;&nbsp;<input type="radio" name="{{ k }}" value="cfm" ng-model="v.props">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    <b>Defect risk</b>&nbsp;&nbsp;&nbsp;<input type="radio" name="{{ k }}" value="dr" ng-model="v.props">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                        <a type="reset" ng-click="reset()">
                            <span class="glyphicon glyphicon-repeat"></span>
                        </a>&nbsp;&nbsp;&nbsp;

                        <a href="" ng-click="remove(v)">
                            <span class="glyphicon glyphicon-trash"></span></a>
                        </span>
                        {% endverbatim %}
                <tr>
                    <td>
                        <button type="button" class='btn btn-info' ng-click="addAlert()">
                            <span class="glyphicon glyphicon-plus"></span>
                            &nbsp;Add Check</button>
                        <button type="reset" ng-click="reset()" class="btn btn-danger">
                            <span class="glyphicon glyphicon-repeat"></span>
                            &nbsp;Reset All</button>
                    </td>
                </tr>
            </table>
        </div>
        <table class="table">
            <!--IMPORT FILE-->
            <tr>
                <td>
                    <div style="position:relative;">
                        <a class='btn btn-primary' href='javascript:;' disabled>
                            Choose File...
                            <input type="file" style='position:absolute;z-index:2;top:0;left:0;
                        filter: alpha(opacity=0);-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";
                        opacity:0;background-color:transparent;color:transparent;' name="file_source" size="40"  onchange='$("#upload-file-info").html($(this).val());'>
                        </a>
                        &nbsp;
                        <span class='label label-info' id="upload-file-info"></span>
                        <button ng-click="uploadAttachFile()" class="btn btn-small btn-default" id="uploadfile" name="uploadfile" disabled>
                            <span class="glyphicon glyphicon-cloud-upload"></span>&nbsp;Import File</button>
                    </div>
                </td>
            </tr>

            <!--ADD COMMENTS-->

            <tr>
                <td>
                    Add Comments*<div class="span5"><textarea name="bugnote_text" placeholder="Add comments here (max=600 characters)" rows="3" class="span10 ng-pristine
                ng-valid ng-valid-maxlength" ng-maxlength="600"></textarea></div>
                </td>
                <td>
                    Add ECN*<input type="text" class="form-control" placeholder="Add ECN here">

                </td>
            </tr>
            <form ng-submit="submit()" ng-controller="ExampleController">
                <tr>
                    <td>
                        <button type="submit" id="submit" class="btn btn-small btn-success"><span class="glyphicon glyphicon-pencil"></span>&nbsp;Update check DB</button>
                        <button class="btn btn-small btn-grey"><span class="glyphicon glyphicon-remove"></span>&nbsp;Cancel</button>
                    </td>

                </tr>
            </form>
            <!--<tr><td><div ng-controller="ModalDemoCtrl">-->
            <!--<script type="text/ng-template" id="orc_enable.html">-->
            <!--</script>-->
            <!--<button type="button" class="btn btn-default" ng-click="open('lg')">Pop-up</button>-->
            <!--</div></td></tr>-->
        </table>
</div>

<script>
  angular.module('submitExample', [])
    .controller('ExampleController', ['$scope', function($scope) {
      $scope.list = [];
      $scope.text = 'hello';
      $scope.submit = function() {
        if ($scope.text) {
          $scope.list.push(this.text);
          $scope.text = '';
        }
      };
    }]);
</script>

{% endblock %}

The .js file:

{% block extrascript %}


{{ ngapp }}.controller("LayerCtrl", function ($scope, $http, $resource){

  var layerresource_url = $resource("{% url 'api_dispatch_list' 'v1' 'layer' %}");

  $scope.technodes = [
     {'value': 22, 'label': 22},
     {'value': 28, 'label': 28},
  ];

  console.log('initializing....')

  $scope.$watch('selected_technode', function () {
         <!--alert($scope.selected_technode);-->
         $scope.update_layer();
  });

  $scope.update_layer = function(){
    console.log('Stage1: Initializing Primary Data... ');
    layerresource_url.get({techtype__contains: $scope.selected_technode, limit:1500},
      function(data){
        $scope.layerlist = data['objects'][0]['layer'];
        console.log($scope.layerlist);
      },function(data, status){
        console.log('Stage1: Internal error while loading initial data:'+status );
        alert('internal error');
      }
    );
  };
});

{{ ngapp }}.controller("AlertDemoCtrl", function ($scope, $http, $resource){

  $scope.alerts = [];

  $scope.addAlert = function() {
    $scope.alerts.push({msg: 'Another alert!', props : 0, input : ""});
  };

  $scope.closeAlert = function(index) {
    $scope.alerts.splice(index, 1);
  };

  $scope.reset = function() {
    angular.forEach($scope.alerts, function(v){
    v.input = "";
    v.props = 0;
    });
  };

  $scope.remove = function(v){
    v.hide = 1;
  }

  $scope.reset();
});

{% endblock %}

and my view.py

class CheckBinningView(JSONResponseMixin, ListView):

    template_name = "orc_enable.html"
    model = OrcRecord

    def get_context_data(self, *args, **kwargs):
        context = super(CheckBinningView, self).get_context_data(*args, **kwargs)
        fab = GroupProfile.objects.get(id=self.request.session['ACL_gid']).fab

        gp = GroupProfile.objects.get(id=self.request.session['ACL_gid'])
        layer = []
        technode = []
        for l in self.model.objects.raw('SELECT distinct layer, id FROM orc_orcrecord GROUP BY layer'):
            layer.append(l.layer)

        if fab == "ALL":

            SQL = "SELECT distinct process_id, id FROM orc_orcrecord GROUP BY process_id"
        else:
            SQL = "SELECT distinct process_id, id FROM orc_orcrecord \
                   WHERE process_id LIKE '0" + fab +"%%' or process_id LIKE '" + fab + "%%' GROUP BY process_id"

        print SQL

        for t in self.model.objects.raw(SQL):

            sql = "SELECT distinct process_id, id FROM orc_orcrecord GROUP BY process_id"
        else:
            sql = "SELECT distinct process_id, id FROM orc_orcrecord \
                   WHERE process_id LIKE '0" + fab +"%%' or process_id LIKE '" + fab + "%%' GROUP BY process_id"

        print sql

        for t in self.model.objects.raw(sql):


            try:
                technode.append(t.get_technode)
            except Exception, e:
                print e
                continue

        # for t in self.model.objects.filter(process_id__startswith=fab, is_main_record=True,
        #                                    mantis_id__isnull=False).values_list('id', flat=True).order_by('id').distinct()[:100]:
        #     technode.append(self.model.objects.get(id=t).get_technode)

        # context['technode'] = gp.technology
        context['fab'] = gp.fab
        context['technode'] = list(set(technode))
        # context['layer'] = list(set(layer))
        context['technode'] = list(set(technode))
        context['ngapp'] = "CMOD"
        return context
3
  • whats your question? Commented Sep 10, 2015 at 2:06
  • There are lots of tutorials around on how forms and form controls work in angular. Suggest you start with learning the basics of ng-model Commented Sep 10, 2015 at 2:09
  • you have a long journey.So start from client side. when you are able to send a post with the body to want save you should post another question. about python and database. Commented Sep 10, 2015 at 2:38

2 Answers 2

2

You should look in this link about forms

will give you idea about ng-model. then you go the end points, see this resource api as you are using it.

You can use easily as:

   var layerresource_url = $resource("{% url 'api_dispatch_list' 'v1' 'layer' %}");
   layerresource_url.field1 = "teste";
   layerresource_url.field2 = true;
   layerresource_url.field1.$save();
   //will make a post to the URL passed in $resource

If you want to some customization:

   var layerresource_url = $resource("{% url 'api_dispatch_list' 'v1' 'layer' % , 
                                      {},{ save:{method:'POST'}}
                                      }");

so you can just use like:

  layerresource_url.save(model)

please read the link about resources.

you also have to setup the server side to accept the post.

Sign up to request clarification or add additional context in comments.

1 Comment

What are the changes do I need to make in my html file?
2

There's a lot of steps here.

  1. Your server (Django) needs to be available to receive the POST from the client.
  2. Your client needs to capture user input. Angular is one way, but by no means the only way. If you're struggling with this, jQuery is far more accessible. If you're going to stick with Angular, look into ng-model like Alvaro mentions.
  3. You need to make the POST. In Angular, you can do this with $resource and $http. Both are well documented. All you want is the vanilla POST, nothing fancy. Make sure the content of your form is in the body of your post.
  4. You may run into Content-Type issues... you'll probably want your ContentType set to application/json; charset=utf-8 if you're working on js.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.