【发布时间】:2021-01-25 12:03:36
【问题描述】:
我正在尝试使用单个模型、单个模型表单 + 自定义字段和一个简单的 CreateView 创建一个简单的 Django 2.2 应用程序。我正在根据对外部 url 的 http 调用动态填充选择。下拉列表填充得很好,但是当我尝试提交表单时出现错误:
Select a valid choice. ... is not one of the available choices 并刷新表单,下拉列表中包含新的 3 条建议。
models.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})
views.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 %}
我在这里做错了什么?感谢您为我解决这个奇怪的问题提供帮助。
P.S.当我从视图和模板中添加注释掉的代码并一一呈现折叠字段时,表单提交时没有错误。
【问题讨论】:
标签: python django django-forms django-class-based-views