Skip to main content
 首页 » 编程设计

python之Django 表单输入字段样式

2025年05月04日49itcoder

我重新定义了联系我们页面的表单,这是标准的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 --> 

请您参考如下方法:

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">