尝试使用formset,获取__init __()得到一个意外的关键字参数'instance'

时间:2017-02-18 10:02:14

标签: python django

我需要使用formset,并成功实现了它以添加对象。

但现在我需要使用formset来编辑对象。我有以下内容:

models.py

class Cell(models.Model):
    content = models.CharField(max_length=100)
    row = models.ForeignKey('Row')

class Row(models.Model):
    pass

forms.py

class RowForm(forms.Form):
    cell = forms.CharField(label="Ячейка", max_length=100)

number_of_cells = 5
RowFormset = formset_factory(RowForm, extra=number_of_cells)

views.py

def edit_row(request, row_pk):
    try:
        row = Row.objects.get(pk=row_pk)
    except Row.DoesNotExist:
        return HttpResponse('Такая строка не существует')

    if request.method == 'POST':
        formset = RowFormset(request.POST, instance=row)
        if formset.is_valid():
            formset.save()
            return HttpResponseRedirect(reverse('table:index'))
    else:
        formset = RowFormset(instance=row)

    return render(request, 'table/edit-row.html', {'formset': formset})

目前我正在TypeError: __init__() got an unexpected keyword argument 'instance'。我怎样才能完成我的任务,考虑到使用模型形式可能不是一个选项,因为模型不知道我的单元格,或者我应该连续的单元格数量(因此我可能必须坚持普通形式。形式)。

谢谢。

2 个答案:

答案 0 :(得分:2)

您收到错误,因为forms.Form不应该将实例作为参数。 您需要使用Cell模型的formset。我建议这个:

<强> forms.py:

from django.forms import modelformset_factory
from .models import Cell

CellFormSet = modelformset_factory(Cell, fields=('content ',))

<强> views.py:

def edit_row(request, row_pk):
    try:
        row = Row.objects.get(pk=row_pk)
    except Row.DoesNotExist:
        return HttpResponse('Такая строка не существует')

    cells = Cell.objects.filter(row=row)

    if request.method == 'POST':
        formset = CellFormSet(request.POST, instance=cells)
        if formset.is_valid():
            formset.save()
            return HttpResponseRedirect(reverse('table:index'))
        else:
            return render(request, 'table/edit-row.html', {'formset': formset})
    else:
        formset = CellFormSet(instance=cells)
        return render(request, 'table/edit-row.html', {'formset': formset})

答案 1 :(得分:0)

以下代码完全符合我的要求:

def edit_row(request, row_pk):
    try:
        row = Row.objects.get(pk=row_pk)
    except Row.DoesNotExist:
        return HttpResponse('Такая строка не существует')

    cells = Cell.objects.filter(row=row)

    contents = []

    if request.method == 'POST':
        formset = RowFormSet(request.POST)
        if formset.is_valid():
            for form in formset:
                cd = form.cleaned_data
                content = cd.get('cell')
                contents.append(content)

            for i, cell in enumerate(cells):
                cell.content = contents[i]
                cell.save()
        return HttpResponseRedirect(reverse('table:index'))
    else:
        formset = RowFormSet()

    return render(request, 'table/edit-row.html', {'formset': formset})