Failed lookup for key [form] in u' on crispy formset

3k views Asked by At

I keep getting Failed lookup for key [form] in u'(...) when I click submit button. I cant figure whats is happening or why. I dont know if is crispy, form or views problem. Maybe a tip is that i put extra=1 in formset but only shows 1 line.

form.py

class CotizacionForm(forms.ModelForm):
    class Meta:
        model = Cotizacion
        fields = ('fecha', 'local','estado_pago','estado_trabajo','detalle_monto', 'observacion',)
        widgets = {'fecha': forms.DateInput(attrs={'id': 'datetimepicker12'})}



    def __init__(self, *args, **kwargs):
        super(CotizacionForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_id = 'id-cotizacion-form'
        self.helper.form_method = 'post'
        self.helper.form_class = 'form-horizontal'
        self.helper.label_class = 'col-lg-3 text-left'
        self.helper.field_class = 'col-lg-9'
        self.helper.layout = Layout(
                Div(
                    Field('fecha',style="margin-bottom: -10px;"),
                    Field('local',style="margin-bottom: -10px;"),
                    Field('estado_trabajo', style="margin-bottom: -10px;"),
                    Field('estado_pago', style="margin-bottom: -10px;"),
                    Field('detalle_monto', style="margin-bottom: -10px;"),
                    css_class="col-lg-6"
                    ),
                Div(

                    Field('observacion',style="max-height: 100px;"),
                    css_class="col-lg-6"
                    ),
                )



class TrabajoForm(forms.ModelForm):
    class Meta:
        model = Trabajo

        fields = ('unidad','valor','actividad','cuadrilla')

    descripcion = forms.CharField(
            label = "Escriba el detalle del trabajo",
            max_length = 200,
            required = True,
            )

    def __init__(self, *args, **kwargs):
        super(TrabajoForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_id = 'id-trabajo-form'
        self.helper.form_method = 'post'
        # self.helper.form_action = reverse('submit_form')
        # self.helper.add_input(Submit('submit', '+', css_class='btn btn-rounded btn-sm btn-icon btn-default text-right'))
        self.helper.form_class = 'form-inline col-lg-12'
        self.helper.field_template = 'bootstrap3/layout/inline_field.html'
        self.helper.layout = Layout(
                Div(
                    InlineField('descripcion', 
                        style="width:650px"
                        ),
                    'unidad',
                    'valor',
                    'actividad',
                    'cuadrilla',
                    HTML("<a class=" + "delete-row" + " href=" + "javascript:void(0)" + "><i class=" + "'fa fa-trash-o fa-lg icon text-danger-dker'" + "></i>  </a>"),
                    style='margin-bottom:5px',
                    # css_class="col-lg-12"
                    ),
                ButtonHolder(
                Submit('submit', 'Submit', css_class='button white')
            )
                    )

views.py

@login_required
def cotizacion_new(request, cotizacion_id=None):
    TrabajoInlineFormSet = inlineformset_factory(Cotizacion, Trabajo, form=TrabajoForm, extra=1, can_delete=True)

    if cotizacion_id:
        cotizacion = Cotizacion.objects.get(pk=cotizacion_id)

    else:
        cotizacion = Cotizacion()

    if request.method == "POST":
        form = CotizacionForm(request.POST, instance=cotizacion)
        formset = TrabajoForm(request.POST, instance=cotizacion)
        if form.is_valid() and formset.is_valid():
            form.save()
            formset.save()
            return redirect('erp:cotizacion_detail', pk=cotizacion.pk)
    else:
        form = CotizacionForm(instance=cotizacion)
        formset = TrabajoInlineFormSet(instance=cotizacion)

    return render(request, 'erp/cotizacion_edit.html', {'form': form, 'formset': formset})

cotizacion_edit.html

                <div class="col-lg-12">
                    <div class="row">
                        {% crispy form %}
                    </div>
                    <hr>
                    <p>Detalle de los Trabajos:</p>
                    <div class="row link-formset">
                        {% crispy formset formset.form.helper %}
                    </div>
                </div>
                <form method='POST' action=''>
                {% csrf_token %}
                <div class="col-lg-12 ">
                    <br>
                    <input type="submit"  class="btn btn-sm btn-block btn-primary"></input> 
                    <br>
                </div>
                </form>
            </div>

urls.py

(...)
url(r'^cotizacion/new/$', views.cotizacion_new, name='cotizacion_new'),
    url(r'^cotizacion/edit/(?P<cotizacion_id>[0-9]+)/$', views.cotizacion_new, name='cotizacion_edit'),
    url(r'^cotizacion/(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='cotizacion_detail'),

Environment:

Request Method: POST Request URL: http://localhost:8000/erp/cotizacion/new/

Django Version: 1.11.4 Python Version: 2.7.10

Installed Applications:
['erp.apps.ErpConfig',
 'django.contrib.admin',
 'django.contrib.admindocs',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.humanize',
 'crispy_forms']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']

Template error:

Traceback:

File "/Applications/MAMP/htdocs/italuzbi/italuzvenv/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request)

File "/Applications/MAMP/htdocs/italuzbi/italuzvenv/lib/python2.7/site-packages/django/core/handlers/base.py" in _legacy_get_response 249. response = self._get_response(request)

File "/Applications/MAMP/htdocs/italuzbi/italuzvenv/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request)

File "/Applications/MAMP/htdocs/italuzbi/italuzvenv/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/Applications/MAMP/htdocs/italuzbi/italuzvenv/lib/python2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view 23. return view_func(request, *args, **kwargs)

File "/Applications/MAMP/htdocs/italuzbi/erp/views.py" in cotizacion_new 76. return render(request, 'erp/cotizacion_edit.html', {'form': form, 'formset': formset})

File "/Applications/MAMP/htdocs/italuzbi/italuzvenv/lib/python2.7/site-packages/django/shortcuts.py" in render 30. content = loader.render_to_string(template_name, context, request, using=using)

File "/Applications/MAMP/htdocs/italuzbi/italuzvenv/lib/python2.7/site-packages/django/template/loader.py" in render_to_string 68. return template.render(context, request)

File "/Applications/MAMP/htdocs/italuzbi/italuzvenv/lib/python2.7/site-packages/django/template/backends/django.py" in render 66. return self.template.render(context)

File "/Applications/MAMP/htdocs/italuzbi/italuzvenv/lib/python2.7/site-packages/django/template/base.py" in render 207. return self._render(context)

File "/Applications/MAMP/htdocs/italuzbi/italuzvenv/lib/python2.7/site-packages/django/template/base.py" in _render 199. return self.nodelist.render(context)

File "/Applications/MAMP/htdocs/italuzbi/italuzvenv/lib/python2.7/site-packages/django/template/base.py" in render 990. bit = node.render_annotated(context)

File "/Applications/MAMP/htdocs/italuzbi/italuzvenv/lib/python2.7/site-packages/django/template/base.py" in render_annotated 957. return self.render(context)

File "/Applications/MAMP/htdocs/italuzbi/italuzvenv/lib/python2.7/site-packages/django/template/loader_tags.py" in render 177. return compiled_parent._render(context)

File "/Applications/MAMP/htdocs/italuzbi/italuzvenv/lib/python2.7/site-packages/django/template/base.py" in _render 199. return self.nodelist.render(context)

File "/Applications/MAMP/htdocs/italuzbi/italuzvenv/lib/python2.7/site-packages/django/template/base.py" in render 990. bit = node.render_annotated(context)

File "/Applications/MAMP/htdocs/italuzbi/italuzvenv/lib/python2.7/site-packages/django/template/base.py" in render_annotated 957. return self.render(context)

File "/Applications/MAMP/htdocs/italuzbi/italuzvenv/lib/python2.7/site-packages/django/template/loader_tags.py" in render 72. result = block.nodelist.render(context)

File "/Applications/MAMP/htdocs/italuzbi/italuzvenv/lib/python2.7/site-packages/django/template/base.py" in render 990. bit = node.render_annotated(context)

File "/Applications/MAMP/htdocs/italuzbi/italuzvenv/lib/python2.7/site-packages/django/template/base.py" in render_annotated 957. return self.render(context)

File "/Applications/MAMP/htdocs/italuzbi/italuzvenv/lib/python2.7/site-packages/crispy_forms/templatetags/crispy_forms_tags.py" in render 215. c = self.get_render(context)

File "/Applications/MAMP/htdocs/italuzbi/italuzvenv/lib/python2.7/site-packages/crispy_forms/templatetags/crispy_forms_tags.py" in get_render 109. helper = helper.resolve(context)

File "/Applications/MAMP/htdocs/italuzbi/italuzvenv/lib/python2.7/site-packages/django/template/base.py" in resolve 849. value = self._resolve_lookup(context)

File "/Applications/MAMP/htdocs/italuzbi/italuzvenv/lib/python2.7/site-packages/django/template/base.py" in _resolve_lookup 903. (bit, current)) # missing attribute

2

There are 2 answers

0
jplattus On BEST ANSWER

If you want to handle 2 or more forms in the same template ant put the submit button outside the forms, you have to remove the form tag:

self.helper.form_tag = False

Documentation is in http://django-crispy-forms.readthedocs.io/en/d-0/tags.html

0
Daniel Roseman On

I think the issue is where you call {% crispy formset.form.helper %} - the formset doesn't have a form attribute. See the crispy docs about how to use that tag with formsets.