【问题标题】:django form with bootstrap带有引导程序的 django 表单
【发布时间】:2016-08-28 23:36:07
【问题描述】:

我正在尝试在 django 中处理表单。我来自 PHP 背景,从未使用过任何框架。我曾经自己用 HTML 和后端编写表单的所有字段。我用自己的方法来验证它们。

现在,来到 django,它具有模型形式。但是,我也想在我的代码中使用引导程序。所以,我写了这样的 HTML 代码:

<div class='form-group'>
 <label class='control-label col-md-2 col-md-offset-2' for='id_email'>Contact</label>
 <div class='col-md-6'>
   <div class='form-group'>
     <div class='col-md-11'>
       <input class='form-control' id='id_email' placeholder='E-mail' type='text'>
     </div>
   </div>
   <div class='form-group internal'>
    <div class='col-md-11'>
      <input class='form-control' id='id_phone' placeholder='Phone: (xxx) - xxx xxxx' type='text'>
    </div>
  </div>
</div>
</div>

现在,我想在后端验证它。我的模型看起来像:

class Student(models.Model):

    def __str__(self):
        return self.name

    name = models.CharField(max_length=200)
    enrollment_no = models.CharField(max_length=10)
    batch = models.CharField(max_length=4)
    father_income = models.IntegerField(max_length=100)
    email = models.CharField(max_length=1000)
    mobile_number = models.CharField(max_length=1000)

现在,验证上述表单的最佳方法是什么? 请帮我解决这个问题。

【问题讨论】:

  • 为什么不在你的表单类的 Meta 类中使用 modelForm 并定义小部件?然后,您可以确保您的表单元素以“引导友好”的方式呈现,例如 widgets = { 'name': forms.TextInput( attrs={ 'class': 'form-control', 'placeholder': 'Title', 'required': True, } ),},并且您的字段仍然可以通过您的表单类进行验证。
  • 能否请您提供有关这方面的任何文件?我是 Django 的新手。谢谢。

标签: python django forms twitter-bootstrap


【解决方案1】:

对于您的表单,您可以使用 django 的模型表单。您可以使用class Meta 向您的模型表单添加一些定义:

class StudentForm(forms.ModelForm):

    class Meta:
        model = Student
        fields = [
            'name', 'enrollment_no', # etc... 
        ]
        widgets = { 
            'name': forms.TextInput( attrs={ 'class': 'form-control', 'placeholder': 'Title', 'required': True, } ),
            'enrollment_no': # etc...
        }

    # you can also override validation/clean/save/etc methods here

*注意 - 因为您的所有字段都是必需的(根据您的模型,并且因为我们在这里使用模型表单),所以 django 将验证需要所有字段。

然后在您的模板中(假设您将上下文中的表单实例作为form 传递给您的模板)您可以像这样访问每个字段:

...
...
<div class='col-md-11'>
    {{ form.name }}
</div>
...
...

【讨论】:

    猜你喜欢
    • 2014-09-20
    • 2014-01-03
    • 2015-10-16
    • 1970-01-01
    • 2013-07-23
    • 2018-09-19
    • 1970-01-01
    • 2015-10-19
    • 2014-11-25
    相关资源
    最近更新 更多