如何使用选项创建ManyToManyField

时间:2015-05-14 18:31:57

标签: django django-models django-forms

我正在尝试创建一个Django(1.7.3)models.ManyToManyField,允许用户从MultipleChoiceField中选择多个选项,但我遇到了一些麻烦。这个想法是用户可以选择他们打算投票的多个选举。

目前,当我运行syncdb时,我没有收到任何错误,当我访问带有问题的页面时,它只是部分显示默认标题而没有问题选项。

enter image description here

我一直在网上搜索这里,但我不确定我错过了什么。任何帮助都非常适合

models.py

class Person(models.Model):

    election = models.ManyToManyField('Elections')

    def __unicode__(self):
        return self


class Elections(models.Model):

    ELECTION_TYPE = (
        ('NONE', 'None'),
        ('LOCAL', 'Local elections'),
        ('STATE', 'State elections e.g. Governorship'),
        ('NATIONAL', 'National elections e.g. Congress and Senate'),
        ('PRESIDENTIAL', 'Presidential elections'),
        ('OTHER', 'Other'),
        ('DONT_KNOW', "Don't know"),)  

    election_type = models.CharField(null=True, max_length=100, default=None, choices=ELECTION_TYPE, verbose_name = 'Which elections do you regularly vote in or intend to vote in? Select all that apply.')


    def __unicode__(self):
        return self

forms.py

class SurveyFormD(forms.ModelForm): # Political Viewpoints

    class Meta:
        model = Person
        fields = ['liberal_conservative', 'democrat_republican', 'voting_rights', 'elections']        

        widgets = {'liberal_conservative' : forms.RadioSelect,
                   'democrat_republican' : forms.RadioSelect,
                   'voting_rights' : forms.RadioSelect,
                   'elections' : forms.CheckboxSelectMultiple,}

0 个答案:

没有答案