Django从表单小部件移除添加新记录>

2024-10-05 17:24:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经创建了一个表单小部件,它自动在表单的顶部添加一个addnewrecord部分,我不想在那里。有人能告诉我如何禁用这个吗?我只想显示变量而不是add表单。在

在表单.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__" 

在管理员py在

^{pr2}$

改变_视图.html在

^{3}$

加载的页面: sample of issue


Tags: namepyself表单objectshtmltemplateforms
2条回答

如果我理解您在模板中的意图,您希望包括模板包括表单。如果是这样的话:

{% if include_template %}
    {% include include_template %}
{% elif include_form %}
    <form method="POST" class="post-form">
        {% csrf_token %}
        {{ include_form.as_p }}
    </form>
{% endif %}

另一种可能性是,您不想在您的ConfigTemplateAdmin类中使用extra_context['include_form'] = VariableForm,您可以创建一个不同的视图(或当前视图中的方法),以便在表单中添加新变量!在

设法弄清楚了。我添加了一个include data选项,并将其发送到模板中,如下所示:

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,
    )

然后在模板中

^{pr2}$

相关问题 更多 >