簡體   English   中英

Django - CreateView 不使用嵌套表單集保存表單

[英]Django - CreateView not saving form with nested formset

我正在嘗試采用一種使用 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>

終端或其他方面沒有錯誤。 非常感謝幫助。

您當前沒有在CreateView正確處理CreateView 該視圖中的form_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()方法將表單集傳遞給此方法。

我在上面的示例代碼中留下了一些額外的注釋,希望能幫助您解決這個問題。

也許你想看看包django-extra-views ,它提供了視圖CreateWithInlinesView ,女巫允許你創建帶有嵌套內聯的表單,比如 Django-admin 內聯。

在你的情況下,它會是這樣的:

視圖.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'

.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 按鈕來添加/刪除。

你說有一個錯誤,但你沒有在你的問題中顯示它。 錯誤(和整個回溯)比你寫的任何東西都重要(除了可能來自 forms.py 和 views.py)

由於表單集和在同一個 CreateView 上使用多個表單,您的情況有點棘手。 互聯網上沒有很多(或沒有很多好的)例子。 直到您深入了解內聯表單集的工作方式 django 代碼,您才會遇到麻煩。

好的,切入正題。 您的問題是表單集未使用與主表單相同的實例進行初始化。 並且當您的 amin 表單將數據保存到數據庫時,表單集中的實例不會更改,並且最后您沒有主對象的 ID 以作為外鍵放置。 在 init 之后更改表單屬性的實例屬性不是一個好主意。

在正常形式中,如果您在 is_valid 之后更改它,您將獲得不可預測的結果。 對於表單集,即使在 init 之后直接更改實例屬性也無濟於事,因為表單集中的表單已經用某個實例進行了初始化,之后更改它也無濟於事。 好消息是你可以在Formset 初始化后更改實例的屬性,因為在formset 初始化后,所有表單的實例屬性都將指向同一個對象。

您有兩個選擇:

如果formset 不設置實例屬性,只設置instance.pk。 (這只是我從未做過的猜測,但我認為它應該可以工作。問題是它看起來像黑客)。 創建一個將一次初始化所有表單/表單集的表單。 當調用 is_valid() 方法時,應驗證所有表單。 當它的 save() 方法被調用時,所有的表單都必須被保存。 然后您需要將 CreateView 的 form_class 屬性設置為該表單類。 唯一棘手的部分是在您的主表單初始化后,您需要使用第一個表單的實例初始化其他表單(formsests)。 您還需要將表單/表單集設置為表單的屬性,以便在模板中訪問它們。 當我需要創建一個包含所有相關對象的對象時,我正在使用第二種方法。 這會將業務邏輯與視圖邏輯分開,因為從視圖的角度來看,您只有一個表單,它可以是:

用一些數據(在本例中為 POST 數據)初始化,用 is_valid() 檢查有效性,當它有效時可以用 save() 保存。 您保留了表單界面,如果您正確地制作了表單,您甚至可以將它不僅用於創建對象,還可以用於更新對象及其相關對象,並且視圖將非常簡單。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM