微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

关系选择¶显示文本的小部件

如何解决关系选择¶显示文本的小部件

我想在我的 Test_Objekt 模型表单中显示 Test_Baustoff->art 模型的选择。

现在我正试图用一个小部件来解决它...

型号:

class Test_Objekt(models.Model):
   baustoffid = models.ForeignKey(Test_Baustoff,on_delete=models.CASCADE)
   bezeichnung = models.CharField(max_length=100,default='',blank=True)

class Test_Baustoff(models.Model):
   art = models.CharField(max_length=100)
   wert = models.IntegerField(default='0')

表单:(在 django 文档中找到此代码...不知道我是否以正确的方式使用它??)

class BaustoffidSelect(forms.Select):
    def create_option(self,name,value,label,selected,index,subindex=None,attrs=None):
        option = super().create_option(name,subindex,attrs)
        if value:
            option['attrs']['data-art'] = value.instance.art
        return option

class ObjektForm(forms.ModelForm):

        class Meta:
        model = Test_Objekt
        fields = ['bezeichnung','baustoffid','bauweiseid','dickeaussenwand','dickedaemmung','fensterqualitaet']
        labels = {'bezeichnung': 'Objekt-Bez'}
        widgets = {'baustoffid': BaustoffidSelect}

html 模板:

    <table class="table table-bordered table-light">
        {{objekt_form.as_table}}
    </table>

目前,我没有找到解决问题的方法。我看了一些教程或 StackOverflow 的问题,但到目前为止什么都没有。

你对这种处理有什么想法吗?

解决方法

尝试添加具有模型对象实例的元组列表:

Baustoff_choices = []
for i in Test_Baustoff.objects.all():
    Baustoff_choices.append(
        (i.id,i.art)
    ) #second element is what is this what will be displayed in template

然后在你的 forms.ModelForm 中:

baustoffid = forms.ChoiceField(choices=Baustoff_choices)
,

哦,非常感谢。这适用于 id!

我已经在尝试这种方法,但犯了一个错误,我想将其实现到我的模型...我不知道我还可以在我的表单中添加一个额外的字段.modelform

我在问自己什么。 是否也可以不保存 id 而是保存 foreykn 密钥对象

就像在模型中一样:

  #baustoffid = models.ForeignKey(Test_Baustoff,on_delete=models.CASCADE)

并在表单中:

for i in Test_Baustoff.objects.all():
    Baustoff_choices.append(
        (**i**,i.art) # or somithing like **i.instance**
    ) 

但我得到: 无法分配“'Test_Bauweise 对象 (2)'”:“Test_Objekt.bauweiseid”必须是“Test_Bauweise”实例。

亲切的问候!

,

解决了。 错过了在我的 models.py 中添加这个功能 所以它像“对象(1)”一样不高兴......

def __str__(self): return self.art

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。