You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django创建独立非数据库关联下拉选择框遇页面加载异常求助

Django独立下拉选择框问题修正方案

当前代码存在路由冲突、表单Widget类型错误、模板路径不匹配三个核心问题,导致页面无法打开、下拉选择框不显示。以下是各文件的具体修正步骤:


1. forms.py(修正为下拉选择框Widget)

原代码使用CheckboxSelectMultiple生成多选复选框,并非下拉选择框。根据需求选择单一下拉或下拉多选:

from django import forms

FAVORITE_COLORS_CHOICES = [
    ("blue", "Blue"),
    ("green", "Green"),
    ("black", "Black"),
]

class SimpleCombobox(forms.Form):
    # 方案1:单一下拉选择框
    favorite_color = forms.ChoiceField(
        required=False,
        widget=forms.Select,  # 指定下拉选择框Widget
        choices=FAVORITE_COLORS_CHOICES,
    )
    
    # 方案2:下拉多选选择框(若需要多选)
    # favorite_colors = forms.MultipleChoiceField(
    #     required=False,
    #     widget=forms.SelectMultiple,
    #     choices=FAVORITE_COLORS_CHOICES,
    # )

2. app1/views.py(合并视图、修正模板路径)

原代码存在两个视图函数争抢同一路由,且模板路径指向错误。合并为单个视图并修正路径:

from django.shortcuts import render, redirect
from app1.forms import SimpleCombobox

def index(request):
    form = SimpleCombobox()
    if request.method == "POST":
        form = SimpleCombobox(request.POST)
        if form.is_valid():
            print(form.cleaned_data)
            # 单选输出示例: {'favorite_color': 'blue'}
            # 多选输出示例: {'favorite_colors': ['blue', 'green']}
            return redirect("index")
    
    # 模板路径对应app内的templates目录结构
    return render(request, "app1/index.html", {"form": form})

3. app1/urls.py(修复路由冲突)

原代码两条空路径路由导致只有第一个视图生效,删除重复规则:

from django.urls import path
from . import views

urlpatterns = [
    path('', views.index, name='index'),  # 根路径绑定index视图
]

4. 项目根urls.py(清理重复路由)

原代码重复包含app1.urls导致路由混乱,保留一条规则即可:

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('app1.urls')),  # 根路径直接访问app1页面
    # 若需通过/app1/访问,替换为:path('app1/', include('app1.urls')),
]

5. index.html(确保模板位置正确)

模板需放在以下两个位置之一:

  • 若使用app内模板:app1/templates/app1/index.html
  • 若使用项目根模板:项目根目录templates/index.html(需配合settings.py配置)

模板内容保持不变:

<!DOCTYPE html>
<html>
<head>
    <title>下拉选择框示例</title>
</head>
<body>
    <form method="post">
        {% csrf_token %}
        {{ form }}
        <button type="submit">提交</button>
    </form>
</body>
</html>

6. settings.py(模板目录配置)

根据模板位置调整:

  • 模板在app内:保持DIRS: [](Django自动查找app内templates目录)
  • 模板在项目根templates目录:设置DIRS为[BASE_DIR / 'templates']

示例配置(项目根模板):

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR / 'templates'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

内容的提问来源于stack exchange,提问作者Zollikofen4

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 01:27:49