本文介绍了当提供初始值时,Django formset数据不会被保存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表单,其中提供了一些初始数据 - 它是从其他模型克隆的数据,其中包含2个字段'group'和'requested'。



提供的数据是formset中的表单不被保存,只有当我将一些数据修改表单时,才会得到保存。



当没有初始数据提供的表单得到保存。



为什么向表单中添加内部数据使得无法将表单数据保存到数据库?



这是我在get_context_data字典中存在的formset:

  initial = ProcedureActionGroup.objects.filter(procedure__id = self.kwargs .get('pk',None)
initial_values = initial.values('group','requested')
print initial_values
initial_count = initial.count()

ActionGroupFormset = inlineformset_factory(self.model,TaskGroup,extra = initial_count,
form = TaskActionGroupForm,
can_delete = False,

data ['formset'] = ActionGroupFormset(self.request.POST或None,initial = initial_values,
** self。 get_formset_kwargs())

这是我保存所有数据的form_valid方法

  def form_valid(self,form):
context = self.get_context_data()
forms = []
表单。 append(form.is_valid())
如果self.get_procedure_obj():
formset = context ['formset']
forms.append(formset.is_valid())

如果所有(表单):
self.object = form.save(commit = False)
form.save()
如果self.get_procedure_obj():
formset = formset.save(commit = False)
for form中的obj:
obj .task = self.object
obj.save()

self.object.extract_users()

返回HttpResponseRedirect(self.object.get_absolute_url())

型号:

  class TaskGroup(models.Model):
task = models.ForeignKey(Task,null = True,blank = False)
group = models.ForeignKey(ActionGroup,null = True,blank = True)
requested = models.PositiveIntegerField(u'Requested',null = True,blank = True)

表单模板:

 < form method =postaction =class =span6 offset2 form form - 横> 
{%crispy form%}
{{formset.management_form}}
{%if formset%}
< div>
< fieldset>
< table class =table table-striped>
{form for formset%}
< tr>
{%表单中的字段%}
< td> {{field}}< / td>
{%endfor%}
< / tr>
{%endfor%}
< / table>
< / fieldset>
< / div>
{%endif%}
< div class =form-actions>
< button class =btn btn-primary btn-largetype =submit>
保存
< / button>
< / div>
< / form>


解决方案

我有一个类似的问题,使用django额外的视图。



我解决了这个bay修改传递给inlineformset_factory的表单类。 ModelForm.has_changed方法返回false。

  class TaskActionGroupForm(ModelForm):

model = YourModel

def has_changed(self):

覆盖这一点,因为传递给表单的初始数据不会被注意到,所以
不会被保存,除非实际上更改

changed_data = super(ModelForm,self).has_changed()
返回bool(self.initial或changed_data)


I have a formset which has some initial data provided - it's a data cloned from other model which contains 2 fields 'group' and 'requested'.

When initial data is provided the forms in formset do not get saved, they only get saved when I'll modify the form with the data a little bit.

When no initial data is provided forms do get saved.

Why adding intial data to a formset makes it impossible to save formsets data to the database?

This is my formset existing in get_context_data dictionary:

        initial = ProcedureActionGroup.objects.filter(procedure__id=self.kwargs.get('pk', None))
        initial_values = initial.values('group', 'requested')
        print initial_values
        initial_count = initial.count()

        ActionGroupFormset = inlineformset_factory(self.model, TaskGroup, extra=initial_count,
                                                   form=TaskActionGroupForm,
                                                   can_delete=False,
                                                   )
        data['formset'] = ActionGroupFormset(self.request.POST or None, initial=initial_values,
                                             **self.get_formset_kwargs())

This is my form_valid method where I save all data

def form_valid(self, form):
    context = self.get_context_data()
    forms = []
    forms.append(form.is_valid())
    if self.get_procedure_obj():
        formset = context['formset']
        forms.append(formset.is_valid())

    if all(forms):
        self.object = form.save(commit=False)
        form.save()
        if self.get_procedure_obj():
            formset = formset.save(commit=False)
            for obj in formset:
                obj.task = self.object
                obj.save()

        self.object.extract_users()

        return HttpResponseRedirect(self.object.get_absolute_url())

Model:

class TaskGroup(models.Model):
    task = models.ForeignKey(Task, null=True, blank=False)
    group = models.ForeignKey(ActionGroup, null=True, blank=True)
    requested = models.PositiveIntegerField(u'Requested', null=True, blank=True)

form template:

<form method="post" action="" class="span6 offset2 form form-horizontal">
    {% crispy form%}
    {{formset.management_form}}
    {% if formset %}
    <div>
        <fieldset>
            <table class="table table-striped">
                {% for form in formset%}
                <tr>
                    {% for field in form %}
                     <td> {{field}} </td>
                    {% endfor %}
                </tr>
                {% endfor %}
            </table>
        </fieldset>
    </div>
    {% endif %}
    <div class="form-actions">
        <button class="btn btn-primary btn-large" type="submit">
            Save
        </button>
    </div>
</form>
解决方案

I had a similar issue using django extra views.

I solved it bay modifying the form class that is passed to the inlineformset_factory. the ModelForm.has_changed method was returning false.

class TaskActionGroupForm(ModelForm):

    model = YourModel

    def has_changed(self):
        """
        Overriding this, as the initial data passed to the form does not get noticed, 
        and so does not get saved, unless it actually changes
        """
        changed_data = super(ModelForm, self).has_changed()
        return bool(self.initial or changed_data)

这篇关于当提供初始值时,Django formset数据不会被保存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 13:35