0

我发现这比我认为的要复杂得多。我有 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)

表格.py

class MyPreferencesForm(forms.Form):
        MyGenderPref = forms.MultipleChoiceField(choices=GENDER_CHOICES,widget=forms.CheckboxSelectMultiple())

视图.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

这样做的最佳方法是什么,以便我以后可以轻松使用数据库。但与此同时,我无法让这个工作。

4

1 回答 1

0

在导入部分,您有

from django.forms import forms

也许应该是

from django import forms
于 2013-08-18T20:50:46.867 回答