create project, app
$ django-admin.py startproject app $ cd app $ python manage.py startapp blog
app/
settings.py
データベースの設定とか適当に
apps/urls.py
from django.conf.urls import patterns, include, url from django.contrib import admin urlpatterns = patterns('', url(r'^blog/', include('blog.urls')), )
blog/
blog/views.py
from django import http from django.utils import simplejson as json from django.views.generic.base import View class JSONResponseMixin(object): def render_to_response(self, context): "Returns a JSON response containing 'context' as payload" return self.get_json_response(self.convert_context_to_json(context)) def get_json_response(self, content, **httpresponse_kwargs): "Construct an `HttpResponse` object." return http.HttpResponse(content, content_type='application/json', **httpresponse_kwargs) def convert_context_to_json(self, context): "Convert the context dictionary into a JSON object" return json.dumps(context) class JSONView(JSONResponseMixin, View): pass class FooView(JSONView): def get(self, request, *args, **kwargs): return self.render_to_response({'Foo': 'bar'})
urls.py
from django.conf.urls.defaults import patterns, url from blog.views import FooView urlpatterns = patterns('', url(r'^foo$', FooView.as_view(), name='foo'), )
確認
runserver
python manage.py runserver