首页 > 解决方案 > django 表单中的多级下拉菜单

问题描述

Django 初学者在这里。

我想以 django 形式创建一个 2 级下拉菜单。像这样的东西:

https://imgur.com/8s3mwiy

我希望能够用字符串“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 %}

标签: pythondjangoformslist

解决方案


推荐阅读