{"id":13849425,"url":"https://github.com/bbengfort/django-generic-json-views","last_synced_at":"2025-04-30T17:04:11.825Z","repository":{"id":57420211,"uuid":"10482026","full_name":"bbengfort/django-generic-json-views","owner":"bbengfort","description":"Class based generic views that render JSON data. ","archived":false,"fork":false,"pushed_at":"2018-09-29T00:43:49.000Z","size":44,"stargazers_count":31,"open_issues_count":3,"forks_count":17,"subscribers_count":5,"default_branch":"master","last_synced_at":"2025-04-30T17:04:05.829Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/bbengfort.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2013-06-04T15:35:27.000Z","updated_at":"2021-10-27T06:29:43.000Z","dependencies_parsed_at":"2022-09-10T15:20:40.546Z","dependency_job_id":null,"html_url":"https://github.com/bbengfort/django-generic-json-views","commit_stats":null,"previous_names":[],"tags_count":4,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bbengfort%2Fdjango-generic-json-views","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bbengfort%2Fdjango-generic-json-views/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bbengfort%2Fdjango-generic-json-views/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bbengfort%2Fdjango-generic-json-views/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/bbengfort","download_url":"https://codeload.github.com/bbengfort/django-generic-json-views/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":251748935,"owners_count":21637414,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-08-04T19:01:17.649Z","updated_at":"2025-04-30T17:04:11.376Z","avatar_url":"https://github.com/bbengfort.png","language":"Python","funding_links":[],"categories":["Python"],"sub_categories":[],"readme":"# Django Generic JSON Views\n\n[![Stories in Ready](https://badge.waffle.io/bbengfort/django-generic-json-views.png?label=ready\u0026title=Ready)](https://waffle.io/bbengfort/django-generic-json-views)\n [![Build Status](https://travis-ci.org/bbengfort/django-generic-json-views.svg)](https://travis-ci.org/bbengfort/django-generic-json-views) [![PyPi version](https://img.shields.io/pypi/v/django-generic-json-views.svg)](https://pypi.python.org/pypi/django-generic-json-views/)\n\n**Class based generic views that render JSON data.**\n\nThe `django.views.generic` package has several generic class based views\nthat render HTML for a model or a set of applications and provide an API\nto use those views and modify querysets and context data. However, Django\nrecommends that to specify the output of JSON data, you use a mixin or\nanother approach to `render_to_response` the JSON.\n\nMany AJAX applications, however, have the need for quick views like the\nones specified the in the `generic` package to either serialize a model\nor to provide other context data in the View logic. These generic views\nallow that, and correctly render JSON data with the correct HTTP Headers.\n\nMore documentation can be found at Read the Docs: [Django Generic JSON Views Documentation](http://django-generic-json-views.readthedocs.org/en/latest/)\n\n## Installation\n\nThe easiest way to install this library is to use `pip` as follows:\n\n```bash\n$ pip install django-generic-json-views\n```\n\nAlternatively you can download the source code and run the following:\n\n```bash\n$ python setup.py install\n```\n\nYou can import from the `json_views.views` module.\n\nOtherwise copy the views.py file to a utils directory in your Django Project and import it correctly from there.\n\n## Basic Usage\n\nThere are several provided classes that work right off the bat:\n\n* `JSONDataView`\n* `JSONDetailView`\n* `JSONListView`\n* `PaginatedJSONListView`\n* `JSONFormView`\n\nThese classes all provide the following functionality:\n\n1. Render the output of `get_context_data` as a JSON object\n2. Serialize Django Models and Querysets with a Lazy Encoder\n3. Correctly add the application/json HTTP header\n4. Remove duplicate objects and middleware context built into Django\n\nThe most simple example is the `JSONDataView` which will allow you to output generic JSON data as needed:\n\n```python\nfrom datetime import datetime\nfrom json_views.views import JSONDataView\n\n\nclass JSONTime(JSONDataView):\n\n    def get_context_data(self, **kwargs):\n        context = super(JSONTime, self).get_context_data(**kwargs)\n        context['current_time'] = datetime.now().strftime(\"%c\")\n        return context\n```\n\nIn order to render the detail view of a model as a JSON serialization,\nuse the `JSONDetailView` -- note that this view can be used for both\nserialization and deserialization as noted in the section below.\n\n```python\nfrom json_views.views import JSONDetailView\n\n\nclass CustomerJSON(JSONDetailView):\n\n    model = Customer\n```\n\nMany JSON views are centered around lists, hence the `JSONListView` and\nthe `PaginatedJSONListView`.\n\n```python\nfrom json_views.views import JSONListView\n\n\nclass ProductsJSON(JSONListView):\n\n    model = Product\n```\n\nThe `PaginatedJSONListView` looks up the special parameter `page=n` to\ndecide which part of the list to return. It also removes the Django paginator\nobject and returns the following data:\n\n```python\n{\n    'pages': Number,\n    'count': Number,\n    'is_paginated': Bool,\n    'per_page': Number,\n    'current': Number,\n    'object_list': List\n}\n```\n\nAn example of using this view is:\n\n```python\nfrom json_views.views import PaginatedJSONListView\n\n\nclass PaginatedProducts(PaginatedJSONListView):\n\n    paginate_by = 10\n    count_query = 'count'\n    count_only  = False\n\n    def get_querset(self):\n        return Product.objects.filter(instores=True)\n```\n\n`count_query` specifies the name of the property to pass in as kwargs in\na GET request that will force the view to only return the total number\nof expected items, and not fetch them from the db. E.g. if you use\n`/?count=true` in your url, the view will respond only with the total number.\n\nFinally the JSONFormView accepts incoming JSON data to populate a form\nrather than waiting for HTTP POST data, this is how you would do AJAX login\nforms. Note that GET requests are not allowed.\n\n```python\nfrom json_views.views import JSONFormView\n\n\nclass LoginForm(JSONFormView):\n\n    form = LoginForm\n```\n\nIn the form view, a parameter `success` is passed back, as either True or\nFalse. This can be customized by overriding `get_context_data`.\n\n## Serialization \u0026 Deserialization\n\nThe lazy encoder attempts to serialze the model into a dictionary or other\ncompatible JSON-Python type, and does so in a recursive fashion,\ncontinuing to serialize objects, the default serialization is this:\n\n1. If the object is an iterable- construct a list\n2. If the object extends `ModelBase` attempt to call a `serialize` method\n3. Utilize `force_unicode` to force the object to unicode data.\n\nTherefore if your `Models` provide a `serialize` method that returns a\ndictionary, you can very easily control what fields and what format the\nmodel is serialized to.\n\nAdditionally you can specify a `@classmethod` `deserialize` that accepts\nas input a dictionary and returns an instance of the `Model`.\n\nHere is an example of the serialization of a UserProfile, as an extension\nof the `django.contrib.auth` package.\n\n```python\nclass UserProfile(models.Model):\n\n    user  = models.OneToOneField( 'django.contrib.auth.User', editable=False, related_name='profile' )\n    bio   = models.CharField( max_length=255, null=True, blank=True, default=None )\n    birth = models.DateField( )\n\n    def serialize(self):\n        return {\n            'username': self.user.username,\n            'email': self.user.email,\n            'name': \" \".join((self.user.first_name, self.user.last_name)),\n            'birthday': self.birth.strftime(\"%d %M, %Y\"),\n        }\n\n    @classmethod\n    def deserialize(klass, data):\n        username = data.get('username', None)\n        if username:\n            try:\n                return klass.objects.get(username=username)\n            except klass.DoesNotExist:\n                pass\n        return klass(**data)\n```\n\n## Pushing to PyPi\n\nA couple of notes on pushing this software to PyPi:\n\n1. Version Bump    \n    1. Change the version in `__init__`.py\n    2. Change the version in tests\n    3. Change the download URL in setup.py\n2. Tag the release `git tag -a v0.x.x`\n3. Push to Github\n4. Register `python setup.py register -r pypi`\n5. Upload `python setup.py sdist upload -r pypi`  \n\n## Contributors\n\nThanks to [@philippbosch](https://github.com/philippbosch) for helping provide Python 3 support with later versions of Django.\n\nThanks to [@freeworlder](https://github.com/freeworlder) who provided Django 1.10 compatibility.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbbengfort%2Fdjango-generic-json-views","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fbbengfort%2Fdjango-generic-json-views","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbbengfort%2Fdjango-generic-json-views/lists"}