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

2024-06-09 05:00:38 发布

您现在位置:Python中文网/ 问答频道 /正文

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

型号。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')

视图。py:

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

Book.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 %}

Forms.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'))
            )
        }

如您所见,结果如下: locations object(1), locations object(2)...

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


Tags: pydivformidtruemodelsformsorigin