“选择一个有效的选择。”在Django中使用Modelform时出错

时间:2016-04-26 15:15:48

标签: python django forms model

我不明白为什么我一直收到这个错误:

“选择一个有效的选择。这个选择不是可用的选择之一。” 错误消息属于“帐户”字段

以下是我的模特:

class Account(models.Model):
    owner = models.ForeignKey(User, on_delete=models.CASCADE)
    balance = models.FloatField()
    name = models.CharField(max_length=50)

    def __str__(self):
        return self.name


class Entry(models.Model):
    account = models.ForeignKey("Account", on_delete=models.CASCADE)
    amount = models.FloatField()
    expense = models.BooleanField(default=True)
    date = models.DateTimeField()
    usage = models.CharField(max_length=200, blank=True)
    payment_method = models.ForeignKey("PaymentMethod",    on_delete=models.CASCADE)
    category = models.ForeignKey("Category", on_delete=models.CASCADE)

    def __str__(self):
        return "{} - {}".format(self.date, self.account)

我的观点:

class AddExpenseView(View):
    template_name = "finance/create_booking.html"
    form_class = CreateBookingForm

    @method_decorator(login_required)
    def get(self, request):
        context = {
            "title": "StatYourLife - Neue Ausgabe",
            "create_booking_form": self.form_class(user=request.user)
        }

        return render(request, self.template_name, context)
    @method_decorator(login_required)
    def post(self, request):
        form = self.form_class(request.POST)
        if form.is_valid():
            user_profile = UserProfile.objects.get(user_id=request.user)
            booking = form.save(commit=False)
            account = booking.account
            account.balance -= booking.amount
            booking.expense = True
            booking.date = timezone.now()
            user_profile.entrys += 1
            user_profile.save()
            account.save()
            booking.save()
            return HttpResponseRedirect(reverse("finance:index"))
        else:
            context = {
                "title": "test",
                "create_booking_form": form
            }
            return render(request, self.template_name, context)

和我的表格:

class CreateBookingForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user', None)
        super(CreateBookingForm, self).__init__(*args, **kwargs)
        self.fields["account"].queryset =     Account.objects.filter(owner=self.user)

    class Meta:
        model = Entry
        exclude = ["expense", "date"]

我工作正常,直到我尝试提交此表单并选择了帐户类型。

2 个答案:

答案 0 :(得分:3)

在您的帖子方法中,您忘记将user传递给表单。由于您将account字段的查询集设置为Account.objects.filter(owner=self.user),这意味着当您在验证数据时显示表单时,您具有不同的查询集。

将其更改为:

def post(self, request):
    form = self.form_class(request.POST, user=self.request.user)

将表单更改为:

可能更好
self.user = kwargs.pop('user')

如果user中缺少kwargs,则会出现明确的错误。

答案 1 :(得分:0)

在将account模型实例直接传递到account字段时测试模型时,我也遇到这种类型的错误。因为模型窗体将外键字段显示为选择选项。即。它将所有帐户对象作为值为account.id的选择选项列出,如果account_obj not in avilable choices(帐户ID列表([int]),则会引发错误。

CreateBookingForm(data={'account': Account.objects.first()})

但是在这里,我们必须传递帐户ID而不是整个帐户对象。

CreateBookingForm(data={'account': Account.objects.first().id})