我创建了一个表单窗口小部件,它自动在表单顶部添加一个添加新记录部分,我不想在那里。谁能告诉我如何禁用它?我只是想显示变量而不是添加形式。
forms.py
class TemplateVariablesWidget(forms.Widget):
template_name = 'sites/config_variables.html'
def render(self, name, value, attrs=None):
sc_vars = ConfigVariables.objects.filter(type='Showroom')
wc_vars = ConfigVariables.objects.filter(type='Major Site')
context = {
'SConfigVariables' : sc_vars,
'WConfigVariables' : wc_vars,
}
return mark_safe(render_to_string(self.template_name, context))
class VariableForm(forms.ModelForm):
variables = forms.CharField(widget=TemplateVariablesWidget, required=False)
class Meta:
model = ConfigVariables
fields = "__all__"
admin.py
class ConfigTemplateAdmin(admin.ModelAdmin):
list_display = ('device_name', 'date_modified')
def change_view(self, request, object_id, form_url='', extra_context=None):
extra_context = extra_context or {}
#extra_context['include_template'] = '/path/to/template.html'
extra_context['include_form'] = VariableForm
return super(ConfigTemplateAdmin, self).change_view(
request, object_id, form_url, extra_context=extra_context,
)
change_view.html
{% block extra_content %}
{% if include_template %}
{% include include_template %}
{% endif %}
{% if include_form %}
<form method="POST" class="post-form">
{% csrf_token %}
{{ include_form.as_p }}
</form>
{% endif %}
{% endblock %}
答案 0 :(得分:2)
如果我在您的模板中了解您的意图,您希望包含模板或包含该表单。如果是这样的话:
{% if include_template %}
{% include include_template %}
{% elif include_form %}
<form method="POST" class="post-form">
{% csrf_token %}
{{ include_form.as_p }}
</form>
{% endif %}
另一种可能性是,您不希望在extra_context['include_form'] = VariableForm
课程中ConfigTemplateAdmin
,并且可以在表格中添加新的变量来创建不同的视图(或当前视图中的方法)! / p>
答案 1 :(得分:0)
管理好了解决这个问题。我添加了一个包含数据选项,并按照以下内容将其发送到模板:
def change_view(self, request, object_id, form_url='', extra_context=None):
from sites.models import ConfigVariables
config_variables = ConfigVariables.objects.all()
extra_context = extra_context or {}
extra_context['include_data'] = config_variables
extra_context['include_template'] = 'admin/config_variables.html'
#extra_context['include_form'] = VariableForm
return super(ConfigTemplateAdmin, self).change_view(
request, object_id, form_url, extra_context=extra_context,
)
然后在模板中
{% for d in include_data %}