Django形成输入字段样式

时间:2016-03-10 20:20:08

标签: python django django-forms

我已经重新定义了联系我们页面的表单,这是标准的django-form内容,但我很难理解如何在<inpout>字段中编写说明。

准确地说,我想在Name字段内写<input>,所以我该怎么做呢。我将<input>字段定义为{{ form.name }},因此如何将其定义为更像<input type="name" class="form-control" id="id_name" placeholder="Your Name">

   <div class="col-xs-12 col-sm-12 col-md-4 col-md-offset-2 col-lg-4">
       {% if form.errors %}
           <p style="color: red">
               Please correct the error{{ form.errors|pluralize }} below.
           </p>
       {% endif %}

            <form class="form-horizontal" action="." method="POST">
                {% csrf_token %}
                <div class="field form-group">
                    {{ form.name.errors }}                        
                    <label for="id_name" class="control-label"></label>
                    <div class="col-sm-10">    
                        {{form.name}}
                    </div>
                </div>
                <div class="field form-group">
                    {{ form.email.errors }}                        
                    <label for="id_email" class="control-label"></label>
                    <div class="col-sm-10">
                        {{ form.email }}
                    </div>
                </div>
                <div class="field form-group">
                    {{ form.phone_number.errors }}                        
                    <label for="id_phone_number" class="control-label"></label>
                    <div class="col-sm-10">
                        {{ form.phone_number }}
                    </div>
                </div>
                <div class="field form-group">
                    {{ form.message.errors }}                        
                    <label for="id_message" class="control-label"></label>
                    <div class="col-sm-10">
                        {{ form.message }}
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-sm-12">
                        <input type="submit" class="btn btn-primary btn-block" value="Submit"></button>
                    </div>
                </div>
            </form>
          </div><!--/end form colon -->

1 个答案:

答案 0 :(得分:5)

If you want to modify the placeholder text, or other values of the field Django creates, it can be done in the form code using the widget's attrs:

class MyForm(forms.Form):
    name = forms.CharField(
        widget=forms.TextInput(
            attrs={
                'class': 'my-class',
                'placeholder': 'Name goes here',
            }))

如果您打算将所有代码保留在模板中,则必须手动创建每个输入字段,而不是使用Django渲染的字段。 You can still access the values of the generated field in the template to help you do that though.

<input name="{{ form.name.name }}" type="text" placeholder="Name field">