如何更改 Django 表单中下拉菜单的标签?

Mri*_*dul 0 python django django-forms

我有一个表单,要求用户从下拉列表中选择出发地和目的地。然而,标签并不是我想要的。我想改变这一点。

模型.py:

class locations(models.Model):
    id = models.AutoField(primary_key=True)
    location = models.TextField()

class drones(models.Model):
    origin = models.ForeignKey('locations', models.PROTECT, null=True, related_name='destination_id')
    destination = models.ForeignKey('locations', models.PROTECT, null=True, related_name='origin_id')
Run Code Online (Sandbox Code Playgroud)

视图.py:

def book(request):
    form = BookForm(request.POST or None)
    context = {
        "form": form
    }
    return render(request, '../../drone_system/templates/drone_system/book.html', context)
Run Code Online (Sandbox Code Playgroud)

书.html:

{% extends "drone_system/base.html" %}

{% block content %}
    <nav class="mx-auto card w-25" style=text-align:center;border:none;padding-top:12%>
        <form action="book" method="POST">{% csrf_token %}
            <h3 style="padding-bottom: 10px">Book</h3>
            <div class="form-group">
                <div>
                    <label for="Origin">Origin</label>
                    {{ form.origin }}
                    <br>
                    <label for="Destination">Destination</label>
                    {{ form.destination }}
                </div>
            </div>
            <button type="submit" class="btn btn-primary btn-lg btn-block">Book</button>
        </form>
    </nav>
{% endblock %}
Run Code Online (Sandbox Code Playgroud)

表格.py:

from django import forms
from django.forms import ModelForm
from .models import drones


class BookForm(ModelForm):
    class Meta:
        model = drones
        fields = ['origin', 'destination']
        widgets = {
            'origin': forms.Select(
                attrs={
                    'class': 'my-1 mr-2',
                },
                choices=((1, 'London'), (2, 'Plymouth'), (3, 'Swansea'), (4, 'Birmingham'), (5, 'Manchester'), (6, 'Edinburgh'), (7, 'Belfast'))
            ),
            'destination': forms.Select(
                attrs={
                    'class': 'my-1 mr-2',
                },
                choices=((1, 'London'), (2, 'Plymouth'), (3, 'Swansea'), (4, 'Birmingham'), (5, 'Manchester'), (6, 'Edinburgh'), (7, 'Belfast'))
            )
        }
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,结果如下: 位置对象(1),位置对象(2)...

相反,我想查看伦敦、普利茅斯等城市的名称。这些名称也是位置模型的一部分(locations.location)。我也尝试过在 forms.py 中使用选择,但它没有改变任何东西。我应该如何将其更改为城市名称?

Ami*_*udi 5

您必须添加__str__模型,使其具有字符串表示形式

class locations(models.Model):
    ...
    def __str__(self):
        return self.location

class drones(models.Model):
    ...
    def __str__(self):
        return self.destination.location
Run Code Online (Sandbox Code Playgroud)