Django-CreateView不保存带有嵌套表单集的表单


14

我正在尝试采用一种使用Django-Crispy-Forms布局功能将嵌套表单集与主表单保存在一起的方法,但是我无法保存它。我正在跟踪代码示例项目,但无法验证表单集以保存数据。如果有人能指出我的错误,我将非常感激。我还需要在同一视图中为EmployeeForm添加三个内联。我尝试了Django-Extra-Views,但无法正常工作。如果您建议为同一视图(如5左右)添加多个内联,将不胜感激。我想实现的唯一目的是创建一个页面Employee及其内联Education, Experience, Others。下面是代码:

楷模:

class Employee(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='employees',
                                null=True, blank=True)
    about = models.TextField()
    street = models.CharField(max_length=200)
    city = models.CharField(max_length=200)
    country = models.CharField(max_length=200)
    cell_phone = models.PositiveIntegerField()
    landline = models.PositiveIntegerField()

    def __str__(self):
        return '{} {}'.format(self.id, self.user)

    def get_absolute_url(self):
        return reverse('bars:create', kwargs={'pk':self.pk})

class Education(models.Model):
    employee = models.ForeignKey('Employee', on_delete=models.CASCADE, related_name='education')
    course_title = models.CharField(max_length=100, null=True, blank=True)
    institute_name = models.CharField(max_length=200, null=True, blank=True)
    start_year = models.DateTimeField(null=True, blank=True)
    end_year = models.DateTimeField(null=True, blank=True)

    def __str__(self):
        return '{} {}'.format(self.employee, self.course_title)

视图:

class EmployeeCreateView(CreateView):
    model = Employee
    template_name = 'bars/crt.html'
    form_class = EmployeeForm
    success_url = None

    def get_context_data(self, **kwargs):
        data = super(EmployeeCreateView, self).get_context_data(**kwargs)
        if self.request.POST:
            data['education'] = EducationFormset(self.request.POST)
        else:
            data['education'] = EducationFormset()
        print('This is context data {}'.format(data))
        return data


    def form_valid(self, form):
        context = self.get_context_data()
        education = context['education']
        print('This is Education {}'.format(education))
        with transaction.atomic():
            form.instance.employee.user = self.request.user
            self.object = form.save()
            if education.is_valid():
                education.save(commit=False)
                education.instance = self.object
                education.save()

        return super(EmployeeCreateView, self).form_valid(form)

    def get_success_url(self):
        return reverse_lazy('bars:detail', kwargs={'pk':self.object.pk})

形式:

class EducationForm(forms.ModelForm):
    class Meta:
        model = Education
        exclude = ()
EducationFormset =inlineformset_factory(
    Employee, Education, form=EducationForm,
    fields=['course_title', 'institute_name'], extra=1,can_delete=True
    )

class EmployeeForm(forms.ModelForm):

    class Meta:
        model = Employee
        exclude = ('user', 'role')

    def __init__(self, *args, **kwargs):
        super(EmployeeForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_tag = True
        self.helper.form_class = 'form-horizontal'
        self.helper.label_class = 'col-md-3 create-label'
        self.helper.field_class = 'col-md-9'
        self.helper.layout = Layout(
            Div(
                Field('about'),
                Field('street'),
                Field('city'),
                Field('cell_phone'),
                Field('landline'),
                Fieldset('Add Education',
                    Formset('education')),
                HTML("<br>"),
                ButtonHolder(Submit('submit', 'save')),
                )
            )

根据示例的自定义布局对象:

from crispy_forms.layout import LayoutObject, TEMPLATE_PACK
from django.shortcuts import render
from django.template.loader import render_to_string

class Formset(LayoutObject):
    template = "bars/formset.html"

    def __init__(self, formset_name_in_context, template=None):
        self.formset_name_in_context = formset_name_in_context
        self.fields = []
        if template:
            self.template = template

    def render(self, form, form_style, context, template_pack=TEMPLATE_PACK):
        formset = context[self.formset_name_in_context]
        return render_to_string(self.template, {'formset': formset})

Formset.html:

{% load static %}
{% load crispy_forms_tags %}
{% load staticfiles %}

<table>
{{ formset.management_form|crispy }}

    {% for form in formset.forms %}
            <tr class="{% cycle 'row1' 'row2' %} formset_row-{{ formset.prefix }}">
                {% for field in form.visible_fields %}
                <td>
                    {# Include the hidden fields in the form #}
                    {% if forloop.first %}
                        {% for hidden in form.hidden_fields %}
                            {{ hidden }}
                        {% endfor %}
                    {% endif %}
                    {{ field.errors.as_ul }}
                    {{ field|as_crispy_field }}
                </td>
                {% endfor %}
            </tr>
    {% endfor %}

</table>
<br>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script src="{% static 'js/jquery.formset.js' %}">
</script>
<script type="text/javascript">
    $('.formset_row-{{ formset.prefix }}').formset({
        addText: 'add another',
        deleteText: 'remove',
        prefix: '{{ formset.prefix }}',
    });
</script>

终端或其他方面没有错误。非常感谢您的帮助。


另一种解决方案是让表单也处理表单集:我使用schinckel.net/2019/05/23/form-and-formset中的相关表单集使用cached_property
Matthew Schinckel

Answers:


0

您目前无法在中正确处理表单集CreateViewform_valid在该视图中将仅处理父表单,而不处理表单集。您应该做的是重写该post方法,然后您需要验证表单和附加到它的所有表单集:

def post(self, request, *args, **kwargs):
    form = self.get_form()
    # Add as many formsets here as you want
    education_formset = EducationFormset(request.POST)
    # Now validate both the form and any formsets
    if form.is_valid() and education_formset.is_valid():
        # Note - we are passing the education_formset to form_valid. If you had more formsets
        # you would pass these as well.
        return self.form_valid(form, education_formset)
    else:
        return self.form_invalid(form)

然后form_valid像这样修改:

def form_valid(self, form, education_formset):
    with transaction.atomic():
        form.instance.employee.user = self.request.user
        self.object = form.save()
        # Now we process the education formset
        educations = education_formset.save(commit=False)
        for education in educations:
            education.instance = self.object
            education.save()
        # If you had more formsets, you would accept additional arguments and
        # process them as with the one above.
    # Don't call the super() method here - you will end up saving the form twice. Instead handle the redirect yourself.
    return HttpResponseRedirect(self.get_success_url())

您当前使用的get_context_data()方式不正确-完全删除该方法。它仅应用于获取上下文数据以渲染模板。您不应该从您的form_valid()方法中调用它。相反,您需要将表单集从上述post()方法传递给此方法。

我在上面的示例代码中留下了一些其他注释,希望可以帮助您解决这一问题。


在回答之前,请在本地重新创建示例。我已经试过了,但是没有用。
Shazia Nusrat

1
@ShaziaNusrat对不起,我没有时间去尝试找出对您不起作用的东西,特别是如果您不说自己已经尝试了什么而又不起作用的话(“这不起作用”不是对无效的充分说明)。我相信我的回答中有足够的帮助您确定当前实施中需要更改的内容。如果没有,那么我们希望其他人能够为您提供更全面的答案。
solarissmoke

我在用于测试的代码中尝试过,但遇到了问题。这就是为什么我谦虚地请您在本地尝试,以便更好地指导我。感谢您花了一些时间来帮助我。但是没有用。
Shazia Nusrat

0

也许您希望看到package django-extra-views,提供的view CreateWithInlinesView,witch允许您使用嵌套内联(如Django-admin内联)创建表单。

在您的情况下,将是这样的:

views.py

class EducationInline(InlineFormSetFactory):
    model = Education
    fields = ['course_title', 'institute_name']


class EmployeeCreateView(CreateWithInlinesView):
    model = Employee
    inlines = [EducationInline,]
    fields = ['about', 'street', 'city', 'cell_phone', 'landline']
    template_name = 'bars/crt.html'

crt.html

<form method="post">
  ...
  {{ form }}
  <table>
  {% for formset in inlines %}
    {{ formset.management_form }}
      {% for inline_form in formset %}
        <tr class="{% cycle 'row1' 'row2' %} formset_row-{{ formset.prefix }}">
          {{ inline_form }}
        </tr>
      {% endfor %}
  {% endfor %}
  </table>
  ...
  <input type="submit" value="Submit" />
</form>

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script src="{% static 'js/jquery.formset.js' %}">
</script>
<script type="text/javascript">
    {% for formset in inlines %}
      $('.formset_row-{{ formset.prefix }}').formset({
          addText: 'add another',
          deleteText: 'remove',
          prefix: '{{ formset.prefix }}',
      });
    {% endfor %}
</script>

该视图EmployeeCreateView将像Django-admin中一样为您处理表单。至此,您可以将所需的样式应用于表单。

我建议您访问文档以获取更多信息

编辑:我添加了management_form 和js按钮来添加/删除。


我已经尝试过了,但是不允许我为多个内联添加/删除按钮。它仅支持一个带有JS按钮的内联。我已经尝试过了。
Shazia Nusrat

1
它支持它,您必须management_form为每个添加formset
John

0

您说存在错误,但未在问题中显示它。错误(以及整个回溯)比您编写的任何内容都重要(可能来自forms.py和views.py)

您的案例有些棘手,因为这些表单集并在同一CreateView上使用了多个表单。互联网上没有很多(或很多好)示例。除非您在Django代码中挖掘内联表单集的工作方式,否则您将遇到麻烦。

好的,直截了当。您的问题是,表单集没有使用与主表单相同的实例进行初始化。而且,当您的amin表单将数据保存到数据库时,表单集中的实例不会更改,最后,您没有主对象的ID即可作为外键放置。在初始化之后更改表单属性的实例属性不是一个好主意。

在正常形式下,如果在is_valid之后更改它,将会得到无法预料的结果。对于表单集,即使直接在init之后直接更改实例属性也不会显示,因为表单集中的表单已经使用某个实例进行了初始化,而在之后进行更改将无济于事。好消息是,您可以在Formset初始化之后更改实例的属性,因为在Formset初始化之后,所有窗体的实例属性都将指向同一对象。

您有两种选择:

如果不设置表单集,则不设置实例属性,而仅设置instance.pk。(这只是猜测,我从未做过,但我认为它应该起作用。问题在于它看起来像hack)。创建一个将立即初始化所有表单/表单集的表单。调用is_valid()方法时,应验证所有格式。调用save()方法时,必须保存所有表单。然后,您需要将CreateView的form_class属性设置为该表单类。唯一棘手的部分是,在初始化主窗体后,您需要使用第一个窗体的实例来初始化其他窗体(窗体)。另外,您需要将表单/表单集设置为表单的属性,以便在模板中对其进行访问。当我需要创建一个包含所有相关对象的对象时,我正在使用第二种方法。

使用is_valid()检查有效性的一些数据(在这种情况下为POST数据)初始化的数据在有效时可以通过save()保存。您可以保留表单界面,并且如果正确地创建了表单,您甚至可以将其不仅用于创建对象,还可以用于更新对象及其相关对象,视图将非常简单。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.