【发布时间】:2018-01-15 15:05:13
【问题描述】:
我发现这比我想象的要复杂得多。我有 Django 1.4.5 并使用模型原型和模板想要创建具有多个复选框的选项。我热衷于使用模型、表单和视图方法,因为我以后想使用数据库。现在我只是在寻找如何显示多个复选框以允许多个选择时遇到了麻烦。
模型.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
这样做的最佳方法是什么,以便我以后可以轻松地使用数据库。但与此同时,我无法让它工作。
【问题讨论】:
-
您确定您的 forms.py 使用的是“forms.MultipleChoiceField()”而不仅仅是“MultipleChoiceField()”吗?因为该错误消息使它看起来像后者。
-
啊是的,我把它拿出来了,但是form.XXX回来的错误信息是:'module' object has no attribute 'MultipleChoiceField'
-
如果你尝试“from django.forms import MultipleChoiceField”然后在 forms.py 中使用“MyGenderPref = MultipleChoiceField(...)”会发生什么?如果这样可行,那么 Brenda 是对的,并且您导入了错误的表单模块。