gpt4 book ai didi

python - Django ModelForm 外键 optgroup 选择

转载 作者:太空宇宙 更新时间:2023-11-03 12:06:16 25 4
gpt4 key购买 nike

我正在使用 Django 1.8 构建一个简单的问答网站。
我想根据 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')

问题表

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

模板(显示选择)

{{ form.college }}

当前结果
enter image description here

需要的结果
enter image description here

谢谢!

最佳答案

我知道这已经过时了,但我已经找到了解决“将按外键分类的 ModelChoiceField 选项显示到另一个模型”的问题的解决方案。

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

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

问题表:

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

关于python - Django ModelForm 外键 optgroup 选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31256905/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com