Djang中的多个复选框

2024-10-03 17:19:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我发现这比我想象的要复杂得多。我有django1.4.5,并且使用模型原型和模板希望创建一个选项来拥有多个复选框。我热衷于使用模型、窗体和视图方法,因为我希望以后使用DB。现在我很难找到如何显示允许多个选择的多个复选框。在

在模型.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在

^{pr2}$

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

最好的方法是什么,这样我就可以用最少的麻烦使用一个数据库。但在此期间,我不能让这个工作。在


Tags: frompy模型importformtruemodelmodels