Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
394 views
Welcome To Ask or Share your Answers For Others

1 Answer

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...