Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在django的表单中从模型字段设置attr_Python_Django - Fatal编程技术网

Python 如何在django的表单中从模型字段设置attr

Python 如何在django的表单中从模型字段设置attr,python,django,Python,Django,如何基于模型方法返回值或仅基于模型字段名为html模板设置特定属性 我已经知道可以通过\uuuu init\uuuu函数或类似的小部件覆盖字段: 型号.py class Item(models.Model): title = models.CharField(verbose_name=u"name", max_length=200, blank=False, null=False) def __str__(self): retur

如何基于模型方法返回值或仅基于模型字段名为html模板设置特定属性

我已经知道可以通过
\uuuu init\uuuu
函数或类似的小部件覆盖字段:

型号.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)

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
          })
forms.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)

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
          })

这里不需要模型表单,也不需要动态字段。您需要一个普通表单,其中包含一个ModelChoiceField,该字段将使用queryset自动填充所有选项

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