A memo for getting data from DB with Ajax and returning it in JSON format with Django.
First of all, in order to use Ajax with Django, if it is post, processing like the following page is required. Django Official: https://docs.djangoproject.com/ja/1.10/ref/csrf/
It is necessary to create a js file according to this.
class Sample(models.Model): name = models.CharField(max_length=30) first = models.CharField(max_length=30)
def SampleListAjax(request): objs = Sample.objects.all() data = [dict(name = obj.name, first = obj.first) for obj in objs] json = json.dumps(data) return HttpResponse(json, content_type="application/json")
class urlpatterns=[ url(r'^sample/',ajax.SampleListAjax) ]
After that, as usual, just request the url set by Ajax with something JavaScript and get the JSON data. If you want to control with HTTP method Obtained with request ["method"]. PUT can be obtained with QueryDict.
Please let me know if there is a better way.
Recommended Posts