How do I pass a context variable from a view to a custom field/widget in a Django template?

Viewed 4132

I have defined a custom field and widget for a form that is being served by subclassing UpdateView. So, something like this:

myapp/forms.py:

from .form_fields import MyCustomField
from .widgets import MyCustomWidget

class MyModelForm(forms.ModelForm):

    my_field = MyCustomField(queryset=MyModel.objects.all(), widget=MyCustomWidget)

myapp/views.py:

from django.views.generic import UpdateView
from .forms import MyModelForm

class MyView(UpdateView):
    form_class = MyModelForm

myapp/widgets.py:

from django.forms import Widget
from django.template.loader import render_to_string
from django.utils.safestring import mark_safe

class MyCustomWidget(Widget):
    context_data = { 'custom_data': custom_data }
    html_output = render_to_string('myapp/widgets/my_custom_widget.html', context_data)
    return mark_safe(html_output)

Basically, I want to be able to pass custom_data from my view (e.g. from the session store or the form instance) to the widget.

3 Answers

You can also overwrite Widget's get_context method:

# myapp/widgets.py
from django.forms import Widget
from django.template.loader import render_to_string
from django.utils.safestring import mark_safe

class MyCustomWidget(Widget):
    template_name = 'myapp/widgets/my_custom_widget.html'

    def __init__(self, attrs=None, extra_widget_data=None):
        self.extra_widget_data = extra_widget_data
        super(MyCustomWidget, self).__init__()

    def get_context(self, name, value, attrs):
        context = super().get_context(name, value, attrs)
        context['custom_data'] = self.extra_widget_data
        return context
Related