繁体   English   中英

Select 是一个有效的选择。 ...不是可用的选择之一

[英]Select a valid choice. ... is not one of the available choices

我正在尝试创建一个简单的 Django 2.2 应用程序,其中包含单个 model、单个 model 表单 + 自定义字段和一个简单的 CreateView。 我根据对外部 url 的 http 调用动态填充选项。下拉列表填充正常,但是当我尝试提交我的表单时出现错误: Select a valid choice. ... is not one of the available choices Select a valid choice. ... is not one of the available choices并且在下拉列表中使用新的 3 个建议刷新了表单。

模型.py

class GhostUser(models.Model):
    first_name = models.CharField("User's first name", max_length=100, blank=False)
    last_name = models.CharField("User's last name", max_length=100, blank=False)
    ghost_name = models.CharField("User's ghost name", max_length=100, blank=False)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return f"{self.ghost_name}"

    def get_absolute_url(self):
        return reverse('ghost_names:ghost-update', kwargs={'id': self.id})

视图.py

class GhostCreateView(CreateView):
    template_name = 'ghost_create.html'
    form_class = GhostUserForm
    success_url = '/'
    # def get_context_data(self, **kwargs):
    #     data = super().get_context_data(**kwargs)
    #     url = "https://donjon.bin.sh/name/rpc-name.fcgi?type=Halfling+Male&n=3"
    #     resp = urllib.request.urlopen(url)
    #     names = resp.read().decode('utf-8')
    #     data['ghost_suggestions'] = names.splitlines()
    #     return data

forms.py

class GhostUserForm(forms.ModelForm):
    ghost_name = forms.ChoiceField(choices=[], widget=forms.Select())
    class Meta:
        model = GhostUser
        fields = ['first_name', 'last_name']



    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['ghost_name'].choices = tuple(get_ghost_names())


def get_ghost_names():
    url = "https://donjon.bin.sh/name/rpc-name.fcgi?type=Halfling+Male&n=10"
    resp = urllib.request.urlopen(url)
    data = resp.read().decode('utf-8').splitlines()
    names = []
    for name in data:
        existing_ghosts = GhostUser.objects.filter(ghost_name=name)
        if existing_ghosts:
            continue
        else:
            print(name.split())
            if len(name.split()) > 1:
                name = name.split()[0]
            names.append((name, name))
    return names[:3]

html

{% block content %}

<form action="." method="POST">{% csrf_token %}
    {% for field in form.visible_fields %}
    <p>
        {{ field.label_tag }}
        {{ field }}
        {{ field.errors }}
    </p>
    {% endfor %}

    <input type="submit" value="Create ghost name">
</form>
{% comment %}{{ghost_suggestions}}
<select name="prefer_car_model" id="id_prefer_car_model" required>
                <option value="0" selected disabled> Select ghost name </option>
                {% for obj in ghost_suggestions %}
                <option value="{{ obj }}">{{ obj }} </option>
                {% endfor %}
            </select>
{% endcomment %}

{% endblock content %}

我在这里做错了什么? 非常感谢您在这个对我来说很奇怪的问题上的帮助。

PS当我从视图和模板中添加注释掉的代码并一一呈现折叠字段时,表单提交时没有错误。

你没有在 form.py GhostUserForm class 中提到字段名称 ghost_name 更改行

fields = ['first_name', 'last_name']  to fields = ['first_name', 'last_name','ghost_name ']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM