Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I reference the underlying model of a django model form object?

When creating a form, I wish to use one field on the model as a label to go with another field that I'm updating.

I've overridden the BaseModelFormSet with a new ___init____ method, like this:

class BaseMyFormSet(BaseModelFormSet):
    def __init__(self, *args, **kwargs):
       super(BaseMyFormSet, self).__init__(*args, **kwargs)
    for form in self.forms:
           form.fields['value'].label = ???

How do I reference the other field in the model so that I can use it as the label value?

(Alternatively, if there's a better way to override the label in the way I need, that would be very helpful as well.)

Thanks.

like image 490
Anthony C Avatar asked Nov 05 '22 19:11

Anthony C


1 Answers

I'm not entirely clear on your goal, are you trying to use the value of a field for a particular instance of a model or are you just trying to use the model field's own name or help_text attribute from the model definition?

I'm guessing you want to do the latter. If so, you can access the model information like this in your init method:

for form in self.forms:
    opts = self.model._meta
    field = opts.get_field("yourfield")
    form.fields['value'].label = field.name

Or

form.fields['value'].label = field.help_text
like image 194
Jesse L Avatar answered Nov 12 '22 13:11

Jesse L