2015-05-29 71 views
0

要解决Taggit问题,我试图在标记字段中的值被引入到模型中之前添加引号。这是我迄今为止的,但它不起作用。我究竟做错了什么?Django:在提交字段值之前修改字段值

class TagField(models.CharField): 

    description = "Simplifies entering tags w/ taggit" 

    def __init__(self, *args, **kwargs): 
     super(TagField, self).__init__(self, *args, **kwargs) 

    # Adds quotes to the value if there are no commas 
    def to_python(self, value): 
     if ',' in value: 
      return value 
     else: 
      return '"' + value + '"' 

class CaseForm(forms.ModelForm): 
    class Meta: 
     model = Case 
     fields = ['title', 'file', 'tags'] 
     labels = { 
      'file': 'Link to File', 
      'tags': 'Categories' 
     } 
     widgets = { 
      'tags': TagField() 
     } 
+0

我的回答是否有效? – metahamza

回答

0

你继承models.CharField,而应该继承forms.CharField,你指定在表单控件属性,但你要创建表单域的子类。

+0

当我这样做,我得到的错误:“int()参数必须是一个字符串,类似字节的对象或数字,而不是'TagField'” –

0

这个不起作用的原因是您正在定义一个自定义模型字段,然后尝试将其指定为窗体中的一个窗口小部件。如果您确实需要自定义小部件,则需要实际提供小部件实例,而不是模型字段实例。

但是为了获得您想要的行为,您需要将模型级别的字段声明为您的自定义字段类的实例。

尝试类似的东西 -

from django.db import models 

class TagField(models.CharField): 
    description = "Simplifies entering tags w/ taggit" 

    def __init__(self, *args, **kwargs): 
    super(TagField, self).__init__(*args, **kwargs) 

    # Adds quotes to the value if there are no commas 
    def to_python(self, value): 
    if any(x in value for x in (',', '"')): 
     return value 
    else: 
     return "\"%s\"" % value 

class ModelWithTag(models.Model): 
    tag = TagField(max_length = 100) 

to_python方法也由Model.clean(),这是表单验证过程中调用的调用,所以我认为这将提供你所需要的行为。

请注意,我还会检查to_python方法中是否存在双引号,否则每次调用save()时引号都会“堆叠”。