我已經爲子類化UpdateView
服務的表單定義了一個自定義字段和窗口小部件。所以,這樣的事情:如何將視圖中的上下文變量傳遞給Django模板中的自定義字段/小部件?
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)
基本上,我希望能夠從我的觀點通過custom_data
(例如來自會話存儲或者窗體實例)添加到窗口小部件。