Giter Club home page Giter Club logo

django-uuidfield's Introduction

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!

django-uuidfield's People

Contributors

chris-martin avatar coagulant avatar dcramer avatar hobbestigrou avatar jezdez avatar ksonbol avatar luto avatar pidelport avatar rca avatar vitaly4uk avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

django-uuidfield's Issues

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?

Provide UUIDMixin in the models

Something like this:

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

    class Meta:
        abstract = True

And it could be used like this:

from uuidfield.models import UUIDMixin
class MyClass(UUIDMixin, models.Model):
    title = models.CharField(max_length=200)

    def __unicode__(self):
        return self.title

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.

UUIDField not cleaning up when using objects.get/objects.get_or_create()

SomeModel.objects.create(id='e86da5fb-9935-4ff7-9b04-d9d508d15fc7')

Then, the following will fail:
SomeModel.objects.get(id='e86da5fb-9935-4ff7-9b04-d9d508d15fc7')

Because the id is actually properly saved as 'e86da5fb99354ff79b04d9d508d15fc7'. But it should be cleaning it in both places.

coercing to Unicode: need string or buffer, StringUUID found

Why do I need to wrap the field in unicode() to make it usable?

unicode(self.order_id)

If I don't I get:

coercing to Unicode: need string or buffer, StringUUID found

This makes it impossible to use in eg. the modellist without wrapping it in a method.

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

Serialization failure on Python3 due to unicode calls

The uuidfield module has some unicode calls that are blocking data serialization on Python 3.

IMHO, these calls as well as any __unicode__ methods should be dropped in favor of __str__ since there is no non-ASCII char in UUIDs anyway.

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?

unicode() method does not work in Python 3.3

Hi,

I recently submitted a fix for django-haystack so that UUID pk fields would work properly.
https://github.com/toastdriven/django-haystack/pull/1115

However, I notice that the Haystack tests for Python 3.3 fail because of:
(From https://travis-ci.org/toastdriven/django-haystack/jobs/44221681)

...
File "/home/travis/build/toastdriven/django-haystack/django_uuidfield-0.5.0-py3.3.egg/uuidfield/fields.py", line 26, in unicode
return unicode(str(self))
nose.proxy.NameError: Problem installing fixture '/home/travis/build/toastdriven/django-haystack/test_haystack/core/fixtures/initial_data.json': global name 'unicode' is not defined
...

In the unicode method for the field, a simple check of whether this is Python 2 or 3 might be the way to go.

Thanks,
/mike

UUIDField in Admin?

Is there a trick to getting a UUID field to show up in the modeladmin? I have several models with UUIDFields, and while i can see the uuid field value in the shell, the field is not listed with the others in the (mostly-default) admin views.

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

Inconsistent backend UUID values in method get_db_prep_value()

Besides #46, another issue with method get_db_prep_value is inconsistency of hyphens.

Let's say we pass the value as a UUID object UUID('00010203-0405-0607-0809-0a0b0c0d0e0f'). The method returns str(value), which, according to Python doc, is stringified with hyphen '00010203-0405-0607-0809-0a0b0c0d0e0f'. However, if we pass a string '00010203-0405-0607-0809-0a0b0c0d0e0f', the method will return a non-hyphen version of it. It doesn't matter with PostgreSQL which supports UUID type, but for other backends where UUID is stored as a char32 the inconsistency would be a problem.

StringUUID not scriptable

What I did:
Added the field to a model.

Did a sync db

created a record in the admin

got an error saying String UUID is not scriptable

Add ability to specify title

In some cases you want to show the UUID field and it would be great if it would be possible to specify a title.

order_id = UUIDField('Order ID', auto=True)

Encounting syntax error when running Django 1.6 on Python 3.3

I set up a test app running Django 1.6. I created a class in models.py containing an attribute having UUIDField. Works fine. But when I run this with Python 3.3, I get the following error:

Validating models...

Unhandled exception in thread started by <function check_errors..wrapper at 0x10f9063b0>
...

from uuidfield import UUIDField
File "/Users/jeff/Env/django16/lib/python3.3/site-packages/uuidfield/init.py", line 4
except Exception, e:
^
SyntaxError: invalid syntax

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.

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

a bug when hyphenate=true

django-uuid have a bug when field's attr 'hyphenate' is true . the uuid is 36 length , but the value get from session is still 32 length . so the cookie can't match session so is it!

Support for BinaryField in Django 1.6+

As of 1.6, BinaryField has been added to Django, which enables the kind of storage you mentioned originally wanting for UUIDs.

Although, based on a look at the Django source code, it looks like BinaryField is actually stored as a "longblob" in my MySQL, which has a different size requirement than 16 bytes. In this case, it would be up to 20 bytes total for the field, according to the documentation on MySQL Storage Requirements.

One more potential downside is that, according to the docs, you cannot filter on a BinaryField. So, overall, this might not be that useful or we might have to do more work to add filter support.

Would it be a good idea to add this?

Other links:

django.db.utils.ProgrammingError: column "uuid" is of type uuid but default expression is of type integer

I tried to push to heroku but got the following error:
Applying accounts.0004_group_uuid...Traceback (most recent call last):
File "manage.py", line 10, in
execute_from_command_line(sys.argv)
File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/init.py", line 385, in execute_from_command_line
utility.execute()
File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/init.py", line 377, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/base.py", line 288, in run_from_argv
self.execute(_args, *_options.dict)
File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/base.py", line 338, in execute
output = self.handle(_args, *_options)
File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 161, in handle
executor.migrate(targets, plan, fake=options.get("fake", False))
File "/app/.heroku/python/lib/python2.7/site-packages/django/db/migrations/executor.py", line 68, in migrate
self.apply_migration(migration, fake=fake)
File "/app/.heroku/python/lib/python2.7/site-packages/django/db/migrations/executor.py", line 102, in apply_migration
migration.apply(project_state, schema_editor)
File "/app/.heroku/python/lib/python2.7/site-packages/django/db/migrations/migration.py", line 108, in apply
operation.database_forwards(self.app_label, schema_editor, project_state, new_state)
File "/app/.heroku/python/lib/python2.7/site-packages/django/db/migrations/operations/fields.py", line 37, in database_forwards
field,
File "/app/.heroku/python/lib/python2.7/site-packages/django/db/backends/schema.py", line 378, in add_field
self.execute(sql, params)
File "/app/.heroku/python/lib/python2.7/site-packages/django/db/backends/schema.py", line 102, in execute
cursor.execute(sql, params)
File "/app/.heroku/python/lib/python2.7/site-packages/django/db/backends/utils.py", line 81, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/app/.heroku/python/lib/python2.7/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
File "/app/.heroku/python/lib/python2.7/site-packages/django/db/utils.py", line 94, in exit
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/app/.heroku/python/lib/python2.7/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: column "uuid" is of type uuid but default expression is of type integer
HINT: You will need to rewrite or cast the expression.

Any idea how to fix this?

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.

Form validation of mal-formed uuid is broken

While working on #30, I wrote this test:

class FormUUIDField(TestCase):

    def test_formfield_error(self):
        form = ManualUUIDForm({'uuid': '123'})
        self.assertFalse(form.is_valid())

This test fails. I did not check much, but I think the reason/fix is this:

    1. to_python should raise ValidationError (i.e. wrap the StringUUID in a try except ValueError and re-raise an appropriate ValidationError)
    1. the formfield method gives CharField as form_class, this has the effect that the to_python that is called is the CharField, this should change so that the correct to_python is called.

I excluded the tests from that PR #30, as this is broken in the current version and can be fixed independently of #30.

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.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.