Django ModelForm外键选择组选择

时间:2015-07-06 22:41:13

标签: python django django-forms

我正在使用Django 1.8建立一个简单的Q& A网站  我想根据foreing key创建select optgroup(详情如下)。

我该怎么做?

医学院

class College(models.Model):
    title = models.CharField(max_length=255)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    slug = models.SlugField(blank=True, max_length=100)
    university = models.ForeignKey(to=University, related_name='college_list')

大学

class University(models.Model):
    title = models.CharField(max_length=255)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    slug = models.SlugField(unique=True, blank=True, max_length=100)

问题

class Question(models.Model):
    title = models.CharField(max_length=150)
    body = RedactorField(verbose_name=u'Vsebina')
    slug = models.SlugField(unique=True, blank=True, max_length=100)
    college = models.ForeignKey(to=College, default=1, related_name='questions')

QuestionForm

class CreateQuestionForm(ModelForm):
    class Meta:
        model = Question
        fields = ['title', 'body', 'college']

模板(显示选择)

{{ form.college }}

当前结果
enter image description here

需要的结果
enter image description here

谢谢!

1 个答案:

答案 0 :(得分:0)

我知道这已经很老了,但是我找到了解决此问题的解决方案,“显示由ForeignKey归类到另一个模型的ModelChoiceField选项”。

几年前,Django增加了在ChoiceField中提供嵌套optgroup的功能。但是,没有自动的方法可以从嵌套模型实例的查询集中构建像这样的嵌套选择。

我设法使用OrderedDict将子组组织为组,然后将选项设置为.items()生成器来解决。重要的是要认识到您正在处理动态选择,因为大学和学院的模型实例可能会随着时间而改变。

QuestionForm:

from collections import OrderedDict
from django.core.exceptions import ObjectDoesNotExist

class CreateQuestionForm(ModelForm):
    """
    ModelForm which dynamically builds a nested set of choices for University and College
    """

    class Meta:
        model = Question
        fields = ['title', 'body', 'college']

    def __init__(self, *args, **kwargs):
        super(CreateQuestionForm, self).__init__(*args, **kwargs)  # Sets up the fields

        university_college_choices_dict = OrderedDict()  # Abused to sort into groups
        for college in self.fields["college"].queryset.order_by("university__title", "college__title"):
            choice_tuple = (college.pk, college.title)
            try:
                university_name = college.university.title
            except (AttributeError, ObjectDoesNotExist):
                university_name = False  # Ends up in the generic ungrouped bin
            try:
                university_college_choices_dict[university_name].append(choice_tuple)
            except KeyError:
                university_college_choices_dict[university_name] = [choice_tuple]

        self.fields["college"].choices = university_college_choices_dict.items()  # MUST call .items() to extract the nested tuples