A very simple custom Django field

I am trying to make a very simple custom field, but cannot make it work.

I am currently adding this field to almost all the models in my application. I would like it to be listed as a custom field to avoid code duplication.

identifier = models.CharField( max_length = 20, unique = True, validators = [validators.validate_slug], help_text = "Help text goes here." ) 

What I have:

 class MyIdentifierField(models.CharField): description = "random string goes here" __metaclass__ = models.SubfieldBase def __init__(self, *args, **kwargs): kwargs['max_length'] = 20 kwargs['unique'] = True kwargs['validators'] = [validators.validate_slug] kwargs['help_text'] = "custom help text goes here" super(MyIdentifierField, self).__init__(*args, **kwargs) def db_type(self, connection): return 'char(25)' 

so that I can use it as follows:

 identifier = MyIdentifierField() 

However, when I do python manage.py schemamigration --auto <myapp> , I get the following error:

  ! Cannot freeze field 'geral.seccao.identifier' ! (this field has class geral.models.MyIdentifierField) ! South cannot introspect some fields; this is probably because they are custom ! fields. If they worked in 0.6 or below, this is because we have removed the ! models parser (it often broke things). ! To fix this, read http://south.aeracode.org/wiki/MyFieldsDontWork 

I looked at the recommended webpage but still cannot find a workaround. Any help is appreciated. Thanks.

+4
source share
1 answer

You need to help Sub a bit in describing your field. There are two ways to do this: http://south.aeracode.org/wiki/MyFieldsDontWork

My preferred method is to add a triple of fields to the field field:

 def south_field_triple(self): try: from south.modelsinspector import introspector cls_name = '{0}.{1}'.format( self.__class__.__module__, self.__class__.__name__) args, kwargs = introspector(self) return cls_name, args, kwargs except ImportError: pass 

Hope this helps you.

+6
source

Source: https://habr.com/ru/post/1492975/


All Articles