【问题标题】:How to render a text box instead of a select box when using model form set使用模型表单集时如何呈现文本框而不是选择框
【发布时间】:2011-03-03 01:35:02
【问题描述】:

当我呈现我的表单集时,其中一个字段呈现为一个选择框,因为它是模型中的一个外来字段。有没有办法将其更改为文本输入?我想使用 Ajax 自动完成来填充该字段。向模型表单添加小部件不起作用,因为 modelformset_factory 采用模型而不是模型表单。

编辑

我的模型表格

class RecipeIngredientForm(ModelForm):
    class Meta:
        model = RecipeIngredient

        widgets = { 'ingredient' : TextInput(), }

我在我的观点中使用它

RecipeIngredientFormSet = modelformset_factory(RecipeIngredient, form=RecipeIngredientForm)
    objRecipeIngredients = RecipeIngredientFormSet()

编辑模型表格

class RecipeIngredientForm(ModelForm):
    ingredient2 = TextInput()
    class Meta:
        model = RecipeIngredient

我创建这样的表单集

RecipeIngredientFormSet = modelformset_factory(RecipeIngredient, form=RecipeIngredientForm)
    objRecipeIngredients = RecipeIngredientFormSet()

问题

我必须在 html 中使用表单集吗?我可以对生成的字段进行硬编码并使用 javascript 创建新字段并增加“form-TOTAL-FORMS”吗?如果可以的话,我就不必担心我的模型形式了。

谢谢

【问题讨论】:

标签: django django-forms


【解决方案1】:

modelformset_factory 确实采用了一种形式。这是来自django.forms.models 的函数签名:

def modelformset_factory(
           model, form=ModelForm, formfield_callback=lambda f: f.formfield(),
           formset=BaseModelFormSet,
           extra=1, can_delete=False, can_order=False,
           max_num=0, fields=None, exclude=None):

如果这对您不起作用,请显示一些代码,我会尝试看看出了什么问题。

在各种 cmets 之后编辑正如您所指出的,以这种方式使用时,小部件参数是错误的。所以解决方案是不要使用它——无论如何它都是最近添加的。相反,直接在表单上定义字段:

class RecipeIngredientForm(forms.ModelForm):
    ingredient = forms.ModelChoiceField(widget=forms.TextInput))
    class Meta:
        model = RecipeIngredient

【讨论】:

  • 我更新了我的代码,但我收到一条错误消息,上面写着“() 得到了一个意外的关键字参数 'widget'”。我只向函数传递了两个参数。
  • 您好丹尼尔,感谢您的回复。我无法渲染该字段,我仍然看到模型表单字段。
猜你喜欢
  • 1970-01-01
  • 2018-07-14
  • 1970-01-01
  • 2011-06-11
  • 2013-01-23
  • 1970-01-01
  • 1970-01-01
  • 2017-01-26
  • 2012-08-02
相关资源
最近更新 更多