我是 Python 和 Django 的新手,因此遇到了这个问题。我想要做的是使用 Django 表单创建 HTML Select 标记的行为。此下拉菜单/选择必须使用数据库中的值进行填充。
我已经拥有的是 location = forms.ModelChoiceField(queryset = MyModel.objects.all())
它确实给了我一个选择/下拉控件,但我需要它来显示一个值数据库并有一个不同的实际值(都来自同一个表,只是不同的列)
我在 HTML 代码中的意思是这样的:
<select>
<option value="1">Berlin</option>
<option value="2">New York</option>
<option value="3">London</option>
<option value="4">Riga</option>
</select>
因此,使用表格我会看到城市的名称,例如。伦敦,但是当它被选中并调用提交时,我在数据库中插入了 3。
期待您的建议。
编辑:
class Event(models.Model):
eventid = models.AutoField(primary_key=True)
date = models.DateField(blank=True, null=True)
time = models.TimeField(blank=True, null=True)
description = models.CharField(max_length=2000, blank=True, null=True)
price = models.IntegerField(blank=True, null=True)
locationid = models.ForeignKey(Location, models.DO_NOTHING, db_column='locationid', blank=True, null=True)
class Meta:
managed = False
db_table = 'event'
class Location(models.Model):
locationid = models.AutoField(primary_key=True)
name = models.CharField(max_length=256, blank=True, null=True)
capacity = models.IntegerField(blank=True, null=True)
type = models.CharField(max_length=256, blank=True, null=True)
cityid = models.ForeignKey(City, models.DO_NOTHING, db_column='cityid', blank=True, null=True)
class Meta:
managed = False
db_table = 'location'
所以我有一个对另一个表的 id 引用,我想从中获取位置名称并使用这些名称填充选择/下拉列表。当用户进行选择时,它不应采用名称,而应采用整数/ID。这有意义吗?
最佳答案
你可以试试这个
在表单中
class your_form(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(your_form, self).__init__(*args, **kwargs)
self.fields['location'].label_from_instance = self.label_from_instance
@staticmethod
def label_from_instance(obj):
return "Label %s" % obj.name
from django.forms import ModelChoiceField
class MyModelChoiceField(ModelChoiceField):
def label_from_instance(self, obj):
return "My Object #%i" % obj.id
引用this
关于python - 如何实现用数据库中的值填充的下拉列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58162125/