我发现这比我想象的要复杂得多。我有Django 1.4.5并且使用模型原型和模板想要创建具有多个复选框的选项。我很想使用模型,表单和视图方法,因为我以后会使用数据库。现在,我只是无法找到如何显示多个可以允许多个选择的复选框。
Models.py
GENDER_CHOICES = (
('M', 'Male'),
('F', 'Female'),
('O', 'Other'),
)
class Gender(models.Model):
MALE = 1
FEMALE = 2
OTHER = 3
gender = models.CharField(('Gender'), max_length=512, choices=GENDER_CHOICES,blank=True)
class MyPreferences(models.Model):
MyGenderPref = models.ManyToManyField(Gender, blank=True, null=True)
Forms.py
class MyPreferencesForm(forms.Form):
MyGenderPref = forms.MultipleChoiceField(choices=GENDER_CHOICES,widget=forms.CheckboxSelectMultiple())
Views.py
from django.forms import ModelForm
from django.forms import forms
from TestForm.models import MyPreferences
def GoPreferences(request):
if request.method == "POST":
form = MyPreferencesForm(request.POST)
if form.is_valid():
commit=False means the form doesn't save at this time.
commit defaults to True which means it normally saves.
model_instance = form.save(commit=False)
model_instance.timestamp = timezone.now()
model_instance.save()
return redirect('victory')
else:
form = MyPreferencesForm()
return render(request, "aboutme.html", {'form': form})
然而,当我尝试这个时,我得到:
GET
Request URL: http://127.0.0.1:8080/myprefs
Django Version: 1.4.5
Exception Type: NameError
Exception Value:
name 'MultipleChoiceField' is not defined
Exception Location: /home/brett/TestForm/TestForm/forms.py in MyPreferencesForm, line 17
Python Executable: /usr/bin/python
Python Version: 2.7.4
这样做的最佳方法是什么,以便我以后可以轻松使用数据库。但与此同时,我无法实现这一目标。
答案 0 :(得分:0)
在导入部分,您有
from django.forms import forms
也许应该是
from django import forms