Reputation: 65
I am trying to send a model data through ajax in django.
My view.py is like this.
from django.core import serializers
def country(request):
country = NewTable.objects.get(id=1)
data = serializers.serialize('json',country)
return HttpResponse(data,mimetype='application/json')
My url.py is like this
from django.conf.urls import patterns, url
from myapp import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^country/$', views.country)
)
my template is like this
function Country(){
$.get('/myapp/country', function(data) {
alert("hello");
}, "json" );
}
when i send the string through view i get the alert message now when I am sending the model data I don't get any alert message.what is the problem?
Upvotes: 1
Views: 1609
Reputation: 65
I've found the solution
view.py
from django.core import serializers
import json
def country(request):
obj_json = serializers.serialize('json', NewTable.objects.filter(id=1) )
obj_list = json.loads( obj_json )
json_data = json.dumps( obj_list )
return HttpResponse( json_data, mimetype='application/json' )
template
$.ajax({
type: "GET",
dataType: "json",
url:"/myapp/country",
success: function(data)
{
alert("Hello");
},
});
Upvotes: 1
Reputation: 959
I have had similar issues, and instead of django's serializers I switched to using json.dumps and now everything works fine.
view.py
import json
def country(request):
country = NewTable.objects.filter(id=1).values()
return HttpResponse(json.dumps(country),content_type='application/json')
EDIT: I am not sure you can use get() for values(), i am using filter in my code and that might be why yours isnt working
Upvotes: 1