我是Django的新手,我研究了如何创建下拉列表。我尝试了所有方法,但仍然没有在HTML视图中显示下拉列表。 我的示例脚本就是这个。
这是model.py
from django.db import models
class samplemodel(models.Model):
list = (
('sample1','SAMPLE1'),
('sample2','SAMPLE2'),
)
list_choices = models.CharField(max_length=6, choices=list)
forms.py
from .models import samplemodel
from django.forms import ModelForm
class sampleForm(ModelForm):
class Meta:
model = samplemodel
fields = ['list_choices']
这是views.py
from django.shortcuts import render
from .models import samplemodel
from .forms import sampleForm
from django.views.generic import CreateView
class sampleView(CreateView):
model = samplemodel
form_class = sampleForm
template_name = 'home/sample.html'
这是home.html
{% extends 'base.html' %}
{% block head %}
<title>Home</title>
{% endblock %}
{% block body %}
<div class="container">
<form class="post">
{% csrf_token %}
{{ form.as_p }}
</form>
</div>
{% endblock %}
我尝试了我在互联网上看到的一切。但我仍然无法显示下拉菜单。我不知道imports
是否是问题。
答案 0 :(得分:0)
你的模特应该是这样的
from django.db import models
class SampleModel(models.Model):
list = (
('sample1','SAMPLE1'),
('sample2','SAMPLE2'),
)
list_choices = models.CharField(max_length=6, choices=list)
&#13;
你的urlconf中的
from django.views.generic import CreateView
from app.models import Samplemodel
from django.forms import ModelForm
url(r'^sample_form$',CreateView.as_view(model=SampleModel, template_name='home/sample.html', success_url='index', name='sample_form'))
&#13;
这就是你不需要forms.py。 django将照顾一切