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.
I figured it out; I'm not totally sure if this is the best/recommended way to do it, but it works.
First, in the view, update
get_form_kwargs()
with the custom data. For example, in my case I wanted to use the extra data from the instance attached to the form.Next, in your form's
__init__()
, pop the kwarg and attach it to the custom widget on the field:Finally, in your custom widget class, grab the variable in the
__init__()
:Now the
{{ custom_data }}
template variable is available in the rendered HTML frommyapp/widgets/my_custom_widget.html
.