Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - Remove add new record from form widget>

Tags:

python

django

I have created a form widget that is automatically adding a add new record section at the top of the form, which i do not want to be there. can someone tell me how to disable this? I just want to display the variables not the add form.

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 %}

page that is loaded: sample of issue

like image 490
AlexW Avatar asked Oct 30 '22 10:10

AlexW


1 Answers

If I understood your intentions in your template, you want to include your template or include the form. If that is the case:

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

Another possibility, is that you do not want to extra_context['include_form'] = VariableForm in your ConfigTemplateAdmin class and you can create a different view (or method in your current view) for adding new Variables with your form!

like image 135
John Moutafis Avatar answered Nov 15 '22 06:11

John Moutafis