使用Bootstrap和Django格式化表单的字段

jvidinwx  于 2023-08-08  发布在  Go
关注(0)|答案(1)|浏览(124)

我有一个由Django中的模型生成的表单,由文本区域,选择字段,切换字段等生成:

class Test(models.Model):
    workerID = models.CharField(max_length=200, blank=True, null=True)
    dashboardURL = models.URLField(blank=True)
    centralinaVecchia = models.BooleanField(default=False)

字符串
我已经用

class StartWorker(ModelForm):
    class Meta:
        model = Test
        fields = ('testTitle', 'testDescription', 'centralinaVecchia')
        labels = {
            "testTitle": _("Titolo"),
            "testDescription": _("Descrizione"),
            "centralinaVecchia": _("Centralina Vecchia?"),
        }

        widgets = {
            'testTitle': forms.TextInput(attrs={'class':'form-control'}),
            'testDescription': forms.Textarea(attrs={'class':'form-control'}),
            'centralinaVecchia': forms.CheckboxInput(attrs={'class':'form-check-input'}),


问题是,如果每个字段的格式都是正确的,一个在另一个下面,那么复选框的位置就很奇怪了(见屏幕截图)


的数据
我无法将它的样式设置为表单的其他部分。根据documentation,我需要在<div class="form-check"></div>中添加复选框,但我不知道如何在Django中完成
该模板简单如

<form method="post">
  {% csrf_token %} {{ form }}
    <button class="btn btn-primary" type="submit" value="Submit">
      Submit
    </button>
</form>

llew8vvj

llew8vvj1#

试试这个代码

forms.py

class StartWorker(forms.ModelForm):

    class Meta:
        model = Test
        fields = "__all__"
        labels = {
            "workerID":"Worker",
            "dashboardURL":"Dashboard Url",
            "centralinaVecchia":"Centralina Vecchia?",
        }

        widgets = {
            'workerID': forms.TextInput(attrs={'class':'form-control'}),
            'dashboardURL': forms.Textarea(attrs={'class':'form-control'}),
            'centralinaVecchia': forms.CheckboxInput(attrs={'class':'form-check-input'}),}

字符串

Html代码

<div class="container p-5">
  <div class="row mx-auto">
    <div class="mb-3">
      <label  class="form-label">{{form.workerID.label_tag}}</label>
      {{form.workerID}}
    </div>
    <div class="mb-3">
      <label  class="form-label">{{form.dashboardURL.label_tag}}</label>
      {{form.dashboardURL}}
    </div>
    <div class="mb-3 form-check">
      <label  class="form-label">{{form.centralinaVecchia.label_tag}}</label>
      {{form.centralinaVecchia}}
    </div>
  </div>
</div>

浏览器输出


的数据

相关问题