Django:在提交字段值之前修改字段值
为了解决Taggit的问题,我尝试在将值传输到模型之前在tag字段中的值周围添加引号。这是我目前所拥有的,但它不起作用。我做错了什么Django:在提交字段值之前修改字段值,django,django-forms,Django,Django Forms,为了解决Taggit的问题,我尝试在将值传输到模型之前在tag字段中的值周围添加引号。这是我目前所拥有的,但它不起作用。我做错了什么 class TagField(models.CharField): description = "Simplifies entering tags w/ taggit" def __init__(self, *args, **kwargs): super(TagField, self).__init__(self, *args,
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()
}
您正在子类化models.CharField,而应该子类化forms.CharField,您正在为表单中的小部件属性指定子类,但您正在尝试创建表单字段子类。这不起作用的原因是您正在定义自定义模型字段,然后尝试将其指定为表单中的小部件。如果确实需要自定义小部件,则需要实际提供小部件实例,而不是模型字段实例 但要获得所需的行为,需要在模型级别将字段声明为自定义字段类的实例 试试像这样的东西-
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方法中您的条件中是否存在双引号,否则每次调用save时引号都会继续堆积起来。当我这样做时,我得到了错误:int参数必须是字符串、类似于object或数字的字节,而不是“TagField”,我的答案对您有用吗?