0

私はこれが私が思っているよりもずっとトリッキーだと思っています。私はDjango 1.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)

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

これを行う最善の方法は何ですか。後で最小限の手間でDBを使用できます。しかし、その間、私はこれを機能させることができません。

4

1 に答える 1

0

インポートセクションには、

from django.forms import forms

多分それはあるべきです

from django import forms
于 2013-08-18T20:50:46.867 に答える