python - django 表单中的多级下拉菜单
问题描述
Django 初学者在这里。
我想以 django 形式创建一个 2 级下拉菜单。像这样的东西:
我希望能够用字符串“A1”、“B3”、“C2”或我从下拉菜单中选择的任何内容填写表单字段。
我尝试使用模型中的选择字段来创建表单的选择,但我不知道如何将其转换为 2 级下拉菜单。也许文档中有提示,但我找不到它...
https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.Field.choices
在此先感谢您的帮助!
# models.py
from django.db import models
class Player(models.Model):
name = models.CharField(max_length=100)
POSITION_CHOICES = [
('A', 'A'),
('B', 'B'),
('C', 'C'),
]
"""
how do I specify the second level of choices here(1,2,3)?
also, the second level is always the same for A,B and C and I would like to avoid repeating code.
"""
position = models.CharField(
max_length=2,
choices=POSITION_CHOICES)
# forms.py
from django import forms
from .models import Player
class PlayerForm(forms.ModelForm):
class Meta:
model = Player
fields = ('name', 'position',)
# views.py
from django.views import generic
class PlayerCreateView(generic.CreateView):
model = Player
form_class = PlayerForm
template_name = 'player_form.html'
def form_valid(self, form):
### do I have to add anything here since the choices are hard-coded?
### form.instance.position = ???
return super().form_valid(form)
'player_form.html' 模板。我是否必须在模板中添加任何内容才能显示多级下拉菜单?
{% extends "base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<div class="content-section">
<form method="POST">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Create Player</legend>
{{ form|crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Submit</button>
</div>
</form>
</div>
{% endblock content %}
解决方案
推荐阅读
- wget - 如何导出使用 Dotcms 制作的网站?
- javascript - 如何迭代数组(过滤器)?
- c# - 使用 Microsoft Graph API 的解决方法 NotFound?
- javascript - 在线将 ES6 javascript 文件转换为 ES5
- javascript - 当托管服务提供商需要 app.js 文件时,在 Phusion Passenger 上托管 NestJS 应用程序
- python - 无法打开 Docker 安装的文件夹/文件
- python - Ubuntu 服务器上的无头 Selenium
- c# - IAsyncResult 到 Byte[] 的转换
- typescript - vue3 typescript 问题,如何修复 ts(2305) 错误?
- javascript - 尝试使用 axios 和 formData 发布数据,但它是空的