gpt4 book ai didi

django-forms - Django表单,使用RadioSelect小部件的ModelChoiceField,按FK分组

转载 作者:行者123 更新时间:2023-12-02 04:19:13 32 4
gpt4 key购买 nike

挑战是,在嵌套的<ul></ul>中输出一个单选,按任务fk分组。

即。

class Category(models.Model):
# ...

class Task(models.Model):
# ...
category = models.ForeignKey(Category)
# ...

表格
class ActivityForm(forms.ModelForm):
# ...
task = forms.ModelChoiceField(
queryset = Task.objects.all(),
widget = RadioSelectGroupedByFK
)

widgets.py
class RadioFieldRendererGroupedByFK(RadioFieldRenderer):
"""
An object used by RadioSelect to enable customization of radio widgets.
"""
#def __init__(self, attrs=None):
# Need a radio select for each?? Just an Idea.
#widgets = (RadioSelect(attrs=attrs), RadioSelect(attrs=attrs))
#super(RadioFieldRendererGroupedByFK, self).__init__(widgets, attrs)

def render(self):
"""Outputs nested <ul> for this set of radio fields."""
return mark_safe(
#### Somehow the crux of the work happens here? but how to get the
#### right context??
u'<ul>\n%s\n</ul>' % u'\n'.join(
[u'<li>%s</li>' % force_unicode(w) for w in self]
)
)

class RadioSelectGroupedByFK(forms.RadioSelect):
renderer = RadioFieldRendererGroupedByFK

最好的谢谢!

最佳答案

itertools.groupby() 非常适合。我假设TaskCategory都具有您希望它们排序的name属性。我不知道Django API,因此您可能需要将排序移到db查询中,并且需要查看小部件的属性以弄清楚如何访问任务对象,但这是基本公式:

from itertools import groupby

# sort first since groupby only groups adjacent items
tasks.sort(key=lambda task: (task.category.name, task.name))

for category, category_tasks in groupby(tasks, key=lambda task: task.category):
print '%s:' % category.name
for task in category_tasks:
print '* %s' % task.name

这应该打印如下列表:
Breakfast foods:
* eggs
* spam
Dinner foods:
* spam
* spam
* spam

高温超导

关于django-forms - Django表单,使用RadioSelect小部件的ModelChoiceField,按FK分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/656614/

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