Andrew Fount Andrew Fount - 3 months ago 12
Python Question

Set Media dynamically for Django widget

Is it possible to add media inside

__init__
in a
Widget
?

I need to find language of page and pass it to widget, but it appears that middleware for processing request works after the media initialization.

So, basically what I have:

class SimpleMiddleware():
# some code for getting language...


class MyWidget(Widget):

class Media:
js = (
'//some source&language='+translation.get_language(),
)


translation.get_language
gives incorrect language, since the middleware didn't execute code before media.

Answer

You need to set media as a dynamic property:

class MyWidget(Widget):    
    def _media(self):
        return forms.Media(js=(
            '//some source&language='+translation.get_language(),
        ))
    media = property(_media)