Search code examples
djangodjango-modelsdjango-formswidgetdjango-widget

relationship choices¶widget showing text


I would like to display choices of Test_Baustoff->art Model in my Test_Objekt Model Form.

Right now i am trying to solve it with a Widget...

Models:

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')

Forms: (found this code in the django docs... don't know if i am using it in the right way??)

class BaustoffidSelect(forms.Select):
    def create_option(self, name, value, label, selected, index, subindex=None, attrs=None):
        option = super().create_option(name, value, label, selected, index, 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 template:

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

For the moment, I don't find a way to solve my problem. I looked some tutorials or StackOverflow questions but nothing up to now.

Do you have any idea about this handling?


Solution

  • Try to add a list of tuples with model object instances:

    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
    
    

    Then in your forms.ModelForm:

    baustoffid = forms.ChoiceField(choices=Baustoff_choices)