A UUIDField for Django

Overview

django-uuidfield

Provides a UUIDField for your Django models.

Installation

Install it with pip (or easy_install):

pip install django-uuidfield

Usage

First you'll need to attach a UUIDField to your class. This acts as a char(32) to maintain compatibility with SQL versions:

from uuidfield import UUIDField

class MyModel(models.Model):
    uuid = UUIDField(auto=True)

Check out the source for more configuration values.

Enjoy!

Comments
  • Return StringUUID's __unicode__ in to_python for compatability with Django's prefetch_related implementation

    Return StringUUID's __unicode__ in to_python for compatability with Django's prefetch_related implementation

    Returning an instance of StringUUID in to_python breaks Django's prefetch_related when a UUIDField is set to primary_key=True - the code expects a string, not an instance.

    opened by pwalsh 11
  • Python 3 support

    Python 3 support

    I started work on Python 3 support today, since I'm trying to port an app of mine that uses django-uuidfield. You can see the beginnings of my work at https://github.com/dominicrodger/django-uuidfield/compare/py3.

    I'm mostly there, there are two outstanding issues:

    1. There's one failing test that I'd appreciate some help with if anyone's got any Python 3/Django/Postgres experience - test_raises_exception throws a psycopg2.DataError at the moment), but it did require switching the tests out from using django-nose to using the default Django test runner, since django-nose doesn't support Python 3 (see https://github.com/jbalogh/django-nose/pull/103). I'm not sure django-nose gets us a lot - it seems to run all the tests twice (I get 10 tests run, even though there are only 5 tests - if I add a simple failing test, I get 12 tests run, 2 failed), and the normal Django runner correctly runs 5 tests.
    2. I'm not quite sure what the purpose of smart_unicode in to_python - the tests don't seem to hit it. I'm guessing just using django.utils.smart_text is the right approach if smart_unicode is still needed.

    I've run the unit tests on Python 2.6, 2.7 and with Django 1.4.5 and 1.5.1 (as you'll see from my changes to tox.ini).

    Does this approach look reasonable? If so, I'll tidy it up, figure out the Postgres issue and send a pull request.

    opened by dominicrodger 10
  • Python3

    Python3

    I started from dominicrodger's PR, and did:

    • rebase against master
    • added additional required fixes for python3
    • updated tox. added .travis.yml, and coveralls

    Note: I was not able to use runtests.py (it is not used by tox/.travis.yml) - perhaps that one should be removed? (in favour of the setup.py test).

    Note: seems some tests are missing, in particular, these methods are not covered at all:

    • value_to_string
    • formfield

    and a test using uuid version1 should probably exist as well.

    opened by julienaubert 7
  • Not JSON encodable

    Not JSON encodable

    UUIDField now returns a StringUUID object. The json encoder has no idea what to do with that, it's not in any of the JSON encoding rules, so it just throws an error.

    Not returning a StringUUID from to_python works, but ideally we'd make StringUUID work in JSON. I could define a custom JSON encoder, but ideally I'd rather make StringUUID just work with JSON so I don't have to.

    opened by andymckay 6
  • Hyphenate problems

    Hyphenate problems

    Created two models with a UUIDField(primary_key=True,hyphenate=True,auto=True) fields. One model has a foreign key to the other model.

    Fixture fields contain UUIDs with hyphens.

    Problem 1: loaddata loads the UUIDs into the database with hyphens removed

    Problem 2: generic.edit.CreateView fails due to a foreign key problem - the form is submitted with a hyphenated UUID, this appears to fail since it is stored without hyphens in the database

    opened by SteveAyre 4
  • String value with hyphens

    String value with hyphens

    I would like to modify UUIDField to return a UUID with hyphens in it. I don't mind how it is stored (in fact, using the Postgres type, it is stored with hyphens in the database). How about an option groups=True that sets max_length to 36 and uses uuid.UUID instead of StringUUID?

    opened by bfirsh 4
  • PostgreSQL throws DataError when trying to retrieve objects with invalid UUID

    PostgreSQL throws DataError when trying to retrieve objects with invalid UUID

    The following code will trigger the problem with PostgreSQL backend:

    SomeModel.objects.get(uuid="invalid_uuid")
    

    An example traceback:

    /.../lib/python2.7/site-packages/django/db/backends/utils.pyc in execute(self, sql, params)
         63                 return self.cursor.execute(sql)
         64             else:
    ---> 65                 return self.cursor.execute(sql, params)
         66 
         67     def executemany(self, sql, param_list):
    
    DataError: invalid input syntax for uuid: "invalid_uuid"
    LINE 1: ... "some_model" WHERE "some_model"."uuid" = 'invalid_u...
                                                         ^
    

    PostgreSQL has a UUID type and throws an error with badly formatted UUID. However, it is not the expected behavior of an API. When user provides an invalid UUID, the API in most cases is expected to return 404, instead of 500 caused by this uncaught exception.

    The problem lies in method get_db_prep_value. If the provided UUID is not valid, the method should return an arbitrary valid UUID that matches nothing in the database.

    opened by lingxiaoyang 3
  • ValueError: badly formed hexadecimal UUID string

    ValueError: badly formed hexadecimal UUID string

    I don't know why it's failing with this error. the way I am using it looks legit to me. https://gist.github.com/pazooki/b3ee2937c72bd0fa679f#file-traceback

    opened by pazooki 3
  • Import the psycopg2.extras module fully.

    Import the psycopg2.extras module fully.

    import psycopg2 alone does not load the extras module: in cases where the latter was not previously loaded as a side effect of other code, the following psycopg2.extras.register_uuid() fails with an AttributeError, leading to other errors later due to the UUID type not being registered in psycopg2.

    import psycopg2.extras fixes this.

    opened by PiDelport 3
  • Not JSON serializable

    Not JSON serializable

    I'm using django-uuidfield together with django-rest-framework to develop a RESTful API. Whenever I try to use the UUIDField, Django throws me this error:

    TypeError at (...)
    UUID('a00fef915e284f6d9d9af8b0500234b7') is not JSON serializable
    

    I believe the UUIDField lacks a method which can serialize it to JSON using python's JSON encoder and decoder.

    Here's the stack trace:

    Traceback:
    File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
      137.                 response = response.render()
    File "/usr/local/lib/python2.7/dist-packages/django/template/response.py" in render
      103.             self.content = self.rendered_content
    File "/usr/local/lib/python2.7/dist-packages/rest_framework/response.py" in rendered_content
      63.         ret = renderer.render(self.data, media_type, context)
    File "/usr/local/lib/python2.7/dist-packages/rest_framework/renderers.py" in render
      606.         context = self.get_context(data, accepted_media_type, renderer_context)
    File "/usr/local/lib/python2.7/dist-packages/rest_framework/renderers.py" in get_context
      556.         raw_data_post_form = self.get_raw_data_form(view, 'POST', request)
    File "/usr/local/lib/python2.7/dist-packages/rest_framework/renderers.py" in get_raw_data_form
      506.                 content = renderer.render(serializer.data, accepted, context)
    File "/usr/local/lib/python2.7/dist-packages/rest_framework/renderers.py" in render
      87.             indent=indent, ensure_ascii=self.ensure_ascii
    File "/usr/lib/python2.7/json/__init__.py" in dumps
      250.         sort_keys=sort_keys, **kw).encode(obj)
    File "/usr/lib/python2.7/json/encoder.py" in encode
      209.             chunks = list(chunks)
    File "/usr/lib/python2.7/json/encoder.py" in _iterencode
      434.             for chunk in _iterencode_dict(o, _current_indent_level):
    File "/usr/lib/python2.7/json/encoder.py" in _iterencode_dict
      408.                 for chunk in chunks:
    File "/usr/lib/python2.7/json/encoder.py" in _iterencode
      442.             o = _default(o)
    File "/usr/local/lib/python2.7/dist-packages/rest_framework/utils/encoders.py" in default
      58.         return super(JSONEncoder, self).default(o)
    File "/usr/lib/python2.7/json/encoder.py" in default
      184.         raise TypeError(repr(o) + " is not JSON serializable")
    
    Exception Type: TypeError at /api/Participants/
    Exception Value: UUID('a00fef915e284f6d9d9af8b0500234b7') is not JSON serializable
    
    opened by brunofin 2
  • Incorrect max_length

    Incorrect max_length

    The default uuid version is uuid4(), which generates a UUID of length 36. However, the default max_length used is 32, and no easy option is provided to customize this length.

    You should increase the default length to 36 or higher, and provide max_length as a customizable option.

    opened by chrisspen 2
  • ImportError: cannot import name 'SubfieldBase'

    ImportError: cannot import name 'SubfieldBase'

    File "C:\Users\mgerd\AppData\Local\Programs\Python\Python36-32\lib\site-packages\uuidfield_init_.py", line 8, in from .fields import UUIDField File "C:\Users\mgerd\AppData\Local\Programs\Python\Python36-32\lib\site-packages\uuidfield\fields.py", line 4, in from django.db.models import Field, SubfieldBase ImportError: cannot import name 'SubfieldBase' how do i fix it?

    opened by miket0o 1
  • Django 1.8+

    Django 1.8+

    Django 1.8 dropped SubFieldBase

    I don't have a pull request for you as I'm using the field in a slightly different way that isn't reusable but here's what I did. You'll probably want to do some checks to maintain backwards compatibility as this will break old versions.

    I removed the import of SubfieldBase and the following line in the class:

    # __metaclass__ = SubfieldBase
    

    and added the class method:

    def from_db_value(self, value, expression, connection, context):
        if value is None:
            return value
        return self.get_db_prep_value(value)
    

    I haven't tested this either.

    opened by rjmoggach 1
  • Version 0.5.1 release

    Version 0.5.1 release

    Hi, David!

    I'd like to use django-uuidfield in my project that uses Python 3.4 and Django 1.7.

    Version 0.5.0 doesn't work, but all the necessary fixes are already in master branch.

    Due to my project specifics, I cannot use Git dependency, only PyPI version.

    Could you, please, release a new version of django-uuidfield? :) It's been a year since 0.5.0 already

    opened by kottenator 6
Owner
David Cramer
founder/cto @getsentry
David Cramer
Meta package to combine turbo-django and stimulus-django

Hotwire + Django This repository aims to help you integrate Hotwire with Django ?? Inspiration might be taken from @hotwired/hotwire-rails. We are sti

Hotwire for Django 31 Aug 9, 2022
django-reversion is an extension to the Django web framework that provides version control for model instances.

django-reversion django-reversion is an extension to the Django web framework that provides version control for model instances. Requirements Python 3

Dave Hall 2.8k Jan 2, 2023
Django-environ allows you to utilize 12factor inspired environment variables to configure your Django application.

Django-environ django-environ allows you to use Twelve-factor methodology to configure your Django application with environment variables. import envi

Daniele Faraglia 2.7k Jan 7, 2023
Rosetta is a Django application that eases the translation process of your Django projects

Rosetta Rosetta is a Django application that facilitates the translation process of your Django projects. Because it doesn't export any models, Rosett

Marco Bonetti 909 Dec 26, 2022
Cookiecutter Django is a framework for jumpstarting production-ready Django projects quickly.

Cookiecutter Django Powered by Cookiecutter, Cookiecutter Django is a framework for jumpstarting production-ready Django projects quickly. Documentati

Daniel Feldroy 10k Dec 31, 2022
Django project starter on steroids: quickly create a Django app AND generate source code for data models + REST/GraphQL APIs (the generated code is auto-linted and has 100% test coverage).

Create Django App ?? We're a Django project starter on steroids! One-line command to create a Django app with all the dependencies auto-installed AND

imagine.ai 68 Oct 19, 2022
django-quill-editor makes Quill.js easy to use on Django Forms and admin sites

django-quill-editor django-quill-editor makes Quill.js easy to use on Django Forms and admin sites No configuration required for static files! The ent

lhy 139 Dec 5, 2022
A Django chatbot that is capable of doing math and searching Chinese poet online. Developed with django, channels, celery and redis.

Django Channels Websocket Chatbot A Django chatbot that is capable of doing math and searching Chinese poet online. Developed with django, channels, c

Yunbo Shi 8 Oct 28, 2022
A handy tool for generating Django-based backend projects without coding. On the other hand, it is a code generator of the Django framework.

Django Sage Painless The django-sage-painless is a valuable package based on Django Web Framework & Django Rest Framework for high-level and rapid web

sageteam 51 Sep 15, 2022
A beginner django project and also my first Django project which involves shortening of a longer URL into a short one using a unique id.

Django-URL-Shortener A beginner django project and also my first Django project which involves shortening of a longer URL into a short one using a uni

Rohini Rao 3 Aug 8, 2021
Dockerizing Django with Postgres, Gunicorn, Nginx and Certbot. A fully Django starter project.

Dockerizing Django with Postgres, Gunicorn, Nginx and Certbot ?? Features A Django stater project with fully basic requirements for a production-ready

null 8 Jun 27, 2022
pytest-django allows you to test your Django project/applications with the pytest testing tool.

pytest-django allows you to test your Django project/applications with the pytest testing tool.

pytest-dev 1.1k Dec 14, 2022
APIs for a Chat app. Written with Django Rest framework and Django channels.

ChatAPI APIs for a Chat app. Written with Django Rest framework and Django channels. The documentation for the http end points can be found here This

Victor Aderibigbe 18 Sep 9, 2022
django-dashing is a customisable, modular dashboard application framework for Django to visualize interesting data about your project. Inspired in the dashboard framework Dashing

django-dashing django-dashing is a customisable, modular dashboard application framework for Django to visualize interesting data about your project.

talPor Solutions 703 Dec 22, 2022
Django-MySQL extends Django's built-in MySQL and MariaDB support their specific features not available on other databases.

Django-MySQL The dolphin-pony - proof that cute + cute = double cute. Django-MySQL extends Django's built-in MySQL and MariaDB support their specific

Adam Johnson 504 Jan 4, 2023
Django-Audiofield is a simple app that allows Audio files upload, management and conversion to different audio format (mp3, wav & ogg), which also makes it easy to play audio files into your Django application.

Django-Audiofield Description: Django Audio Management Tools Maintainer: Areski Contributors: list of contributors Django-Audiofield is a simple app t

Areski Belaid 167 Nov 10, 2022
django Filer is a file management application for django that makes handling of files and images a breeze.

django Filer is a file management application for django that makes handling of files and images a breeze.

django CMS Association 1.6k Jan 6, 2023
Twitter Bootstrap for Django Form - A simple Django template tag to work with Bootstrap

Twitter Bootstrap for Django Form - A simple Django template tag to work with Bootstrap

tzangms 557 Oct 19, 2022
Blog focused on skills enhancement and knowledge sharing. Tech Stack's: Vue.js, Django and Django-Ninja

Blog focused on skills enhancement and knowledge sharing. Tech Stack's: Vue.js, Django and Django-Ninja

Wanderson Fontes 2 Sep 21, 2022