<p>您不需要覆盖模型字段。见<a href="https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#field-types" rel="nofollow noreferrer"><strong>Field types</strong></a>-<a href="https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#field-types" rel="nofollow noreferrer">Django Docs</a></p>
<blockquote>
<p>If the model field has choices set, then the form field’s widget will
be set to Select, with choices coming from the model field’s choices.</p>
</blockquote>
<p>以下代码应该执行您想要的操作:</p>
<p><strong>forms.py</strong></p>
<pre><code>from django import forms
from .models import Car
class CarForm(forms.ModelForm):
class Meta:
model = Car
fields = ['owner_name', 'car_type']
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['owner_name'].widget.attrs.update({"class": "form-control"})
# or iterate over field to add class for each field
for field in self.fields:
self.fields[field].widget.attrs.update({'class':"form-control"})
</code></pre>
<p>您可以在<code>__init__</code>方法中添加任何html属性</p>
<p><strong>html:</strong></p>
<pre><code><form method="post" class="form-group">
{% csrf_token %}
<div class="form-group col-md-12 mb-3">
<label for="{{ form.owner_name.label }}">{{ form.owner_name.label }}</label>
{{ form.owner_name }}
</div>
<div class="form-group col-md-12 mb-3">
<label for="{{ form.car_type.label }}">{{ form.car_type.label }}</label>
{{ form.car_type }}
</div>
<hr class="mb-4">
<button type="submit" class="btn btn-secondary btn-lg btn-block">Submit New Car</button>
</form>
</code></pre>
<p>或者您可以使用<a href="https://docs.djangoproject.com/en/dev/topics/forms/#working-with-form-templates" rel="nofollow noreferrer"><strong>^{<cd2>}</strong></a>-<a href="https://docs.djangoproject.com/en/dev/topics/forms/#working-with-form-templates" rel="nofollow noreferrer">Django Docs</a>将它们包装在<code><p></code>标记中</p>
<p><strong>更新</strong></p>
<hr/>
<p>手动渲染窗体:</p>
<pre><code><form method="post" class="form-group">
{% csrf_token %}
<div class="form-group col-md-12 mb-3">
<label for="{{ form.owner_name.label }}">{{ form.owner_name.label }}</label>
<input type="text" class="form-control" id="{{ form.owner_name.auto_id }}" name="{{ form.owner_name.name }}">
</div>
<div class="form-group col-md-12 mb-3">
<label for="{{ form.car_type.label }}">{{ form.car_type.label }}</label>
<select id="{{ form.car_type.auto_id }}" name="{{ form.car_type.name }}">
{% for value, label in form.fields.car_type.choices %}
<option value="{{ value }}"{% if form.car_type.value == value %} selected{% endif %}>{{ label }}</option>
{% endfor %}
</select>
</div>
<hr class="mb-4">
<button type="submit" class="btn btn-secondary btn-lg btn-block">Submit New Car</button>
</form>
</code></pre>