[Answered ]-Relationship choices¶widget showing text

1👍

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)
👤mka

0👍

Oh Thanks a lot. This works fine with the id!

I was already trying this approach but made the mistake that i wanted to implement this into my models… I did not know that i can also add a extra field to my forms.modelform

what i was asking myself.
is it also possible to not save the id but a foreykn key object

like in models:

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

and in forms:

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

but i get:
Cannot assign "’Test_Bauweise object (2)’": "Test_Objekt.bauweiseid" must be a "Test_Bauweise" instance.

kind regards!

0👍

solved.
missed to add this function in my models.py
so it got displeyed like "Object(1)"…

def __str__(self): return self.art

Leave a comment