Repository navigation
Closed
Labels
Milestone
Description
Checklist
- I have verified that that issue exists against the
masterbranch of Django REST framework. - I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
- This is not a usage question. (Those should be directed to the discussion group instead.)
- This cannot be dealt with as a third party library. (We prefer new functionality to be in the form of third party libraries where possible.)
- I have reduced the issue to the simplest possible case.
- I have included a failing test as a pull request. (If you are unable to do so we can still accept the issue.)
Steps to reproduce
- Create a model with a
JSONFieldfeild (from django.contrib.postgres.fields import JSONField). - For the serializer use
serializer.JSONField(from rest_framework import serializers) - POST
{..., "json_field": {"foo": Infinity} }
Expected behavior
The serializer fails with a bad request: "Value must be valid JSON."
Actual behavior
The server throws a 500 (from a slightly modified snippet tutorial example):
Performing system checks...
System check identified no issues (0 silenced).
June 26, 2017 - 17:31:55
Django version 1.11.2, using settings 'tutorial.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
Internal Server Error: /snippets/
Traceback (most recent call last):
File "/home/steve/.virtualenvs/drf_example/lib/python3.5/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
psycopg2.DataError: invalid input syntax for type json
LINE 1: ...nt("Hello world!")', false, 'python', 'friendly', '{"foo2": ...
^
DETAIL: Token "Infinity" is invalid.
CONTEXT: JSON data, line 1: {"foo2": Infinity...
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/steve/.virtualenvs/drf_example/lib/python3.5/site-packages/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/home/steve/.virtualenvs/drf_example/lib/python3.5/site-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/steve/.virtualenvs/drf_example/lib/python3.5/site-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/steve/.virtualenvs/drf_example/lib/python3.5/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
return view_func(*args, **kwargs)
File "/home/steve/devel/examples/drf/tutorial/snippets/views.py", line 23, in snippet_list
serializer.save()
File "/home/steve/.virtualenvs/drf_example/lib/python3.5/site-packages/rest_framework/serializers.py", line 215, in save
self.instance = self.create(validated_data)
File "/home/steve/devel/examples/drf/tutorial/snippets/serializers.py", line 18, in create
return Snippet.objects.create(**validated_data)
File "/home/steve/.virtualenvs/drf_example/lib/python3.5/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/steve/.virtualenvs/drf_example/lib/python3.5/site-packages/django/db/models/query.py", line 394, in create
obj.save(force_insert=True, using=self.db)
File "/home/steve/.virtualenvs/drf_example/lib/python3.5/site-packages/django/db/models/base.py", line 806, in save
force_update=force_update, update_fields=update_fields)
File "/home/steve/.virtualenvs/drf_example/lib/python3.5/site-packages/django/db/models/base.py", line 836, in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "/home/steve/.virtualenvs/drf_example/lib/python3.5/site-packages/django/db/models/base.py", line 922, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "/home/steve/.virtualenvs/drf_example/lib/python3.5/site-packages/django/db/models/base.py", line 961, in _do_insert
using=using, raw=raw)
File "/home/steve/.virtualenvs/drf_example/lib/python3.5/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/steve/.virtualenvs/drf_example/lib/python3.5/site-packages/django/db/models/query.py", line 1063, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File "/home/steve/.virtualenvs/drf_example/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 1099, in execute_sql
cursor.execute(sql, params)
File "/home/steve/.virtualenvs/drf_example/lib/python3.5/site-packages/django/db/backends/utils.py", line 80, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/home/steve/.virtualenvs/drf_example/lib/python3.5/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
File "/home/steve/.virtualenvs/drf_example/lib/python3.5/site-packages/django/db/utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/home/steve/.virtualenvs/drf_example/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise
raise value.with_traceback(tb)
File "/home/steve/.virtualenvs/drf_example/lib/python3.5/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
django.db.utils.DataError: invalid input syntax for type json
LINE 1: ...nt("Hello world!")', false, 'python', 'friendly', '{"foo2": ...
^
DETAIL: Token "Infinity" is invalid.
CONTEXT: JSON data, line 1: {"foo2": Infinity...
[26/Jun/2017 17:32:10] "POST /snippets/ HTTP/1.1" 500 180159
Changes I made to the code snippet tutorial:
commit b9c6cc6e44ca1a83fa6d88c1f06af073fa7052a7
Author: Stephen Chisholm <[email protected]>
Date: Mon Jun 26 14:51:43 2017 -0300
Add JSONField to model
diff --git a/snippets/migrations/0002_snippet_json_field.py b/snippets/migrations/0002_snippet_json_field.py
new file mode 100644
index 0000000..a53e958
--- /dev/null
+++ b/snippets/migrations/0002_snippet_json_field.py
@@ -0,0 +1,21 @@
+# -*- coding: utf-8 -*-
+# Generated by Django 1.11.2 on 2017-06-26 17:49
+from __future__ import unicode_literals
+
+import django.contrib.postgres.fields.jsonb
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('snippets', '0001_initial'),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name='snippet',
+ name='json_field',
+ field=django.contrib.postgres.fields.jsonb.JSONField(default=dict),
+ ),
+ ]
diff --git a/snippets/models.py b/snippets/models.py
index d443dc6..7772fab 100644
--- a/snippets/models.py
+++ b/snippets/models.py
@@ -1,6 +1,7 @@
from django.db import models
from pygments.lexers import get_all_lexers
from pygments.styles import get_all_styles
+from django.contrib.postgres.fields import JSONField
LEXERS = [item for item in get_all_lexers() if item[1]]
LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS])
@@ -14,6 +15,7 @@ class Snippet(models.Model):
linenos = models.BooleanField(default=False)
language = models.CharField(choices=LANGUAGE_CHOICES, default='python', max_length=100)
style = models.CharField(choices=STYLE_CHOICES, default='friendly', max_length=100)
+ json_field = JSONField(default=dict)
class Meta:
ordering = ('created',)
diff --git a/snippets/serializers.py b/snippets/serializers.py
index 7f12e7c..2a45475 100644
--- a/snippets/serializers.py
+++ b/snippets/serializers.py
@@ -9,6 +9,7 @@ class SnippetSerializer(serializers.Serializer):
linenos = serializers.BooleanField(required=False)
language = serializers.ChoiceField(choices=LANGUAGE_CHOICES, default='python')
style = serializers.ChoiceField(choices=STYLE_CHOICES, default='friendly')
+ json_field = serializers.JSONField()
def create(self, validated_data):
"""
Activity
sbchisholm commentedon Jun 26, 2017
Possible solution, I suppose this might be backwards incompatible for those not using Postgres as a database.
sbchisholm commentedon Jun 26, 2017
Here's a link with the spec on the postgres json data type: https://www.postgresql.org/docs/9.4/static/datatype-json.html
lovelydinosaur commentedon Jun 26, 2017
More broadly I think it's buggy behavior that we accept those values in any case (Not just for postgres JSON fields) since they're not valid JSON.
I'd much rather we were in the situation that we didn't accept them by default, and forced users to use a custom JSONParser if they explicitly did want them. We could consider making this change in a major version release if there's an easy path to backwards compatible behavior.
rpkilby commentedon Jun 28, 2017
This is related to the efforts in #4918. It might make sense to simply override
allow_naninJSONEncoderand add aJSONDecoderwith the handler forparse_constant.rpkilby commentedon Jun 28, 2017
Although,
JSONEncoderis only used byJSONRenderer. ShouldJSONFieldalso use drf'sJSONEncoder?