Book Image

Mastering Django: Core

By : Nigel George
Book Image

Mastering Django: Core

By: Nigel George

Overview of this book

Mastering Django: Core is a completely revised and updated version of the original Django Book, written by Adrian Holovaty and Jacob Kaplan-Moss - the creators of Django. The main goal of this book is to make you a Django expert. By reading this book, you’ll learn the skills needed to develop powerful websites quickly, with code that is clean and easy to maintain. This book is also a programmer’s manual that provides complete coverage of the current Long Term Support (LTS) version of Django. For developers creating applications for commercial and business critical deployments, Mastering Django: Core provides a complete, up-to-date resource for Django 1.8LTS with a stable code-base, security fixes and support out to 2018.
Table of Contents (33 chapters)
Mastering Django: Core
Credits
About the Author
www.PacktPub.com
Preface
Free Chapter
1
Introduction to Django and Getting Started

JsonResponse Objects


class JsonResponse(data, encoder=DjangoJSONEncoder, safe=True, **kwargs) 

An HttpResponse subclass that helps to create a JSON-encoded response. It inherits most behavior from its superclass with some differences:

  • Its default Content-Type header is set to application/json.
  • The first parameter, data, should be a dict instance. If the safe parameter is set to False (see below) it can be any JSON-serializable object.
  • The encoder, which defaults to django.core.serializers.json.DjangoJSONEncoder, will be used to serialize the data.

The safe boolean parameter defaults to True. If it's set to False, any object can be passed for serialization (otherwise only dict instances are allowed). If safe is True and a non-dict object is passed as the first argument, a TypeError will be raised.

Usage

Typical usage could look like:

>>> from django.http import JsonResponse >>> response = JsonResponse({'foo': 'bar'}) >>> response.content '{"foo": "bar"}'

Serializing non-dictionary objects

In order to serialize objects other than dict you must set the safe parameter to False:

response = JsonResponse([1, 2, 3], safe=False) 

Without passing safe=False, a TypeError will be raised.

Changing the default JSON encoder

If you need to use a different JSON encoder class, you can pass the encoder parameter to the constructor method:

response = JsonResponse(data, encoder=MyJSONEncoder)