在django中的选择字段上组合查询集

时间:2011-08-13 23:36:53

标签: django django-templates django-forms

我有以下表格:

class FeaturedVideoForm(ModelForm):

    featured_video = forms.ModelChoiceField(Video.objects.none()
                                        widget=make_select_default,
                                        required=False,  
                                        empty_label='No Featured Video Selected')
    class Meta:
        model = UserProfile
        fields = ('featured_video',)

    def __init__(self, userprofile, *args, **kwargs):
        videos_uploaded_by_user=list(userprofile.video_set.all())
        credits_from_others=[video.video for video in userprofile.videocredit_set.all()]
        all_credited_videos=list(set(videos_uploaded_by_user+credits_from_others))
        super(FeaturedVideoForm, self).__init__(*args, **kwargs)
        self.fields['featured_video'].choices = all_credited_videos

我在构造函数的最后一行之后使用了print语句来确认它正在返回正确的视频列表,而且确实如此。但是,我在模板中显示它时遇到了困难。

我试过了:

{% for video in form.featured_video.choices %}
<option value="{{video}}">{{video}}</option>
{% endfor %}

返回一组空的选项。

我试过了:

{{form.featured_video}}

给了我TemplateSyntaxError at /profile/edit/featured_video/. Caught TypeError while rendering: 'Video' object is not iterable.

如何正确呈现此选择表单?谢谢。

1 个答案:

答案 0 :(得分:3)

选择必须是元组列表:

def __init__(self, userprofile, *args, **kwargs):
    ### define all videos the user has been in ###
    videos_uploaded_by_user=list(userprofile.video_set.all())
    credits_from_others=[video.video for video in userprofile.videocredit_set.all()]
    all_credited_videos=list(set(videos_uploaded_by_user+credits_from_others))

    ### build a sorted list of tuples (CHOICES) with title, id
    CHOICES=[]
    for video in all_credited_videos:
        CHOICES.append((video.id,video.title))
    CHOICES.sort(key=lambda x: x[1])

    ### 'super' the function to define the choices for the 'featured_video' field
    super(FeaturedVideoForm, self).__init__(*args, **kwargs)
    self.fields['featured_video'].choices = CHOICES

并在模板中显示:

{{form.featured_video}}