【问题标题】:Combining querysets on a choice field in django在 django 中的选择字段上组合查询集
【发布时间】:2011-10-26 14:34:56
【问题描述】:

我有以下表格:

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

我在构造函数的最后一行之后使用了一个打印语句来确认它正在返回正确的视频列表,并且确实如此。但是,我很难在模板中显示它。

我试过了:

{% 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.

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

【问题讨论】:

    标签: django django-templates django-forms


    【解决方案1】:

    Choices 需要是一个元组列表:

    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}}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-23
      • 2018-06-02
      • 1970-01-01
      • 2016-09-10
      • 1970-01-01
      • 1970-01-01
      • 2013-07-01
      • 2011-07-03
      相关资源
      最近更新 更多