开发者

Combining querysets on a choice field in django

开发者 https://www.devze.com 2023-03-28 03:39 出处:网络
I have the following form: class FeaturedVideoForm(ModelForm): featured_video = forms.ModelChoiceField(Video.objects.none()

I have the following form:

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

I have used a print statement to after the last line of the constructor to confirm it is returning the correct list of videos, and it is. However, I'm having difficulty displaying it in the template.

I've tried:

{% for video in form.featured_video.choices %}
<option value="{{video}}">{{video}}</opti开发者_高级运维on>
{% endfor %}

which returns an empty set of choices.

And I've tried:

{{form.featured_video}}

which gives me TemplateSyntaxError at /profile/edit/featured_video/. Caught TypeError while rendering: 'Video' object is not iterable.

How would I correctly render this Select form? Thank you.


Choices needs to be a list of tuples:

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

And to display in the template:

{{form.featured_video}}
0

精彩评论

暂无评论...
验证码 换一张
取 消