首页 > 解决方案 > 如何在 django 的表单中从模型字段设置 attr

问题描述

如何根据模型方法返回值或仅模型字段名称为 html 模板设置特定属性?

我已经知道可以通过__init__函数或小部件覆盖字段,如下所示:

模型.py

class Item(models.Model):
        title = models.CharField(verbose_name=u"name", max_length=200, blank=False, null=False)

        def __str__(self):
                return ("%s" % self.title)

表格.py

class ItemForm(forms.ModelForm):
        class Meta:
            model = Item

fields = ['title',]

widgets = {
         'title': forms.RadioSelect(attrs={
                 'class': 'radioselect',
                 'item_name': 'title name?' # <- i want to have title name here of each not statis string
          }),
}
def __init__(self, *args, **kwargs):
    super(ItemForm, self).__init__(*args, **kwargs)
          self.fields['title'].widget.attrs.update({
                  'item_name': '' # <- i want to have title name here of each not statis string
          })

但是,我想根据模型中预先定义的字段来设置特定的字段名称,而不仅仅是像上面提到的示例中那样的静态字符串。如果我添加Item到带有title =“Apple”的数据库中,我想将此字符串插入此属性以在模板中获得这样的预期结果:

<input type="radio" class="radioselect" item_name="Apple">

标签: pythondjango

解决方案


你不想要一个 ModelForm 这里,你不需要动态字段。您需要一个普通的表单,其中包含一个 ModelChoiceField,它将使用一个查询集自动填充所有选项。

class ItemForm(forms.Form):
    title = forms.ModelChoiceField(
        queryset=Item.objects.all(),
        widget=forms.RadioSelect(attrs={'class': 'radioselect'})
    )

推荐阅读