【问题标题】:how to define a widget in a model attribute如何在模型属性中定义小部件
【发布时间】:2023-04-07 19:17:02
【问题描述】:

简单地说,我写:

# forms.py
class NoteForm(ModelForm):
def __init__(self, *args, **kwargs): 
    super(NoteForm, self).__init__(*args, **kwargs)
    #add attributes to html-field-tag:
    self.fields['content'].widget.attrs['rows'] = 3
    self.fields['title'].widget.attrs['size'] = 20

class Meta:
    model = Note
    fields = ('title','content')

向 HTML 标签字段添加或修改某些属性。

但是这一次,我将不得不直接在models.py中的Note模型中进行

#models.py
class Note(models.Model):
    title =   models.CharField(max_length=100)
    content = models.TextField(max_length=255)
    #how to define the fields.widget.attrs here ?????

仅供参考:为什么?因为要作为一个

NotesFormSet = inlineformset_factory(NoteBook, Note, extra=10)

在添加/编辑笔记本时添加许多笔记

注意:这不是 django 管理员

如果我没有给你足够的上下文,请评论,任何提示都是赞赏=')

【问题讨论】:

    标签: python django django-forms


    【解决方案1】:

    不,您仍然在表单中执行此操作,但您只需将该表单作为参数传递给inlineformset_factory

    NotesFormSet = inlineformset_factory(NoteBook, Note, extra=10, form=NoteForm)
    

    【讨论】:

      猜你喜欢
      • 2015-03-21
      • 2016-09-01
      • 2011-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多