简体   繁体   中英

Django pass model to widget in ModelForm

I have a ModelForm that has an extra field that is a custom widget. I can add an extra field with a widget and pass arbitrary key values to it when constructing the widget. I'm also able to access model data within the ModelForm in the __init__ function.

My problem lies in that adding an extra field in the ModelForm requires doing so outside the __init__ function while accessing model data is only possible from within the __init__ function.

class SomeForm(forms.ModelForm):
        title = None
        def __init__(self, *args, **kwargs):
                some_data = kwargs['instance'].some_data
                # ^ Here I can access model data.
                super(SomeForm, self).__init__(*args, **kwargs)
                self.fields['some_extra_field'] = forms.CharField(widget= SomWidget())
                # ^ This is where I would pass model data, but this does not add the field.
        class Meta:
                model = Page 
                fields = "__all__"
        some_extra_field = forms.CharField(widget= SomeWidget())
        # ^ I can add a field here, but there's no way to pass some_data to it.

I've also tried setting self.some_data in __init__ , but it's still not accessible when I try to use self.some_data when setting some_extra_field at then end of the class.

How should pass model data to a widget in a ModelForm ?

If I'm following what you need correctly, you can do this simply by editing or reassigning the widget in __init__ . Something like:

class SomeForm(forms.ModelForm):
    title = None
    def __init__(self, *args, **kwargs):
        some_data = kwargs['instance'].some_data
        super(SomeForm, self).__init__(*args, **kwargs)
        # Pass whatever data you want to the widget constructor here
        self.fields['some_extra_field'].widget = SomWidget(foo=...))
        # or possibly (depending on what you're doing)
        self.fields['some_extra_field'].widget.foo = ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM