2015-05-29 140 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()時引號都會「堆疊」。