Reputation: 143
I have a form that asks the user to choose an origin and destination from a drop down. However, the labels are not what I want them to be. I would like to change this.
Models.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')
Views.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'))
)
}
As you can see, this comes out as follows: locations object(1), locations object(2)...
I instead want to see names of cities like London , Plymouth etc. These names are part of the locations model as well(locations.location). I have also tried using choices in forms.py, but it hasn't changed anything. How should I change this to city names?
Upvotes: 1
Views: 1129
Reputation: 2279
You have to add __str__
in the model so it has a string representation
class locations(models.Model):
...
def __str__(self):
return self.location
class drones(models.Model):
...
def __str__(self):
return self.destination.location
Upvotes: 6