简体   繁体   English

在 Django Forms 下拉列表中,如何显示通过外键访问的文本?

[英]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.

相关问题 如何在管理员中修复外键的修复下拉列表选择? [Django的] - How to fix foreign key's fix drop-down list selection in admin? [Django] Django表单中的动态下拉列表 - Dynamic drop-down list in Django forms Django的。 如何连接下拉列表(来自HTML)和表单? - Django. How to connect drop-down list (from html) and forms? 如果在 Django 中不可用,如何在下拉列表中显示类别并隐藏? - How To Show Category in Drop-down and Hide if Not Available in Django? 如何在 Django admin 中按字母顺序排列下拉列表? - How to alphabetically order a drop-down list in Django admin? django-autocompletion-light简单外键完成显示不可编辑的下拉窗口小部件 - django-autocompletion-light simple foreign key completion shows not editable drop-down widget Django:如何在下拉列表中进行选择并重定向到另一个页面? - Django: How can I take the choice in drop-down list and redirect to another page? 如何选择将以django形式在下拉列表中表示的值? - How can I choose the values that will be represented in a drop-down list in a form in django? 如何在Django中自定义下拉列表表单元素? - How can I customize a drop-down list form element in django? Django模板和下拉列表 - Django Templates and drop-down list
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM