90👍
There is a bug ticket on Django regarding this issue however a custom so called ‘complex encoder’ by python docs can help you.
import json
from uuid import UUID
class UUIDEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, UUID):
# if the obj is uuid, we simply return the value of uuid
return obj.hex
return json.JSONEncoder.default(self, obj)
Now if we did something like this
json.dumps(my_object, cls=UUIDEncoder)
Your uuid field should be encoded.
- [Django]-Django in / not in query
- [Django]-How to receive json data using HTTP POST request in Django 1.6?
- [Django]-How can I keep test data after Django tests complete?
12👍
Looks like this error is no more relevant for django, while using DjangoJSONEncoder
. No need to write own custom encoder. Provided by django handles most known serializing problems.
import json
from django.core.serializers.json import DjangoJSONEncoder
json.dumps(my_object, cls=DjangoJSONEncoder)
Details here
- [Django]-TypeError: data.forEach is not a function
- [Django]-Django-Forms with json fields
- [Django]-Why is factory_boy superior to using the ORM directly in tests?
6👍
I use convert function for this, it is simple and clean.
import json
from uuid import UUID
def uuid_convert(o):
if isinstance(o, UUID):
return o.hex
json.dumps(users,indent=4,default=uuid_convert)
- [Django]-Django syncdb and an updated model
- [Django]-What is the advantage of Class-Based views?
- [Django]-How can I programmatically obtain the max_length of a Django model field?
5👍
For using the UUID in a URL like that, you should pass it as a string:
return redirect(reverse('namespace:name', kwargs={'uuid' : str(object.id)}))
FYI – it looks like WIMs answer is a bit more thorough. Your regex should certainly be tightened up. If you end up using the string representation of the slug, you’ll want a regex like this: [A-Za-z0-9\-]+
which allows for alphanumerics and hyphens.
- [Django]-How to use "get_or_create()" in Django?
- [Django]-Fastest way to get the first object from a queryset in django?
- [Django]-Is it possible to generate django models from the database?
5👍
An alternative is to use default=str
. I leave it for reference:
import uuid
import json
pk = uuid.UUID("04d8d2dc-e81b-4eaa-8883-d1e361a08da8")
o = json.dumps({"pk": pk}, default=str)
print(o)
Outputs:
{"pk": "04d8d2dc-e81b-4eaa-8883-d1e361a08da8"}
- [Django]-What's the purpose of Django setting ‘SECRET_KEY’?
- [Django]-What is actually assertEquals in Python?
- [Django]-When to create a new app (with startapp) in Django?
0👍
I had this same problem with a UUID field in a database model that I wanted to print out for debugging. I found that the pprint()
function from the pprint
module can handle this. You can also give it an indent
argument to get the same kind of indented output that you would get from json.dumps()
https://docs.python.org/3/library/pprint.html#pprint.pprint
Example:
>>> import uuid
>>> import pprint
>>> import json
>>> x = uuid.UUID('12345678123456781234567812345678')
>>> x
UUID('12345678-1234-5678-1234-567812345678')
>>> print(x)
12345678-1234-5678-1234-567812345678
>>> json.dumps(x)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
...
...
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: UUID('12345678-1234-5678-1234-567812345678') is not JSON serializable
>>> pprint.pprint(x)
UUID('12345678-1234-5678-1234-567812345678')
- [Django]-How to disable Django's CSRF validation?
- [Django]-Modulus % in Django template
- [Django]-Django model CharField: max_length does not work?
0👍
I used a lambda function to inline str() the object.
import uuid
import json
mydict = {
"key1":"value1",
"guid1": uuid.uuid4()
}
myjson = json.dumps(mydict, default=lambda x : str(x))
print(myjson)
- [Django]-How to manage local vs production settings in Django?
- [Django]-Django templates: verbose version of a choice
- [Django]-Django Password Generator