我们可以格式化模型表单如何在模板上的 Django 中显示吗
Can we format as to how the Model Form displays in Django on template
所以我使用了 django 用户模型(来自 django.contrib.auth.models import User)并使用 ModelForm(来自 django.forms import ModelForm)创建了一个模型表单。当我在模板上显示它时,它作为用户名显示在 select 框中。我想显示它是 first_name 和 last_name.
这是我在 HTML
中用于表单的代码
<form class="form-horizontal" method="post" role="form">
{% csrf_token %}
<fieldset>
<legend>{{ title }}</legend>
{% for field in form %} {% if field.errors %}
<div class="form-group">
<label class="control-label col-sm-2">{{ field.label }}</label>
<div class="controls col-sm-10">
{{ field }}
<p class="formError">
{% for error in field.errors %}{{ error }}{% endfor %}
</p>
</div>
</div>
{% else %}
<div class="form-group">
<label class="control-label col-sm-2">{{ field.label }}</label>
<div class="controls col-sm-10">
{{ field }} {% if field.help_text %}
<p class="help-inline"><small>{{ field.help_text }}</small></p>
{% endif %}
</div>
</div>
{% endif %} {% endfor %}
</fieldset>
<div class="form-actions" style="margin-left: 150px; margin-top: 30px;">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
子类 ModelChoiceField
并覆盖 label_from_instance
以显示名字和姓氏。
from django.forms import ModelChoiceField
class UserChoiceField(ModelChoiceField):
def label_from_instance(self, obj):
return "%s %s" % (obj.first_name, obj.last_name)
然后使用模型表单中的选择字段。
from django import forms
from django.contrib.auth.models import User
class MyModelForm(forms.ModelForm):
user = UserChoiceField(queryset=User.objects.all())
...
所以我使用了 django 用户模型(来自 django.contrib.auth.models import User)并使用 ModelForm(来自 django.forms import ModelForm)创建了一个模型表单。当我在模板上显示它时,它作为用户名显示在 select 框中。我想显示它是 first_name 和 last_name.
这是我在 HTML
中用于表单的代码<form class="form-horizontal" method="post" role="form">
{% csrf_token %}
<fieldset>
<legend>{{ title }}</legend>
{% for field in form %} {% if field.errors %}
<div class="form-group">
<label class="control-label col-sm-2">{{ field.label }}</label>
<div class="controls col-sm-10">
{{ field }}
<p class="formError">
{% for error in field.errors %}{{ error }}{% endfor %}
</p>
</div>
</div>
{% else %}
<div class="form-group">
<label class="control-label col-sm-2">{{ field.label }}</label>
<div class="controls col-sm-10">
{{ field }} {% if field.help_text %}
<p class="help-inline"><small>{{ field.help_text }}</small></p>
{% endif %}
</div>
</div>
{% endif %} {% endfor %}
</fieldset>
<div class="form-actions" style="margin-left: 150px; margin-top: 30px;">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
子类 ModelChoiceField
并覆盖 label_from_instance
以显示名字和姓氏。
from django.forms import ModelChoiceField
class UserChoiceField(ModelChoiceField):
def label_from_instance(self, obj):
return "%s %s" % (obj.first_name, obj.last_name)
然后使用模型表单中的选择字段。
from django import forms
from django.contrib.auth.models import User
class MyModelForm(forms.ModelForm):
user = UserChoiceField(queryset=User.objects.all())
...