2011-08-13 86 views
3

我有以下形式:組合查詢集上一個選擇字段在Django

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.

我將如何正確地渲染這種選擇的形式?謝謝。

回答

2

的選擇必須是元組的列表:

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}} 
相關問題