django auto complete light表示ForeignKey需要字段

时间:2014-05-19 13:15:14

标签: django django-autocomplete-light

我有两种模式:

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

2 个答案:

答案 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)