如何在引导表单字段中使用我的modelForm字段?

时间:2018-10-28 18:52:20

标签: django twitter-bootstrap django-templates

我的forms.py看起来像这样

class UserRegistration(UserCreationForm):
    def __int__(self, *args, **kwargs):
        super(UserRegistration, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_id = 'id-registrationForm'
        self.helper.form_class = 'u-form--modern'
        self.helper.form_method = 'post'
        self.helper.form_action = 'submit_form'

        self.helper.add_input(Submit('submit', 'Submit'))

    class Meta:
        model = User

        fields = ['first_name',
                  'username',
                  'last_name',
                  'email',
                  'password1',
                  'password2']

我的模板如下所示(我只显示1个字段,因为它们或多或少相似)

<form class="js-validate mt-5" id="id-registrationForm" method="post">
 <div class="js-form-message mb-4">
                        <label class="h6 small d-block text-uppercase "> Email address</label>
                        <div class="js-focus-state input-group u-form">
                            <input type="email" class="form-control u-form__input" name="email"
                                   placeholder="your@email.com">
                        </div>
                    </div>

不幸的是,我的前端技能接近于0,我无法真正找到如何在引导程序的预制表单中使用我的{{form.email}}。我需要这个来提交我的modelForm并注册一个用户。
为了清楚起见,我希望我的django表单看起来像底部的表单 form example

2 个答案:

答案 0 :(得分:0)

很简单!首先安装bootstrap4:

  

pip install django-bootstrap4

然后在您的html文件中加载bootstrap4和表单:

{% load bootstrap4 %}
<form method="post">
  {% csrf_token %}
  {% bootstrap_form form %}
  <input type="submit" class="btn btn-primary" value="submit">
</form>

我建议您将表单更改为如下形式:

from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserCreationForm
from django import forms


class UserCreateForm(UserCreationForm):

    class Meta():
        fields = ['username', 'email', 'password1', 'password2']
        model = get_user_model()
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

答案 1 :(得分:0)

我实际上是在django-widget-tweaks的帮助下提出了解决方案的

{% load widget_tweaks %}
<div class="js-form-message mb-4">
     <div class="js-focus-state input-group u-form u-form">
           <label class="h6 small d-block text-uppercase "> Email address</label>
                 <div class="js-focus-state input-group u-form">
                    {{ form.email|add_class:"form-control u-form__input u-form" }}
                            </div>
                        </div>

至少对我来说,django小部件调整在如何将自定义CSS添加到表单方面更加直观

我的forms.py

class UserRegistration(UserCreationForm):
    email = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'email@email.com'}))

class Meta:
    model = User

    fields = ['first_name',
              'username',
              'last_name',
              'email',
              'password1',
              'password2']