Any way to pass a variable into a django meta class?

Viewed 873

I am working on a django app that lets the user create a point on a map. This map needs to be centered at a certain location for ease of use, and this location is variable. I am using a LeafletWidget to let the user create this point.

The map can be centered by changing the attributes of the LeafletWidget. Unfortunately this widget is defined inside a Meta class, and as far as I understand you cannot pass a variable into it. Here an example of what I would like to do, somehow passing the variable center into the Meta class. center is a tuple with latitude and longitude values. This example code does not work of course. I don't know if you can somehow pass a variable into a Meta class.

class PointModelForm(ModelForm):
    class Meta(center):
        model = PointModel
        fields = ['name', 'point']
        widgets = {'point': LeafletWidget(attrs={'settings_overrides': {'DEFAULT_CENTER': center} })}

My best bet was defining the widgets attribute in the __init__ function, however Meta classes cannot access these attributes if I am correct. When I run this no widgets are used.

class PointModelForm(ModelForm):
    class Meta:
        model = PointModel
        fields = ['name', 'point']

    def __init__(self, center):
        super(PointModelForm, self).__init__()
        self.widgets = {'point': LeafletWidget(attrs={'settings_overrides': {'DEFAULT_CENTER': center} })}

Do you have any idea how to do this? Thanks in advance!

1 Answers

You can specify the attrs of a widget with:

class PointModelForm(ModelForm):
    class Meta:
        model = PointModel
        fields = ['name', 'point']

    def __init__(self, *args, center=None, **kwargs):
        super(PointModelForm, self).__init__(*args, **kwargs)
        if center is not None:
            attrs = self.fields['point'].widget.attrs
            subattrs = attrs.setdefault('settings_overrides', {})
            subattrs['DEFAULT_CENTER'] = center

You can then construct a PointModelForm with:

PointModelForm(center=(55, 12))  # for GET request
PointModelForm(request.POST, request.FILES, center=(55, 12))  # for POST request
Related