我有两种模式:
class ProductCategory(models.Model):
'''
Product Category determines to which category the product falls into.
'''
category_name = models.CharField(max_length=254)
def __unicode__(self):
return u"%s" %(self.category_name)
class Meta:
verbose_name_plural = "Product Categories"
class Product(models.Model):
'''
Product Information
'''
name = models.CharField(max_length=250)
category = models.ForeignKey(ProductCategory)
def __unicode__(self):
return u"%s" %(self.product_name)
我想在产品型号的autocomplete
类上应用field
。因此,
class ProductCategoryAutoComplete(autocomplete_light.AutocompleteModelBase):
search_fields = ['category_name']
model = Product
choices = ProductCategory.objects.all()
autocomplete_light.register(Product, ProductCategoryAutoComplete)
我也包含了模板。一切正常。除非我选择类别并提交表单html
字段,否则需要在底部弹出。有什么问题?
修改:表单
class ProductCreateForm(autocomplete_light.ModelForm):
category = forms.ModelChoiceField(queryset=ProductCategory.objects, widget=autocomplete_light.ChoiceWidget('ProductCategoryAutoComplete'))
class Meta:
model = Product
答案 0 :(得分:2)
Product.category
是建模Category
的FK,但您传递的自动填充(ProductCategoryAutoComplete
)已注册Product
模型!应该允许选择Category
的字段应使用Category
的自动填充,而不是Product
的自动填充;)
autocomplete_light.ModelForm
由于您使用的是autocomplete_light.ModelForm
,因此您无需指定字段。只需为Category
注册自动填充功能:
autocomplete_light.register(Category, search_fields=['category_name'])
让autocomplete_light.ModelForm
进行字段定义:
class ProductCreateForm(autocomplete_light.ModelForm):
class Meta:
model = Product
是的,您需要的全部;)
答案 1 :(得分:0)
search_fields
错误,产品没有字段category_name,如果我理解你的想法必须是:
class ProductCategoryAutoComplete(autocomplete_light.AutocompleteModelBase):
search_fields = ['category__category_name']
model = Product
choices = ProductCategory.objects.all()
autocomplete_light.register(Product, ProductCategoryAutoComplete)