python - 如何在 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">
解决方案
你不想要一个 ModelForm 这里,你不需要动态字段。您需要一个普通的表单,其中包含一个 ModelChoiceField,它将使用一个查询集自动填充所有选项。
class ItemForm(forms.Form):
title = forms.ModelChoiceField(
queryset=Item.objects.all(),
widget=forms.RadioSelect(attrs={'class': 'radioselect'})
)
推荐阅读
- xcode - 不要缩进 Xcode 风格的注释掉的代码
- python - 创建演示文稿时如何在 Google Slides API 中应用自定义布局
- python - DataFrameGroupBy 对象到 DataFrame
- javascript - Chrome 扩展程序不会在新标签页上自动激活
- javascript - 在元素样式上设置 .cssText 时转换不起作用?
- c# - 如何在运行时编辑 app.xaml 文件?
- php - PHP AES-128-CBC 使用十六进制密钥进行编码
- c - 数组的前 2 个元素在 for 循环后不显示在输出中
- c# - 在将类保存到 xml 文件之前加密属性
- django - 在Django中的整个表(所有字段,所有列,所有行)中查找一个字符串