0
votes

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

1 Answers

3
votes

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())
    ...