MultipleChoiceField 与 SelectMultiple 小部件“值 [...] 不是有效的选择。”

发布于 2024-10-03 00:34:09 字数 1304 浏览 3 评论 0原文

我在模型中定义了一个字段 -

    languages = models.CharField(max_length = 30, choices=LANGUAGE_CHOICES, blank = True, null = True)

选择很简单 -

LANGUAGE_CHOICES = (
    ('English', 'English'),
)

我在此模型上定义一个 ModelForm 并覆盖该字段 -

languages = forms.MultipleChoiceField(choices=LANGUAGE_CHOICES, widget=forms.SelectMultiple)

当我填写表单时,选择“英语”,然后尝试提交,我收到错误 -

languages< br> 值 u"[u'English']" 不是有效的选择

我做错了什么基本的事情吗?或者将 MultipleChoiceField 与 SelectMultiple 小部件结合起来不是可行的方法吗?

另外,是否有任何原因为什么选择元组不能两次具有相同的值,就像我现在拥有的那样(“英语”,“英语”)?

这里有一些额外的代码可能有助于深入了解

模板代码:

<div class="abovepad">
<label for="id_languages">Languages:</label>
    {{form.languages}}
</div>

POST 数据的语言部分:

u'languages': [u'English'],

ModelForm 代码的相关片段:

class ProfileForm(forms.ModelForm):        
languages = forms.MultipleChoiceField(choices=LANGUAGE_CHOICES)
class Meta:
    model = Student

如您所见,我几乎没有自定义任何内容。过去,当我遇到这个问题时,我会转而将列表中的项目制作为模型,然后使用 ManyToMany 字段,这不会导致相同的问题。对于这些情况,让物品成为模型是有意义的。在这种情况下则不然。我只是想知道我是否做错了什么或者这个组合是否不应该起作用。如果没有真正的答案,那么我的另一个选择是尝试挖掘 Django 表单代码,看看它为什么这样做。

I have a field defined in my model-

    languages = models.CharField(max_length = 30, choices=LANGUAGE_CHOICES, blank = True, null = True)

The choices are simple-

LANGUAGE_CHOICES = (
    ('English', 'English'),
)

I define a ModelForm on this model and override the field-

languages = forms.MultipleChoiceField(choices=LANGUAGE_CHOICES, widget=forms.SelectMultiple)

When I fill out the form, select "English", and try to submit, I get an error-

languages
Value u"[u'English']" is not a valid choice

Is there something basic that I am doing wrong? Or is the MultipleChoiceField combined with the SelectMultiple widget not the way to go?

Also, is there any reason why the choices tuple can't have the same value twice, like I have it now ('English', 'English')?

Here is some additional code that might be useful in getting to the bottom of this

Template Code:

<div class="abovepad">
<label for="id_languages">Languages:</label>
    {{form.languages}}
</div>

The portion of POST data with the languages:

u'languages': [u'English'],

Relevant snippet of ModelForm code:

class ProfileForm(forms.ModelForm):        
languages = forms.MultipleChoiceField(choices=LANGUAGE_CHOICES)
class Meta:
    model = Student

As you see, I barely customized anything. In the past when I ran into this issue I would switch to making the items in the list to models and then using ManyToMany fields which did not cause the same issue. For those instances, having the items be models made sense; in this case it doesn't. I just want to know whether I'm doing something wrong or whether this combo is not supposed to work. If there's no real answer then my other option would be to try and dig through the Django form code to see why its doing what its doing.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

狼亦尘 2024-10-10 00:34:09

您必须从您的模型定义中删除choices=LANGUAGE_CHOICES
您的表单返回的是所选值的列表,该列表在您的 models.LANGUAGE_CHOICES 中不存在

You must remove choices=LANGUAGE_CHOICES from your model definition:
what your form return is the list of selected value, that doesn't exist in your models.LANGUAGE_CHOICES

冷夜 2024-10-10 00:34:09

我知道这个问题已经一年多了,但我认为尝试回答可能仍然有帮助。

我相信这里可能存在一些问题,但当前的主要问题是 ModelForm 期望数据库记录的键而不是字符串值。

如果您正在制作与数据库无关的表单,我建议您制作表单而不是 ModelForm。但是,如果您确实想与数据库交互,请使用 ModelForm 并在 Student 模型中定义一个外键来与语言表关联,让 ModelForm 为您完成这项工作。

基于我对您的模型的假设的示例应用程序。

your_project/example_app/models.py:

from django.db import models

class Student(models.Model):
    name = models.CharField(max_length=255)
    language = models.ForeignKey('Language')

class Language(models.Model):
    name = models.CharField(max_length=255)

your_project/example_app/forms.py:

from django.forms import ModelForm
from example.models import Student

class StudentForm(ModelForm):
    class Meta:
        model = Student

相关文档:https://docs.djangoproject.com/en/dev/topics/forms/ modelforms/#modelform

片段:

正如您所料,ForeignKey 和 ManyToManyField 模型字段类型是特殊情况:

ForeignKey 由 django.forms.ModelChoiceField 表示,它是一个 ChoiceField,其选择是一个模型 QuerySet。
ManyToManyField 由 django.forms.ModelMultipleChoiceField 表示,它是一个 MultipleChoiceField,其选择是一个模型 QuerySet。

I know this over a year old now but thought it may still be helpful to attempt an answer.

I believe there may be a couple of issues here, but the main issue at hand is that the ModelForm is expecting a key to the database record not a string value.

I would suggest making a Form instead of ModelForm, if you are making a form that isn't relating to your database. But if you do want to interact with your database then use the ModelForm and and define a ForeignKey in your Student model to relate to the language table, letting the ModelForm do the work for you.

Example app based on my assumptions of your model.

your_project/example_app/models.py:

from django.db import models

class Student(models.Model):
    name = models.CharField(max_length=255)
    language = models.ForeignKey('Language')

class Language(models.Model):
    name = models.CharField(max_length=255)

your_project/example_app/forms.py:

from django.forms import ModelForm
from example.models import Student

class StudentForm(ModelForm):
    class Meta:
        model = Student

Relevant docs: https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#modelform

snippet:

As you might expect, the ForeignKey and ManyToManyField model field types are special cases:

ForeignKey is represented by django.forms.ModelChoiceField, which is a ChoiceField whose choices are a model QuerySet.
ManyToManyField is represented by django.forms.ModelMultipleChoiceField, which is a MultipleChoiceField whose choices are a model QuerySet.

英雄似剑 2024-10-10 00:34:09

该错误消息表明,languages 包含一个包含该数组表示形式的 unicode 字符串,而不是包含数组。 languages 应计算为 [u'English'] (数组),但计算结果为 u"[u'English']" (unicode 字符串) )。

您的 ModelForm 是否包含任何可能会更改 linguals 值的自定义验证(例如 clean_languages 函数)?

顺便说一句:SelectMultiple 已经是 MultipleChoiceField 的默认小部件,因此无需指定该小部件。

对于查找原因很有用的一些内容:

  • 呈现表单的模板代码
  • 表单返回的 POST 数据
  • 用于 ModelForm 类的代码

The error message suggests that instead of containing an array, languages contains a unicode string containing a representation of that array. languages should evaluate to [u'English'] (array) but instead evaluates to u"[u'English']" (unicode string).

Does your ModelForm include any custom validation (say, a clean_languages function) that might be changing the value for languages?

BTW: SelectMultiple is already the default widget for MultipleChoiceField so there's no need to specify the widget.

Some things that would be useful for finding the cause:

  • the template code that renders the form
  • the POST data returned by the form
  • the code used for your ModelForm class
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文