user1659653
user1659653

Reputation: 334

Django Query doesn't match

I have the following Django Model:

class State(models.Model):
    name = models.CharField(max_length=80,null=False)
    latitude = models.CharField(max_length=80,null=False)
    longitude = models.CharField(max_length=80,null=False)

def __unicode__(self):
    return self.name

In my views.py file I've created the following method:

def getCoords(request):
    if request.is_ajax():
        if request.method == 'POST':
            try:
                state = request.POST['state'] #receives the state from JS
                stateInstance = State.objects.get(name=state)
                stateLat = stateInstance.latitude
                stateLong = stateInstance.longitude
                data = {"lat" : stateLat, "long" : stateLong}
             except State.DoesNotExist:
                 return HttpResponse("No record")

             return HttpResponse(simplejson.dumps(data)) #returns json 

So I'm sending this method a param through ajax, let's say "California". The state variable gets the value (I have proved that) but the query doesn't get executed, it returns the query doesn't match message. I've tried with the following as well:

    state = request.POST['state']
        if state == 'California':
            return HttpResponse("Yes!")
        else:
            return HttpResponse(state)

When this snippet returns the state it displays California which means state's value is correct but the query is not executed properly. I don't know what's going on. Any thoughts?

Upvotes: 1

Views: 714

Answers (1)

Mike Shultz
Mike Shultz

Reputation: 1418

Make sure you're connecting to the correct database in your settings.py. Make sure the record actually does exist with plain old SQL.

SELECT * FROM [app_name]_state WHERE name = 'California';

Also, try it from the Django shell. python manage.py shell

>>> from [app_name].models import State
>>> s = State.objects.get(name='California')
>>> s
<State: California>

Make sure that what is actually being sent is sent as POST, and not accidentally a GET variable in the URL. Also, make sure that the post variable has no extra characters and that it is actually valid. A decent way to do that is to just print it to the console, or if AJAX, with Firebug.

# Single quotes added so you can see any extra spaces in the console
print "'%s'" % state 

Upvotes: 1

Related Questions