How to display a field from a modelchoice

42 Views Asked by At

I have a class in my forms and a object called tiposervico (ForeignKey). See bellow. In my template, after select a tiposervico I would like to display 'descricao' field on my screen. How can i do that?

class servicoForm(forms.ModelForm):
    tiposervico = forms.ModelChoiceField(queryset=tiposervico.objects.all(), required=True)

tiposervico -> id, descricao

1

There are 1 best solutions below

0
On

You can override the label_from_instance of the field inside the get_form() method in CBV and get access to the field with lambda

def get_form(self, form_class=None):
    form = super(ModelView, self).get_form()
    form.fields['field_name'].label_from_instance = lamda x : x.model_field_name_to_display
    return form

For FBV, you can do so after initializing your form;

form = FormName()
form.fields['field_name'].label_from_instance = lamda x : x.model_field_name_to_display