从Django Model Formset保存数据

时间:2017-08-18 20:44:56

标签: python django python-3.x formset

如何将数据从django模型formset保存到数据库?

models.py:

from django.db import models
from django.utils import timezone

class MyModel(models.Model):
    idno = models.CharField(max_length=20)
    date = models.DateTimeField(default=timezone.now)
    entity = models.CharField(max_length=50)
    logic = models.CharField(max_length=100)
    choices = (
        ('1', 'Choice1'),
        ('2', 'Choice2'),
        ('3','Choice3'),
    )
    choices = models.CharField(
        max_length=20,
        choices=choices,
        null=True,
        )
    comment = models.CharField(max_length=500, null=True)
    def __str__(self):
        return self.idno

forms.py:

from .models import MyModel
from django.forms import modelformset_factory, ModelForm

class MyForm(ModelForm):

    class Meta:
        model = MyModel
        fields = '__all__'

    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        self.fields['idno'].disabled = True
        self.fields['date'].disabled = True
        self.fields['entity'].disabled = True
        self.fields['logic'].disabled = True

MyFormSet = modelformset_factory(MyModel, extra=1, exclude=(), form=MyForm)

views.py:

from django.shortcuts import render
from django.http import HttpResponse
from .models import MyModel
from .forms import MyFormSet

def index(request):
new = MyModel.objects.filter(choices__isnull=True)
modelformset = MyFormSet(request.POST or None, queryset=new)
context = {'modelformset':modelformset}
if request.method == 'POST':
    if modelformset.is_valid():
        modelformset.save()
        idno = modelformset.cleaned_data['idno']
        entity = modelformset.cleaned_data['entity']
        messages.success(request, '%s for %s submitted' % (idno, entity))
    return HttpResponseRedirect('/')
return render(request, 'selfserve/index.html', context)

的index.html:

<form method="post" action="">
  {% csrf_token %}
  {{ modelformset.management_form }}
<table>
<tr>
  <th>idno</th>
  <th>date</th>
  <th>entity</th>
  <th>logic</th>
  <th>choices</th>
  <th>comment</th>
</tr>
{% for form in modelformset %}
<tr>
  <td>{{ form.idno }}</td>
  <td>{{ form.date }}</td>
  <td>{{ form.entity }}</td>
  <td>{{ form.logic }}</td>
  <td>{{ form.choices }}</td>
  <td>{{ form.comment }}</td>
  <td><input type="submit" value="Submit"></td>
</tr>
{% endfor %}
</table>
</form>

现在,它返回了模型formset中每个元素的一个很好的表,每个元素旁边都有一个提交按钮。当我填写启用的字段(choicescomment)时,我希望将formset中的表单保存到数据库中。现在,当我单击其中一个提交按钮时,会发生以下错误:

['ManagementForm data is missing or has been tampered with']

我知道这通常意味着管理表格没有包含在模板中。但是,我已经把那篇文章包括在内了。

我认为我的问题是在views.py和index.html的组合中,我只是不确定在哪里。理想情况下,我希望保存数据,并且用户保持在同一页面上,这样他们就不必在保存每个数据时来回走动。或者,它可能只需要一个保存按钮,在完成所有编辑后它们会单击它们。

0 个答案:

没有答案