1

I am trying to add a new column to my User form called stakeholder_quadrant, but I am running into weird scenarios. 1) when I create a new item, it does not actually save the value that i enter in this field, and 2) when I go to update an item, the form pops up with stakeholder_group&stakeholder_quadrant concatenated within the stakeholder_group field and nothing in the stakeholder_quadrant field (e.g. RobD instead of stakeholder_group = Rob and stakeholder_quadrant = D).

I believe the issue is within my javascript portion... I went through this and re-created every line where there is stakeholder_group mentioned for my new stakeholder_quadrant field, but when I do that my forms don't work at all. Any idea what's causing these errors?

EDIT: I hit submit on my Add form and the page refreshes, the URL then changes to the following, no record was created, and no alert: http://127.0.0.1:7000/polls/stakeholders/?employee=aaa&description=bbb&stakeholder_group=ccc&stakeholder_quadrant=D

<script>// Create Django Ajax Call
$(document).ready(function() {
    $('form').on('submit', function(e){
    e.preventDefault();
    var employeeInput = $('input[name="employee"]').val().trim();
    var descriptionInput = $('input[name="description"]').val().trim();
    var stakeholder_groupInput = $('input[name="stakeholder_group"]').val().trim();
    var stakeholder_quadrantInput = $('input[name="stakeholder_quadrant"]').val().trim();
    if (employeeInput && descriptionInput && stakeholder_groupInput && stakeholder_quadrantInput) {
        // Create Ajax Call
        $.ajax({
            url: '{% url 'polls:crud_ajax_create' %}',
            data: {
                'employee': employeeInput,
                'description': descriptionInput,
                'stakeholder_group': stakeholder_groupInput
                'stakeholder_quadrant': stakeholder_quadrantInput
            },
            dataType: 'json',
            success: function (data) {
                if (data.user) {
                  appendToUsrTable(data.user);
                }
            }
        });
    alert(stakeholder_groupInput +","+stakeholder_quadrantInput)
    } else {
        alert(stakeholder_groupInput +","+stakeholder_quadrantInput)
        alert("All fields must have a valid value.");
    }
    $('form#addUser').trigger("reset");
    return false;
});

models

class Stakeholder(models.Model):
    employee = models.CharField(max_length=200)
    stakeholder_group = models.CharField(max_length=200)
    description = models.CharField(max_length=200)
    stakeholder_quadrant = models.CharField(max_length=200)
    def __str__(self):
        return self.stakeholder

views

class CrudView(TemplateView):
    template_name = 'polls/stakeholders.html'
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['users'] = Stakeholder.objects.all()
        return context

class CreateCrudUser(View):
    def  get(self, request):
        employee = request.GET.get('employee', None)
        description = request.GET.get('description', None)
        stakeholder_group = request.GET.get('stakeholder_group', None)
        stakeholder_quadrant = request.GET.get('stakeholder_quadrant', None)

        obj = Stakeholder.objects.create(
            employee = employee,
            description = description,
            stakeholder_group = stakeholder_group,
            stakeholder_quadrant = stakeholder_quadrant
        )

        user = {'id':obj.id,'employee':obj.employee,'description':obj.description,'stakeholder_group':obj.stakeholder_group,'stakeholder_quadrant':obj.stakeholder_quadrant}

        data = {
            'user': user
        }
        return JsonResponse(data)

class UpdateCrudUser(View):
    def  get(self, request):
        id1 = request.GET.get('id', None)
        employee1 = request.GET.get('employee', None)
        description1 = request.GET.get('description', None)
        stakeholder_group1 = request.GET.get('stakeholder_group', None)
        stakeholder_quadrant1 = request.GET.get('stakeholder_quadrant', None)

        obj = Stakeholder.objects.get(id=id1)
        obj.employee = employee1
        obj.description = description1
        obj.stakeholder_group = stakeholder_group1
        obj.stakeholder_quadrant = stakeholder_quadrant1
        obj.save()

        user = {'id':obj.id,'employee':obj.employee,'description':obj.description,'stakeholder_group':obj.stakeholder_group,'stakeholder_quadrant':obj.stakeholder_quadrant}
        data = {
            'user': user
        }
        return JsonResponse(data)

urls

urlpatterns = [
    path('stakeholders/',  views.CrudView.as_view(), name='crud_ajax'),
    path('ajax/crud/create/',  views.CreateCrudUser.as_view(), name='crud_ajax_create'),
    path('ajax/crud/update/',  views.UpdateCrudUser.as_view(), name='crud_ajax_update'),
    path('ajax/crud/delete/',  views.DeleteCrudUser.as_view(), name='crud_ajax_delete'),
]

html

<!-- Edit Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="myModalLabel">Update User</h4>
            </div>
            <form id="updateUser" action="">
                <div class="modal-body">
                    <input class="form-control" id="form-id" type="hidden" name="formId" />
                    <label for="name">employee</label>
                    <input class="form-control" id="form-employee" type="text" name="formemployee" />
                    <label for="description">description</label>
                    <input class="form-control" id="form-description" type="text" name="formdescription" />
                    <label for="stakeholder_group">stakeholder_group</label>
                    <input class="form-control" id="form-stakeholder_group" type="text" name="formstakeholder_group" />
                    <label for="stakeholder_quandrant">stakeholder_quadrant</label>
                    <input class="form-control" id="form-stakeholder_quadrant" type="text" name="formstakeholder_quadrant" />
                </div>
                <div class="modal-footer">
                    <button type="submit" class="btn btn-primary">Save changes</button>
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!--New Modal-->
<div class="modal fade" id="new" tabindex="-1" role="dialog" aria-labelledby="exampleModalLongTitle" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLongTitle">New Item</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form id="addUser" action="">
                    <div class="form-group">
                        <input class="form-control" type="text" name="employee" placeholder="employee" required>
                    </div>
                    <div class="form-group">
                        <input class="form-control" type="text" name="description" placeholder="description" required>
                    </div>
                    <div class="form-group">
                        <input class="form-control" type="text" name="stakeholder_group" placeholder="stakeholder_group" required>
                    </div>
                    <div class="form-group">
                        <input class="form-control" type="text" name="stakeholder_group" placeholder="stakeholder_group" required>
                    </div>
                    <button class="btn btn-primary form-control" type="submit">SUBMIT</button>
                </form>
            </div>
        </div>
    </div>
</div>

javascript block within the same html:

{% block javascript %}

<script>// Create Django Ajax Call
$("form#addUser").submit(function() {
    var employeeInput = $('input[name="employee"]').val().trim();
    var descriptionInput = $('input[name="description"]').val().trim();
    var stakeholder_groupInput = $('input[name="stakeholder_group"]').val().trim();
    if (employeeInput && descriptionInput && stakeholder_groupInput) {
        // Create Ajax Call
        $.ajax({
            url: '{% url 'polls:crud_ajax_create' %}',
            data: {
                'employee': employeeInput,
                'description': descriptionInput,
                'stakeholder_group': stakeholder_groupInput
            },
            dataType: 'json',
            success: function (data) {
                if (data.user) {
                  appendToUsrTable(data.user);
                }
            }
        });

    } else {
        alert("All fields must have a valid value.");
    }
    $('form#addUser').trigger("reset");
    return false;
});


// Delete Django Ajax Call
function deleteUser(id) {
  var action = confirm("Are you sure you want to delete this user?");
  if (action != false) {
    $.ajax({
        url: '{% url "polls:crud_ajax_delete" %}',
        data: {
            'id': id,
        },
        dataType: 'json',
        success: function (data) {
            if (data.deleted) {
              $("#userTable #user-" + id).remove();
            }
        }
    });
  }
}


// Create Django Ajax Call
$("form#updateUser").submit(function() {
    var idInput = $('input[name="formId"]').val().trim();
    var employeeInput = $('input[name="formemployee"]').val().trim();
    var descriptionInput = $('input[name="formdescription"]').val().trim();
    var stakeholder_groupInput = $('input[name="formstakeholder_group"]').val().trim();
    if (employeeInput && descriptionInput && stakeholder_groupInput) {
        // Create Ajax Call
        $.ajax({
            url: '{% url "polls:crud_ajax_update" %}',
            data: {
                'id': idInput,
                'employee': employeeInput,
                'description': descriptionInput,
                'stakeholder_group': stakeholder_groupInput
            },
            dataType: 'json',
            success: function (data) {
                if (data.user) {
                  updateToUserTabel(data.user);
                }
            }
        });

    } else {
        alert("All fields must have a valid value.");
    }
    $('form#updateUser').trigger("reset");
    $('#myModal').modal('hide');
    return false;
});


// Update Django Ajax Call
function editUser(id) {
  if (id) {
    tr_id = "#user-" + id;
    employee = $(tr_id).find(".useremployee").text();
    description = $(tr_id).find(".userdescription").text();
    stakeholder_group = $(tr_id).find(".userstakeholder_group").text();
    $('#form-id').val(id);
    $('#form-employee').val(employee);
    $('#form-description').val(description);
    $('#form-stakeholder_group').val(stakeholder_group);
  }
}

function appendToUsrTable(user) {
  $("#userTable > tbody:last-child").append(`
        <tr id="user-${user.id}">
            <td class="useremployee" name="employee">${user.employee}</td>
            '<td class="userdescription" name="description">${user.description}</td>
            '<td class="userstakeholder_group" name="stakeholder_group">${user.stakeholder_group}</td>
            '<td align="center">
                <button class="btn btn-success form-control" onClick="editUser(${user.id})" data-toggle="modal" data-target="#myModal")">EDIT</button>
            </td>
            <td align="center">
                <button class="btn btn-danger form-control" onClick="deleteUser(${user.id})">DELETE</button>
            </td>
        </tr>
    `);
}

function updateToUserTabel(user){
    $("#userTable #user-" + user.id).children(".userData").each(function() {
        var attr = $(this).attr("employee");
        if (attr == "employee") {
          $(this).text(user.employee);
        } else if (attr == "description") {
          $(this).text(user.description);
        } else {
          $(this).text(user.stakeholder_group);
        }
      });
}</script>

{% endblock javascript %}

javascript with stakeholder_quadrant included (not working)

{% block javascript %}

<script>// Create Django Ajax Call
$("form#addUser").submit(function() {
    var employeeInput = $('input[name="employee"]').val().trim();
    var descriptionInput = $('input[name="description"]').val().trim();
    var stakeholder_groupInput = $('input[name="stakeholder_group"]').val().trim();
    var stakeholder_quadrantInput = $('input[name="stakeholder_quadrant"]').val().trim();
    if (employeeInput && descriptionInput && stakeholder_groupInput && stakeholder_quadrantInput) {
        // Create Ajax Call
        $.ajax({
            url: '{% url 'polls:crud_ajax_create' %}',
            data: {
                'employee': employeeInput,
                'description': descriptionInput,
                'stakeholder_group': stakeholder_groupInput
                'stakeholder_quadrant': stakeholder_quadrantInput
            },
            dataType: 'json',
            success: function (data) {
                if (data.user) {
                  appendToUsrTable(data.user);
                }
            }
        });

    } else {
        alert("All fields must have a valid value.");
    }
    $('form#addUser').trigger("reset");
    return false;
});


// Delete Django Ajax Call
function deleteUser(id) {
  var action = confirm("Are you sure you want to delete this user?");
  if (action != false) {
    $.ajax({
        url: '{% url "polls:crud_ajax_delete" %}',
        data: {
            'id': id,
        },
        dataType: 'json',
        success: function (data) {
            if (data.deleted) {
              $("#userTable #user-" + id).remove();
            }
        }
    });
  }
}


// Create Django Ajax Call
$("form#updateUser").submit(function() {
    var idInput = $('input[name="formId"]').val().trim();
    var employeeInput = $('input[name="formemployee"]').val().trim();
    var descriptionInput = $('input[name="formdescription"]').val().trim();
    var stakeholder_groupInput = $('input[name="formstakeholder_group"]').val().trim();
    var stakeholder_quadrantInput = $('input[name="formstakeholder_quadrant"]').val().trim();
    if (employeeInput && descriptionInput && stakeholder_groupInput && stakeholder_quadrantInput) {
        // Create Ajax Call
        $.ajax({
            url: '{% url "polls:crud_ajax_update" %}',
            data: {
                'id': idInput,
                'employee': employeeInput,
                'description': descriptionInput,
                'stakeholder_group': stakeholder_groupInput
                'stakeholder_quandrant': stakeholder_quadrantInput
            },
            dataType: 'json',
            success: function (data) {
                if (data.user) {
                  updateToUserTabel(data.user);
                }
            }
        });

    } else {
        alert("All fields must have a valid value.");
    }
    $('form#updateUser').trigger("reset");
    $('#myModal').modal('hide');
    return false;
});


// Update Django Ajax Call
function editUser(id) {
  if (id) {
    tr_id = "#user-" + id;
    employee = $(tr_id).find(".useremployee").text();
    description = $(tr_id).find(".userdescription").text();
    stakeholder_group = $(tr_id).find(".userstakeholder_group").text();
    stakeholder_quadrant = $(tr_id).find(".userstakeholder_quadrant").text();
    $('#form-id').val(id);
    $('#form-employee').val(employee);
    $('#form-description').val(description);
    $('#form-stakeholder_group').val(stakeholder_group);
    $('#form-stakeholder_quadrant').val(stakeholder_quadrant);
  }
}

function appendToUsrTable(user) {
  $("#userTable > tbody:last-child").append(`
        <tr id="user-${user.id}">
            <td class="useremployee" name="employee">${user.employee}</td>
            '<td class="userdescription" name="description">${user.description}</td>
            '<td class="userstakeholder_group" name="stakeholder_group">${user.stakeholder_group}</td>
            '<td class="userstakeholder_quadrant" name="stakeholder_quadrant">${user.stakeholder_quadrant}</td>
            '<td align="center">
                <button class="btn btn-success form-control" onClick="editUser(${user.id})" data-toggle="modal" data-target="#myModal")">EDIT</button>
            </td>
            <td align="center">
                <button class="btn btn-danger form-control" onClick="deleteUser(${user.id})">DELETE</button>
            </td>
        </tr>
    `);
}

function updateToUserTabel(user){
    $("#userTable #user-" + user.id).children(".userData").each(function() {
        var attr = $(this).attr("employee");
        if (attr == "employee") {
          $(this).text(user.employee);
        } else if (attr == "description") {
          $(this).text(user.description);
        } else if (attr == "stakeholder_group") {
          $(this).text(user.stakeholder_group);
        } else {
          $(this).text(user.stakeholder_quadrant);
        }
      });
}</script>

{% endblock javascript %}
RCarmody
  • 712
  • 1
  • 12
  • 29
  • Hi, your modal(new) doesn't have any input with `name="stakeholder_quadrant"` there are two inputs with same name i.e : `stakeholder_group` ? – Swati Jan 01 '21 at 04:51
  • Yes I fixed this but no luck – RCarmody Jan 02 '21 at 00:09
  • Try printing values which are getting passed to your backend page inside your submit handler see if all values are correct – Swati Jan 02 '21 at 04:00
  • @Swati - confirmed that I am able to update the field from the command line as well as within my SQLite3 database. This must mean that my models are working, so the issue resides in either my views or js portion of my code, correct? – RCarmody Jan 02 '21 at 15:12
  • yes .. just put `alert(stakeholder_groupInput +","+stakeholder_quadrantInput)` inside your `$("form#addUser").submit(function() {` see if that showing right values – Swati Jan 02 '21 at 15:17
  • Just added an edit to the post with the details. Adding that alert did not trigger anything unfortunately... Maybe I added it in the wrong spot? – RCarmody Jan 02 '21 at 15:32
  • Your page should not get refresh because here you need to use ajax so first handle that issue . Check this [post](https://stackoverflow.com/questions/6462143/prevent-default-on-form-submit-jquery) to avoid same and then let me know further update. – Swati Jan 02 '21 at 15:35
  • I've added this code (updated above) based on the link you shared but no changes: $(document).ready(function() { $('form').on('submit', function(e){ e.preventDefault(); – RCarmody Jan 02 '21 at 15:50
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/226742/discussion-between-swati-and-rcarmody). – Swati Jan 02 '21 at 16:01

0 Answers0