[英]In a Django Forms drop-down list, how do I show text accessed via a foreign key?
I have code to edit a table "instruments", which has a foreign key to another table 'instrumenttype'.我有代码来编辑一个表“仪器”,该表具有另一个表“仪器类型”的外键。 I'd like to show a drop-down list showing the text values from the instreumenttype table.
我想显示一个下拉列表,其中显示了仪器类型表中的文本值。 My problem is that the drop-down list shows "InstrumentType object(n)" instead of the instrument type description from the other table.
我的问题是下拉列表显示“InstrumentType object(n)”而不是另一个表中的仪器类型描述。 The update works fine;
更新工作正常; when I get the selected value and update the instruments table, the correct key id is put in.
当我获得选定的值并更新仪器表时,会输入正确的键 ID。
Here is the form:这是表格:
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from instruments.models import Instrument
from instrumenttypes.models import InstrumentType
# Form used to edit the data pertaining to a specific instrument
class EditInstrumentForm(forms.ModelForm):
instrumenttype = forms.ModelChoiceField(queryset=InstrumentType.objects.all())
class Meta:
model = Instrument
fields = ('instrument', 'dateAdded', 'dateRemoved', 'nickname', 'serialNo', 'status',
'instrumenttype')
Here is the view snippet:这是视图片段:
def update_instrument_view(request, id=id):
instrument = get_object_or_404(Instrument, id=id)
if request.method == 'POST':
form = EditInstrumentForm(request.POST, request.FILES, instance=instrument)
if form.is_valid():
instrument.instrument = form.cleaned_data.get('instrument')
instrument.dateAdded = form.cleaned_data.get('dateAdded')
instrument.dateRemoved = form.cleaned_data.get('dateRemoved')
instrument.nickname = form.cleaned_data.get('nickname')
instrument.serialNo = form.cleaned_data.get('serialNo')
instrument.status = form.cleaned_data.get('status')
instrument.instrumenttype = form.cleaned_data.get('instrumenttype')
instrument.save()
messages.success(request, 'Your instrument has been updated.')
return redirect('instrument_details', instrument.id)
else:
form = EditInstrumentForm(instance=instrument)
messages.error(request, 'Issue updating data.')
return render(request, 'instrument_update.html', {'form': form, 'instrument':instrument})
else:
form = EditInstrumentForm(instance=instrument)
return render(request, 'instrument_update.html', {'form':form, 'instrument': instrument})
The drop down list shows the object reference, but I want it to show instrumenttype.instrumentType (which is a text description).下拉列表显示对象引用,但我希望它显示 instrumenttype.instrumentType (这是一个文本描述)。 snapshot of form output
表单输出快照
Here is the model of the instrument type table:这是仪器类型表的型号:
from django.db import models
from instrumenttypes.models import InstrumentType
from stations.models import Station
# Create your models here.
class Instrument(models.Model):
instrument = models.CharField(max_length=40)
instrumenttype = models.ForeignKey(InstrumentType, on_delete=models.CASCADE, null=True)
station = models.ForeignKey(Station, on_delete=models.CASCADE, default=1)
serialNo = models.CharField(max_length=60, null=True, blank=True)
dateAdded = models.DateTimeField("Date Added", null=True, blank=True)
dateRemoved = models.DateTimeField("Date Removed", null=True, blank=True)
status = models.CharField(max_length=10, null=True, blank=True)
nickname = models.CharField(max_length=40, null=True, blank=True)
Here is the model of the instruments table:这是仪器表的型号:
from django.db import models
from instrumenttypes.models import InstrumentType
from stations.models import Station
# Create your models here.
class Instrument(models.Model):
instrument = models.CharField(max_length=40)
instrumenttype = models.ForeignKey(InstrumentType, on_delete=models.CASCADE, null=True)
station = models.ForeignKey(Station, on_delete=models.CASCADE, default=1)
serialNo = models.CharField(max_length=60, null=True, blank=True)
dateAdded = models.DateTimeField("Date Added", null=True, blank=True)
dateRemoved = models.DateTimeField("Date Removed", null=True, blank=True)
status = models.CharField(max_length=10, null=True, blank=True)
nickname = models.CharField(max_length=40, null=True, blank=True)
I have read a lot of docs and related answers about this, but so far have not found a solution... frustrating because it seems like such a simple thing...我已经阅读了很多关于此的文档和相关答案,但到目前为止还没有找到解决方案......令人沮丧,因为它看起来很简单......
override the __str__
method on your model to return the appropriate description, like;覆盖模型上的
__str__
方法以返回适当的描述,例如;
def __str__(self):
return self.instrumentType
(note that you have your Instrument model twice in your question, not the InstrumentType model you mention, so not 100% sure that's the right field to access, but should be easy enough for you to make work if not) (请注意,您的问题中有两次 Instrument 模型,而不是您提到的 InstrumentType 模型,因此不能 100% 确定这是访问正确的字段,但如果不是,应该很容易让您工作)
If you wanted to call a custom method instead of relying on the __str__
behaviour, see https://docs.djangoproject.com/en/4.0/ref/forms/fields/#django.forms.ModelChoiceField.iterator :如果您想调用自定义方法而不是依赖
__str__
行为,请参阅https://docs.djangoproject.com/en/4.0/ref/forms/fields/#django.forms.ModelChoiceField.iterator :
from django.forms import ModelChoiceField
class InstrumentTypeModelChoiceField(ModelChoiceField):
def label_from_instance(self, obj):
return f"choice: {obj.instrumentType}"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.