views:

191

answers:

2

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.

+1  A: 

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
jdl2003
(Sorry for the late response, I was out of town this past week.)It's actually the former. In your example above, I would need the actual value of "yourfield" to be the label for the field called "value." So, something like (renaming the variables for clarity): namefield = opts.get_field("namefield") form.fields['quantityfield'].label = namefield.valueI will try fiddling around, using the samples you give to see if I can figure this out.thanks
Anthony
A: 

I posted this question because I had a model with two fields:

LabelField
ValueField

and I wanted to display a form that used "LabelField" as the label while allowing the user to update "ValueField." My first thought was to somehow assign the value of "LabelField" into the label attribute of "ValueField."

What I ended up doing instead was to set the "disabled" attribute of "LabelField" as true:

form.fields['labelfield'].widget.attrs['disabled'] = True

This allows me to display "labelfield" without letting the users update it. I can think of at least two other ways to accomplish this same goal, but this is what I'm using for now given my level of familiarity with Django et al.

Anthony
This doesn't work. The 'disabled' attribute prevents updates to the underlying model.
Anthony
Which is the same issue as is discussed in this thread:http://stackoverflow.com/questions/1105507/make-a-foreign-key-field-in-a-django-form-read-only-and-still-enable-the-form-to
Anthony