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

喜你入骨 提交于 2019-12-11 19:44:58

问题


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:


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


来源:https://stackoverflow.com/questions/32274808/can-we-format-as-to-how-the-model-form-displays-in-django-on-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!