我是django的新手,我正在尝试让ChoiceField用于用户输入。 我已经尝试了两次html迭代,但是都没有显示任何形式的下拉列表。
有关模型,表格和html,请参见下面的代码
models.py
from django.db import models
from django.contrib.auth.models import User
class Post(models.Model):
CATEGORIES=(
('COM', 'Combat'),
('CRA', 'Crafting'),
('WAR', 'Warfare'),
)
post= models.CharField(max_length=500)
post2= models.CharField(max_length=500)
category=models.CharField(max_length=3, choices=CATEGORIES)
user = models.ForeignKey(User, on_delete=models.CASCADE)
forms.py
class HomeForm(forms.ModelForm):
post = forms.CharField()
post2 = forms.CharField()
category = forms.ChoiceField(choices=Post.CATEGORIES)
class Meta:
model = Post
fields = ('post','post2','category',)
html
<form method="post">
{% csrf_token %}
{{form.as_p}} or {{form}}
<input type="submit" value="Submit">
</form>
views.py
Class HomeView(TemplateView): template_name ='fitness / name.html'
def get(self, request):
form = HomeForm()
return render(request, self.template_name, {'form':form})
def post(self, request):
form = HomeForm(request.POST)
if form.is_valid():
form.save()
text = form.cleaned_data['post']
form = HomeForm()
return redirect('home:home')
args = {'form': form, 'text': text}
return render(request, self.template_name, args)
答案 0 :(得分:0)
尝试一下
class HomeForm(forms.ModelForm):
post = forms.CharField()
post2 = forms.CharField()
class Meta:
model = Post
fields = ('post','post2','category',)
widgets = {
'category': forms.Select(choices=Post.CATEGORIES,attrs={'class': 'form-control'}),
}