Adding Simple Custom Field to Django — How to Write South Introspection Rules

自古美人都是妖i 提交于 2020-01-01 09:53:27

问题


I am trying to add a custom field to my Django project that uses South. Because of this, I am trying (for the first time) to write introspection rules for South. I believe my case is the simplest possible as I am simply extending a CharField. Specifically:

class ColorField(models.CharField):
    def __init__(self, *args, **kwargs):
        kwargs['max_length'] = 10
        super(ColorField, self).__init__(*args, **kwargs)

    def formfield(self, **kwargs):
        kwargs['widget'] = ColorPickerWidget
        return super(ColorField, self).formfield(**kwargs)

This is from a Django snippet called jQuery color picker model field for those interested.

Since I am not adding any new attributes, I believe I only have to add these lines of code:

from south.modelsinspector import add_introspection_rules
add_introspection_rules([], ["^myproject\.myapp\.models\.ColorField"])

It is probably obvious, but where should they go? Also, is my assumption that this is all I have to do correct?

I have reviewed several questions posted here, but most deal with much more complex introspections.

Per http://south.readthedocs.org/en/latest/customfields.html#where-to-put-the-code, I have tried puttin the code at the top of my models.py file where the custom field is defined. But this has not worked.


回答1:


Simple answer: yes, the code should go in the models.py file where the field was defined. The correct code is:

from south.modelsinspector import add_introspection_rules
add_introspection_rules([], ["^myapp\.models\.ColorField"])

Not sure why I was putting the project name in there.




回答2:


You have to make sure that the path to the file is correct. The one you mention looks similar to one I am using, but the path is:

add_introspection_rules([], ["^colors\.fields\.ColorField"])


来源:https://stackoverflow.com/questions/11642268/adding-simple-custom-field-to-django-how-to-write-south-introspection-rules

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!