... ここでは、API ベースのワークフローと「通常の」フォーム POST で動作するフォームの実装例を紹介します: from django.http import JsonResponse from django.views.generic.edit import CreateView from myapp.models import Author class JsonableResponseMixin : """ Mixin t ... ): response = super () . form_invalid ( form ) if self . request . accepts ( "text/html" ): return response else : return JsonResponse ( form . errors , status = 400 ) def form_valid ( self , form ): # We make sure to call the parent's form_valid() method b ... ( form ) if self . request . accepts ( "text/html" ): return response else : data = { "pk" : self . object . pk , } return JsonResponse ( data ) class AuthorCreateView ( JsonableResponseMixin , CreateView ): model = Author fields = [ "name" ] 上の例では、クラ ... ... ここでは、API ベースのワークフローと「通常の」フォーム POST で動作するフォームの実装例を紹介します: from django.http import JsonResponse from django.views.generic.edit import CreateView from myapp.models import Author class JsonableResponseMixin : """ Mixin t ... ): response = super () . form_invalid ( form ) if self . request . accepts ( "text/html" ): return response else : return JsonResponse ( form . errors , status = 400 ) def form_valid ( self , form ): # We make sure to call the parent's form_valid() method b ... ( form ) if self . request . accepts ( "text/html" ): return response else : data = { "pk" : self . object . pk , } return JsonResponse ( data ) class AuthorCreateView ( JsonableResponseMixin , CreateView ): model = Author fields = [ "name" ] 上の例では、クラ ... ... not considered valid because email has not been sanitized: from django.core.mail import send_mail from django.http import JsonResponse def my_proof_of_concept ( request ): email = request . GET . get ( "email" , "" ) send_mail ( "Email subject" , "Email bod ... y" , email , [ "admin@example.com" ]) return JsonResponse ( status = 200 ) Developers must always validate and sanitize input before using it. The correct approach would be to use ... nsure email is properly validated: from django import forms from django.core.mail import send_mail from django.http import JsonResponse class EmailForm ( forms . Form ): email = forms . EmailField () def my_proof_of_concept ( request ): form = EmailForm ( re ... ... not considered valid because email has not been sanitized: from django.core.mail import send_mail from django.http import JsonResponse def my_proof_of_concept ( request ): email = request . GET . get ( "email" , "" ) send_mail ( "Email subject" , "Email bod ... y" , email , [ "admin@example.com" ]) return JsonResponse ( status = 200 ) Developers must always validate and sanitize input before using it. The correct approach would be to use ... nsure email is properly validated: from django import forms from django.core.mail import send_mail from django.http import JsonResponse class EmailForm ( forms . Form ): email = forms . EmailField () def my_proof_of_concept ( request ): form = EmailForm ( re ... ... s from django.http import HttpResponse class HttpResponseNoContent ( HttpResponse ): status_code = HTTPStatus . NO_CONTENT JsonResponse オブジェクト ¶ class JsonResponse ( data , encoder = DjangoJSONEncoder , safe = True , json_dumps_params = None , ** kwarg ... ps() 呼び出しに渡すキーワード引数の辞書です。 使い方 ¶ 一般的な使用方法は以下のようになります: >>> from django.http import JsonResponse >>> response = JsonResponse ({ "foo" : "bar" }) >>> response . content b'{"foo": "bar"}' 辞書以外のオブジェクトのシリアライ ... ズ ¶ dict 以外のオブジェクトをシリアライズする場合、 safe パラメータを False に設定する必要があります: >>> response = JsonResponse ([ 1 , 2 , 3 ], safe = False ) safe=False を指定しなかった場合、 TypeError が発生します。 dict オブジェクトに基づいた API ... ... s from django.http import HttpResponse class HttpResponseNoContent ( HttpResponse ): status_code = HTTPStatus . NO_CONTENT JsonResponse オブジェクト ¶ class JsonResponse ( data , encoder = DjangoJSONEncoder , safe = True , json_dumps_params = None , ** kwarg ... ps() 呼び出しに渡すキーワード引数の辞書です。 使い方 ¶ 一般的な使用方法は以下のようになります: >>> from django.http import JsonResponse >>> response = JsonResponse ({ "foo" : "bar" }) >>> response . content b'{"foo": "bar"}' 辞書以外のオブジェクトのシリアライ ... ズ ¶ dict 以外のオブジェクトをシリアライズする場合、 safe パラメータを False に設定する必要があります: >>> response = JsonResponse ([ 1 , 2 , 3 ], safe = False ) safe=False を指定しなかった場合、 TypeError が発生します。 dict オブジェクトに基づいた API ... ... ef get_absolute_url ( self ): return reverse ( "article-detail" , args = [ self . pk ]) views.py ¶ from django.http import JsonResponse from django.shortcuts import get_object_or_404 , resolve_url from .models import Article def article_api_view ( request , ... Return metadata about an article, including its canonical URL.""" article = get_object_or_404 ( Article , pk = pk ) return JsonResponse ( { "id" : article . pk , "title" : article . title , "url" : resolve_url ( article ), } ) Resolving a target URL for use ... ... ef get_absolute_url ( self ): return reverse ( "article-detail" , args = [ self . pk ]) views.py ¶ from django.http import JsonResponse from django.shortcuts import get_object_or_404 , resolve_url from .models import Article def article_api_view ( request , ... Return metadata about an article, including its canonical URL.""" article = get_object_or_404 ( Article , pk = pk ) return JsonResponse ( { "id" : article . pk , "title" : article . title , "url" : resolve_url ( article ), } ) Resolving a target URL for use ... ... response to return something not rendered via a Django template then you'll want to do it. For an example of this, see the JSONResponseMixin example . render_to_response() 自体は get_template_names() を呼び出しますが、デフォルトではクラスベースのビューで tem ... SONへの変換処理をするmixinクラスを作成できます。 たとえば、JSONのmixinは以下のようになるでしょう。 from django.http import JsonResponse class JSONResponseMixin : """ A mixin that can be used to render a JSON response. """ def render_to_json_response ( self , ... context , ** response_kwargs ): """ Returns a JSON response, transforming 'context' to make the payload. """ return JsonResponse ( self . get_data ( context ), ** response_kwargs ) ... ... response to return something not rendered via a Django template then you'll want to do it. For an example of this, see the JSONResponseMixin example . render_to_response() 自体は get_template_names() を呼び出しますが、デフォルトではクラスベースのビューで tem ... SONへの変換処理をするmixinクラスを作成できます。 たとえば、JSONのmixinは以下のようになるでしょう。 from django.http import JsonResponse class JSONResponseMixin : """ A mixin that can be used to render a JSON response. """ def render_to_json_response ( self , ... context , ** response_kwargs ): """ Returns a JSON response, transforming 'context' to make the payload. """ return JsonResponse ( self . get_data ( context ), ** response_kwargs ) ... 2026年10月08日