Django - ManyToManyField不让我保存,"这个字段是必需的"即使我选择了一些东西

时间:2017-02-16 12:35:20

标签: django

我有一个像这样的formset:

class TransactionForm(ModelForm):
    def __init__(self, *args, **kwargs):
        try:
            user = kwargs.pop("user")
        except KeyError:
            user = None
        super(TransactionForm, self).__init__(*args, **kwargs)
        self.fields["date"].widget.attrs["class"] = "datepicker"

        if user is not None:
            self.fields["categories"].queryset = Category.objects.get_all(user)
            self.fields["account"].queryset = Account.objects.for_user(user)

    class Meta:
        model = Transaction
        exclude = [""]
TransactionFormSet = modelformset_factory(Transaction, form=TransactionForm, exclude=("",))

查看:

def transaction_create_view(request, account_id=None):
    if request.method == "POST":
        formset = TransactionFormSet(request.POST)
        print(formset.errors)
        if formset.is_valid():
            for form in formset:
                if form.is_valid and form.has_changed():
                    form.save()

    if account_id is not None:
        transactions = TransactionFormSet(queryset=Transaction.objects.for_account(account_id, request.user))
    else:
        transactions = TransactionFormSet(queryset=Transaction.objects.for_user(request.user))

    transactions.form = curry(TransactionForm, user=request.user)
    transactions.forms.insert(0, transactions.forms[-1])
    del transactions.forms[-1]    
    context = {"transactions":transactions,}
    return render(request, "transactions/transactions.html", context)  

型号:

class Transaction(models.Model):
    account = models.ForeignKey(Account)
    date = models.DateField()
    payee = models.CharField(max_length = 100)
    categories = models.ManyToManyField(Category)
    comment = models.CharField(max_length = 1000)
    outflow = models.DecimalField(max_digits=10, decimal_places=3)
    inflow = models.DecimalField(max_digits=10, decimal_places=3)
    cleared = models.BooleanField()

class Category(models.Model):
    title = models.CharField(max_length = 100)
    subcategory = models.ForeignKey("self", blank=True, null=True)
    user = models.ForeignKey(User)
    budget = models.DecimalField(max_digits=10, decimal_places=2)

模板:

<form action="{% url 'transaction_create' %}" method="post">
    {% csrf_token %}
    {{ transactions.management_form }}

    {% for form in transactions %}
        {{ form.as_p }}
        <input type="submit" value="Save transaction" />
        <hr>
    {% endfor %}
</form> 

我以它生成的空表格输入信息,然后点击保存按钮,但是表单集无效,我在打印错误时得到了这个:

[{'categories': ['This field is required.']}, {}]

模板中的类别由<select>表示,我在其中选择一个类别(背景为彩色)。显然它没有设置,因此我无法保存,为什么会这样?我该如何解决?

编辑:

我不知道为什么,但现在它有效。

我重新设置数据库重新创建了一些数据以查看是否修复了这些内容,而且确实如此,我没有更改代码中的任何内容。

1 个答案:

答案 0 :(得分:0)

如果覆盖TransactionForm中的save(),则必须调用save_m2m()来保存m2m对象。

https://docs.djangoproject.com/en/1.10/topics/forms/modelforms/