Django 表单字段显示记录的 uuid

Django form field is displaying uuid of the record

我正在使用 django 2.2 和 python 3.6。 我有一个 Django 模型。我正在使用脆皮表格在模板中显示表格。 表单不显示记录的值。它显示记录的 uuid 值。我需要显示记录名称值而不是 uuid 值。

models.py :

    @reversion.register()
class Staff(BaseModel):
    user = models.OneToOneField(
        User, on_delete=models.PROTECT, db_index=True, verbose_name=_("Kullanıcı"))
    photo = models.ImageField(
        upload_to="staff/", null=True, blank=True, verbose_name=_("Fotoğraf"))
    staff_type = models.ManyToManyField(
        StaffType, verbose_name=_("Personel Tipi"))
    name = models.CharField(
        max_length=100, db_index=True, verbose_name=_("İsim"))
    surname = models.CharField(
        max_length=100, db_index=True, verbose_name=_("Soyad"))
    phone = models.CharField(max_length=100, verbose_name=_("Telefon Numarası"))
    email = models.EmailField(verbose_name=_("Email"), db_index=True)
    address = models.TextField(verbose_name=_("Adres"))
    subject = models.ForeignKey(Subject, on_delete=models.SET(
        get_unknown_subject), verbose_name=_("Branş"))
    gender = models.IntegerField(
        choices=GENDERS, default=None, verbose_name=_("Cinsiyet"))
    nationality = models.CharField(
        choices=NATIONALITIES, max_length=100, verbose_name=_("Uyruk"))
    blood_type = models.CharField(
        choices=BLOOD_TYPES, max_length=20, verbose_name=_("Kan Grubu"))
    id_no = models.CharField(max_length=100, unique=True,
                             verbose_name=_("Kimlik No"))
    birthdate = models.DateField(verbose_name=_("Doğum Günü"))
    birthplace = models.CharField(max_length=200, verbose_name=_("Doğum Yeri"))
    education = models.IntegerField(
        choices=EDUCATION, default=None, verbose_name=_("Eğitim"))
    marital_status = models.BooleanField(
        default=True, verbose_name=_("Evlilik Durumu"))
    number_of_children = models.IntegerField(
        verbose_name=_("Çocuk Sayısı"))
    special_notes = models.TextField(
        null=True, blank=True, verbose_name=_("Özel Notlar"))
    registration_date = models.DateField(verbose_name=_("Kayıt Tarihi"))
    foreign_language = models.ForeignKey(Language,  on_delete=models.SET(
        get_default_language), null=True, blank=True, verbose_name=_("Yabancı Dil"))

    class Meta:
        permissions = (
            ("list_staff", _("List Staff")),
        )
        ordering = ['name', 'surname']

    def __unicode__(self):
        return "%s %s" % (self.name, self.surname)

    def save(self, *args, **kwargs):
        self.name = self.name.title()
        self.surname = self.surname.upper()
        groups = []
        for staff_type_object in self.staff_type.all():
            group = Group.objects.get_or_create(name=staff_type_object.name)[0]
            groups.append(group)
        self.user.groups = groups
        self.user.save()
        super(Staff, self).save(*args, **kwargs)

views.py:

    @login_required(login_url='/accounts/login/')
def personelkayit(request):
    staffs = Staff.objects.values("user__username", "name", "surname", "uuid")
    if request.method == 'GET':
        staff_uuid = request.GET.get("staff_uuid")
        if staff_uuid:
            instance = get_object_or_404(Staff, uuid=staff_uuid)
            form = StaffForm(instance=instance)
            form.fields['username'].initial = instance.user.username
            form.fields['username'].widget.attrs['readonly'] = True
        else:
            form = StaffForm()
        return render(request, 'personelkayit.html', {'form': form, 'staffs':
                                                     staffs, 'staff_uuid': staff_uuid})
    elif request.method == 'POST':
        staff_uuid = request.GET.get("staff_uuid")
        if staff_uuid:
            instance = get_object_or_404(Staff, uuid=staff_uuid)
            form = StaffForm(request.POST or None,
                             request.FILES or None, instance=instance)
        else:
            form = StaffForm(request.POST,  request.FILES or None)
        if form.is_valid():
            password = form.cleaned_data.get("password")
            re_password = form.cleaned_data.get("re_password")
            staff = form.save(commit=False)
            staff.user = user
            staff.save()
            form.save_m2m()            
            staff.save()
            return redirect('/')
        else:
            return render(request, "personelkayit.html", {'form': form, 'staffs': staffs})

personelkayit.html:

    {% extends 'base.html' %}
{% load crispy_forms_tags %}
{% load i18n %}
{% load staticfiles %}
{% block content %}

<br>

<table style="width: 100%">

<tr>

<td style="width: 4%"></td>

<td style="width: 92%">

<div class="block-area" id="basic">
            <form role="form" method="get">
            <select class="form-control input-sm m-b-10" name="staff_uuid">
                <option value="" {% if not staff_uuid %} selected="selected" {% endif %} disabled="disabled">{% trans "Personel" %}</option>
            {% for staff in staffs %}
            <option {% if staff_uuid and staff.uuid|lower == staff_uuid|lower %}selected="selected"{% endif %} value="{{ staff.uuid }}">{{ staff.user__username }} - {{ staff.name }} {{ staff.surname }}</option>
            {% endfor %}
            </select>

                <br />
                <button type="submit" class="btn btn-sm btn-alt">{% trans "Personel Düzenle" %}</button>
                <a class="btn btn-sm btn-alt" href="{% url 'personelkayit' %}">{% trans "Personel Ekle" %}</a>
            <div class="modal-footer"></div>
    </form>
</div>



<div class="block-area" id="basic">
    <form role="form" enctype="multipart/form-data" method="post">
        {% csrf_token %}
        {{ form|crispy }}
        <div >
            <br>
            <button style="background-color: #002266 !important; color: white !important" type="submit" class="btn btn-lg btn-alt"><span class="glyphicon glyphicon-floppy-disk
                    pull-left"></span>{% trans "Kaydet" %}</button>
        </div>
    </form>
    <br>
</div>

</td>

<td style="width: 4%"></td>

</tr>

</table>



<script>        
$( document ).ready(function() {
    $( "select[name$='staff_uuid']" ).select2({
        theme: "bootstrap"
    });         
    $( "select[name$='subject']" ).select2({
        theme: "bootstrap"
    }); 
    $( "select[name$='staff_type']" ).select2({
        theme: "bootstrap"
    }); 
});             
</script>

{% endblock content %}

发生这种情况的原因是因为 Django 将在表单中呈现模型对象的字符串表示形式。默认情况下,模型由对象类型的名称和主键呈现。所以像Subject object (...)这样的字符串是正常的。

您可以简单地为 Subject 模型实现一个 __str__(对于 一个 __unicode__),以按照您指定的方式呈现它:

class Subject(models.Model):
    # …

    def <b>__str__</b>(self):
        return …