首页 > 解决方案 > 为什么我无法在我的 html 模板上获得下拉菜单?

问题描述

我添加了我的 html 模板在浏览器中的外观截图。我没有在我的表单中获得名称标签的下拉列表。我在我的模型中获得了所需的输出(下拉列表)。我已经浏览了 Django 的官方文档,但找不到解决方案。我是 Django 新手。我该怎么办?

模型.py

from django.db import models

class Record(models.Model):
    CHOICES = (  
    ('john', 'JOHN'),
    ('sam', 'SAM'),
    ('lucy', 'LUCY')
)
    date = models.DateTimeField(auto_now_add = True)
    emp_name = models.CharField(max_length=10, choices=CHOICES)
    amount = models.PositiveIntegerField(default=0)

视图.py

from django.http import HttpResponse
from django.views.generic import FormView
from .models import Record
from .forms import RecordForm

class home(FormView):
    template_name = 'myapp/home.html'
    form_class = RecordForm

    def form_valid(self, form):
        return HttpResponse("Sweeeeeet.")

表格.py

from django import forms
from .models import Record

CHOICES = [  
    ('john', 'JOHN'),
    ('sam', 'SAM'),
    ('lucy', 'LUCY')
]

class RecordForm(forms.ModelForm):
    name = forms.CharField(label='Name', widget=forms.Select(choices=CHOICES))
    amount = forms.IntegerField()

    class Meta:
        model = Record
        fields = '__all__'

网址.py

from django.urls import path
from django.contrib.auth import views as auth_views
from .views import EmployeeListView, home
from . import views

urlpatterns = [
    path('', home.as_view(),name='home'),
    path('logout/', auth_views.LogoutView.as_view(template_name = 'myapp/logout.html'), name='home-logout'),
    path('profile/', views.profile, name='home-profile'),
    path('employee/', EmployeeListView.as_view(), name='home-employee'),
]

主页.html

<style type="text/css">
  .form-container {
      border-radius: 10px;
      padding: 10px;
      box-shadow: 0px 0px 10px 0px;
  }
  .row {
    padding: 80px;
  }
</style>

<div class="row">
  <div class="col s12 m12">
    <div class="card teal lighten-1">
      <div class="card-content white-text">
        <form method="POST" class="form-container">
          {% csrf_token %}
          <div class="fieldWrapper">
            <label for="id_name">Name</label>
            {{ form.name }}
          </div>
          <div class="fieldWrapper">
            <label for="id_amount">Amount</label>
            {{ form.amount }}
        </div>
          <button class="waves-effect waves-light btn" type="submit">Post</button>
      </form>
      </div>
    </div>
  </div>
</div>

输出

没有获得名称标签的下拉列表

标签: djangodjango-modelsdjango-formsdjango-templatesdjango-views

解决方案


推荐阅读