Cannot create new Django model object within Ajax post request-Collection of common programming errors
This is kind of “I already lost x hours debugging this” kind of problem/question 🙁
Following jQuery js code is initiating POST request upon button click
$("#btn_create_tag").click(function(evt) {
$.post("/tag/createAjax", {
tagname: $("#txt_tag_name").val()
},
function(data) {
}
);
});
Django code that is performed on this call is:
@suppress_logging_output
@login_required
def createAjax(request):
if request.is_ajax() and request.method == 'POST':
tagName = request.POST["tagname"]
new_tag = Tag()
new_tag.name = tagName
new_tag.save()
print "new tag with id %s has been created" % new_tag.id
That code is executed successfully (I’m doing checks for empty or already existing name, but didn’t wrote here to be more clear), but new Tag object is NOT created. I’m even getting “”new tag with id %s has been created” printed on devserver’s prompt, and every time ID is increased for one, as suppossed to, but objects are not stored in db.
When I execute
new_tag = Tag()
new_tag.name = tagName
new_tag.save()
from Django shell, new Tag object is regulary created, but from jQuery request, it’s not created.
Have any idea what’s wront, what to check, how to debug this….
DB behind is PostgresSQL 8.3.
Any suggestion is more then welcome 🙂
Update:
I wrote UnitTest which is working:
class AjaxTestCase(TestCase):
def testAjaxCreateTag(self):
tagNum = Tag.objects.filter(name="TEST_TAG").count()
self.assertEqual(tagNum, 0)
c = Client()
c.post('/lookup/tag/createAjax', {'tagname': 'TEST_TAG'}, HTTP_X_REQUESTED_WITH='XMLHttpRequest')
tagNum = Tag.objects.filter(name="TEST_TAG").count()
self.assertEqual(tagNum, 1)
Update2:
Hum, this morning, it seems that everything is working fine, but code hasn’t changed. I don’t like this at all 🙁
-
This sounds very strange. Can you double check your database settings? Ensure that you are using the correct database inside
settings.py
? Also write an unit test to exercise the code using Django’s test client. In your test method remember to send theHTTP_X_REQUESTED_WITH
header foris_ajax()
to work. -
try
new_tag=Tag(name=tagName) new_tag.save()
BTW – you should sanitize the new tagname and not take it directly from the POST