Django, Role matching query does not exist

As the Title says, The models for Role and Location both have data in them as it was inserted in the admin page and confirmed. I get the same issue with Location instead of role if it is commented out.

DoesNotExist at /api/add/res/
Role matching query does not exist.

Traceback:
File "/usr/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 132.                     
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/speedy/hrdb/hrdb/api.py" in set 26.         
role=Role.objects.get(role_name=data['role']), 
File "/usr/lib/python2.7/site-packages/django/db/models/manager.py" in manager_method 127.                 
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/usr/lib/python2.7/site-packages/django/db/models/query.py" in get 334.                 
self.model._meta.object_name

here is the api

def set(request):
data = json.loads(request.body)
res = Resource.objects.get_or_create(
    title=data['title'],
    preferred_name=data['preferred_name'],
    last_name=data['last_name'],
    employstatus=data['employstatus'],
    employer=data['employer'], 
    role=Role.objects.get(role_name=data['role']), 
    location=Location.objects.get(name=data['location']), 
    workphone=data['workphone'], 
    mobile_phone=data['mobile_phone'],
    email=data['email'], 
    notes=data['notes'], 
    updated_by=data['updated_by'], 
    )
print res
return HttpResponse('"Submitted"', content_type='application/json')

here is the Model

class Resource(models.Model):

    title = models.CharField(max_length=10)
    preferred_name = models.CharField(max_length=20)
    last_name = models.CharField(max_length=30)
    employstatus = models.CharField(max_length=20)
    employer = models.CharField(max_length=30)
    role = models.ForeignKey('Role')
    location = models.ForeignKey('Location')
    workphone = models.CharField(max_length=25, blank=True, null=True)
    mobile_phone = models.CharField(max_length=15, blank=True, null=True)
    email = models.CharField(max_length=15, blank=True, null=True)
    notes = models.CharField(max_length=200, blank=True, null=True)
    updated_by = models.CharField(max_length=30, blank=True, null=True)


class Location(models.Model):
    name = models.CharField(max_length=200)
    phone_number = models.CharField(max_length=200)
class Role(models.Model):
    role_name = models.CharField(max_length=200)
    role_description = models.CharField(max_length=200)

Ad this is the JS stuff

var data={}

$.each($('#addPersonnel').find('.form-control'), function(){
    var field = this.id,
        value = $(this).val()
        data[field] = value
}) 
//data from add resource model to database with success function
$.ajax({
    type: "POST",
    url: "/api/add/res/",
    data: JSON.stringify(data),

    success: function(response) {
        var successMessage = $('<div>').text('Successfully saved to database...').css('color', 'green');
            $('.form-group').removeClass('has-error')
            $('#submitresource').html('Added!').addClass('btn-success')
            $('.modal-body').append(successMessage);
            window.setTimeout(function() { 
            $('#addPersonnel').modal('hide'); }, 1000);
            console.log("yers")              
        },
            contentType: "application/json",
            dataType: "json"

And here is some more then. This is the HTML, the part relevant to the location and role

<div class="form-group">
    <label for="role" class="col-lg-3 control-label">Role</label>
        <div class="col-lg-8">
            <select class="form-control" id="role">
            </select>
        </div>
</div>

<div class="form-group">
    <label for="location" class="col-lg-3 control-label">Location</label>
        <div class="col-lg-8">
            <select class="form-control" id="location">
            </select>
        </div>
</div>

this is the drop down js stuff (note Employer works fine)

var data={}

$(document).ready(function() {
    $.get('/api/new/emp/', function(response){

        $('#employer').empty()

        $('#location').empty()

        $('#role').empty()

     $.each(response.Employers, function(){
         $('#employer').append('<option value='+this+'>'+this+'</option>')
    })

        $.each(response.Locations, function(){
            $('#location').append('<option value='+this+'>'+this+'</option>')
    })

        $.each(response.Roles, function(){
            $('#role').append('<option value='+this+'>'+this+'</option>')

And this is the api stuff.

def addresddpop(request):
    data = {
        'Employers':[],
        'Locations':[],
        'Roles':[]
}

# Get a list of all employers
    for ddemp in Employer.objects.all():
        data['Employers'].append(ddemp.employer_name)

# Get a list of all locations
    for ddloc in Location.objects.all():
        data['Locations'].append(ddloc.name)

# Get a list of all roles
    for ddrol in Role.objects.all():
        data['Roles'].append(ddrol.role_name)

    return HttpResponse(json.dumps(data), content_type='application/json')

Answers


I think one of two things is happening. Possibility one: the values you're posting for Role and Location don't match the format you expect. For instance, the label in the dropdown may be the name or role_name but the posted value may be the ID. You mentioned that those data points are selected with a drop-down - double-check the value attributes in your options for that select to make sure they're really names and not IDs.

Or, your jquery function is setting data['role_name'] and data['location'] before a selection is made (or is failing to change the value if the selection is changed).

If you post the value of data we can figure out which one is the case, but I'm almost certain it's one of these two issues.


It is ok world I fixed the issue. Because I had spaces in my roles and location the dropdowns were the issue so I changed them a bit

var data={}

$(document).ready(function() {
    $.get('/api/new/emp/', function(response){

        $('#employer').empty()

        $('#location').empty()

        $('#role').empty()


        $.each(response.Employers, function(){
            //$('#employer').append('<option value='+this+'>'+this+'</option>')
            $('#employer').append($('<option></option>').val(this).text(this))
    })

        $.each(response.Locations, function(){
            //$('#location').append('<option value='+this+'>'+this+'</option>')
            $('#location').append($('<option></option>').val(this).text(this))
    })

        $.each(response.Roles, function(){
            // $('#role').append('<option value='+this+'>'+this+'</option>')
            $('#role').append($('<option></option>').val(this).text(this))

I have left the old code in so you can see the fix


Need Your Help

Find if windows installer succeeds or fails

installer windows-installer

I want to send my users a package of 3 applications (each of them are an exe file that can be installed) for them to download and install.

How to call my app url from google app engine

java google-app-engine gwt

I developed my application using java GWT and I deployed my application on google app engine. my access url is sample.myappid.appspot.com I want to call this url through code so i did like this :- ...