Can we format as to how the Model Form displays in Django on template

So I am using the django user model (from django.contrib.auth.models import User) and created a Model Form by using the ModelForm (from django.forms import ModelForm). When i display it on the template it shows up on the select boxes as usernames. i want to display it is first_name and last_name.

Thisis the code I am using for form in 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>

Subclass ModelChoiceField and override label_from_instance to display the first and last name.

from django.forms import ModelChoiceField

class UserChoiceField(ModelChoiceField):
    def label_from_instance(self, obj):
        return "%s %s" % (obj.first_name, obj.last_name)

Then use the choice field in your model form.

from django import forms
from django.contrib.auth.models import User

class MyModelForm(forms.ModelForm):
    user = UserChoiceField(queryset=User.objects.all())
    ...
链接地址: http://www.djcxy.com/p/56536.html

上一篇: 如何在python django的表格单元格中设置类名称?

下一篇: 我们可以格式化模型表单在模板中如何在Django中显示模型表单