Django:ModelFormSet仅保存第一个条目

时间:2016-02-05 21:37:59

标签: django django-forms formset

更新

问题似乎在于Django-formset的编码。我正在处理它作为内联formset而不是模型formset。下面的答案也是正确的。谢谢!

我正在使用中间模型的模型formset。我正在使用django-formset js在模板上添加其他formset字段。大多数一切正常,但是当我去保存formset时,只有第一个条目被保存到DB。第一个条目已保存并正确分配,但不会消失。它没有抛出任何错误,所以我不确定会出现什么问题。谢谢!

模特

class StaffAssignment(models.Model):
    study = models.ForeignKey(Study, related_name='study_set', null=True, on_delete=models.CASCADE)
    staff = models.ForeignKey('account.UserProfile', related_name='assigned_to_set', null=True, on_delete=models.CASCADE)
    role = models.CharField(max_length=100, null=True)
    assigned_on = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ('-role',)

    def __str__(self):
        return '{} is assigned to {}'.format(self.staff, self.study)

表格:

class AddStaff(forms.ModelForm):
    model = StaffAssignment
    fields = ('staff',)

    def __init__(self, *args, **kwargs):
        super(AddStaff, self).__init__(*args, **kwargs)
        for field in self.fields:
            self.fields[field].widget.attrs.update({'class': 'form-control'})

观点:

def add_staff(request, study_slug):
    study = get_object_or_404(Study, slug=study_slug)
    staff_formset = modelformset_factory(StaffAssignment, form=AddStaff, fields=('staff',), can_delete=True)
    if request.method == 'POST':
        staffList = staff_formset(request.POST, request.FILES)
        if staffList.is_valid():
            for assignment in staffList:
                assigned = assignment.save(commit=False)
                assigned.study = study
                assigned.role = assigned.staff.job_title
                assigned.save()
            return HttpResponseRedirect(reverse('studies:studydashboard'))
        else:
            HttpResponse('Something is messed up')
    else:
        staffList = staff_formset(queryset=StaffAssignment.objects.none())
        return render(request, 'studies/addstaff.html', {'staffList': staffList, 'study': study})

模板:

    <form action="{% url 'studies:addstaff' study.slug %}" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    <div class="box-body">
            {% for list in staffList %}
                <div class="form-group" id="formset">
                {% if list.instance.pk %}{{ list.DELETE }}{% endif %}
                    {{ list.staff }}
                    {% if list.staff.errors %}
                        {% for error in list.staff.errors %}
                            {{ error|escape }}
                        {% endfor %}
                    {% endif %}
                </div>
            {% endfor %}
            {{ staffList.management_form }}
    </div>
    <div class="box-footer">
        <button type="submit" class="btn btn-primary">Submit</button>
    </div>
    </form>

1 个答案:

答案 0 :(得分:0)

您未在模板中包含主键字段required by the docs。添加

{% for list in staffList %}
    {{ list.pk }}
    ...
{% endfor %}