在u'中查找密钥[表单]失败在crispy formset上

时间:2017-09-05 16:02:43

标签: python django formset inline-formset

当我点击提交按钮时,我一直在使用['(...)中的密钥[表单]查找失败。我不知道发生了什么或为什么。我不知道是否有酥脆,形式或观点问题。也许一个提示是我在formset中加上extra = 1但只显示1行。

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

环境:

请求方法:POST 请求网址:http://localhost:8000/erp/cotizacion/new/

Django版本:1.11.4 Python版本: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']

模板错误:

回溯:

File&#34; /Applications/MAMP/htdocs/italuzbi/italuzvenv/lib/python2.7/site-packages/django/core/handlers/exception.py"在内心   41. response = get_response(request)

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

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

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

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

File&#34; /Applications/MAMP/htdocs/italuzbi/erp/views.py"在cotizacion_new   76. return render(request,&#39; erp / cotizacion_edit.html&#39;,{&#39; form&#39 ;: form,&#39; formset&#39;:formset})

File&#34; /Applications/MAMP/htdocs/italuzbi/italuzvenv/lib/python2.7/site-packages/django/shortcuts.py"在渲染中   30. content = loader.render_to_string(template_name,context,request,using = using)

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

File&#34; /Applications/MAMP/htdocs/italuzbi/italuzvenv/lib/python2.7/site-packages/django/template/backends/django.py"在渲染中   66. return self.template.render(context)

File&#34; /Applications/MAMP/htdocs/italuzbi/italuzvenv/lib/python2.7/site-packages/django/template/base.py"在渲染中   207. return self._render(context)

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

File&#34; /Applications/MAMP/htdocs/italuzbi/italuzvenv/lib/python2.7/site-packages/django/template/base.py"在渲染中   990. bit = node.render_annotated(context)

File&#34; /Applications/MAMP/htdocs/italuzbi/italuzvenv/lib/python2.7/site-packages/django/template/base.py"在render_annotated中   957. return self.render(context)

File&#34; /Applications/MAMP/htdocs/italuzbi/italuzvenv/lib/python2.7/site-packages/django/template/loader_tags.py"在渲染中   177. return compiled_pa​​rent._render(context)

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

File&#34; /Applications/MAMP/htdocs/italuzbi/italuzvenv/lib/python2.7/site-packages/django/template/base.py"在渲染中   990. bit = node.render_annotated(context)

File&#34; /Applications/MAMP/htdocs/italuzbi/italuzvenv/lib/python2.7/site-packages/django/template/base.py"在render_annotated中   957. return self.render(context)

File&#34; /Applications/MAMP/htdocs/italuzbi/italuzvenv/lib/python2.7/site-packages/django/template/loader_tags.py"在渲染中   72. result = block.nodelist.render(context)

File&#34; /Applications/MAMP/htdocs/italuzbi/italuzvenv/lib/python2.7/site-packages/django/template/base.py"在渲染中   990. bit = node.render_annotated(context)

File&#34; /Applications/MAMP/htdocs/italuzbi/italuzvenv/lib/python2.7/site-packages/django/template/base.py"在render_annotated中   957. return self.render(context)

文件&#34; /Applications/MAMP/htdocs/italuzbi/italuzvenv/lib/python2.7/site-packages/crispy_forms/templatetags/crispy_forms_tags.py"在渲染中   215. c = self.get_render(context)

文件&#34; /Applications/MAMP/htdocs/italuzbi/italuzvenv/lib/python2.7/site-packages/crispy_forms/templatetags/crispy_forms_tags.py"在get_render中   109. helper = helper.resolve(context)

File&#34; /Applications/MAMP/htdocs/italuzbi/italuzvenv/lib/python2.7/site-packages/django/template/base.py"在决心   849. value = self._resolve_lookup(context)

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

2 个答案:

答案 0 :(得分:0)

我认为问题出在您致电{% crispy formset.form.helper %}的地方 - 表单集没有form属性。有关如何将该标记用于表单集,请参阅the crispy docs

答案 1 :(得分:0)

如果您想在同一模板中处理2个或更多表单,请将提交按钮放在表单之外,您必须删除表单标记:

self.helper.form_tag = False

文档位于http://django-crispy-forms.readthedocs.io/en/d-0/tags.html