用户在表单选择中过滤ManyToManyField(**)

时间:2017-03-09 23:21:02

标签: python-3.x django-models django-forms

我需要将歌曲添加到我的播放列表中 - 但我希望只有用户可以添加您注册的歌曲,而不是所有歌曲。

我有这个:

模型

class Song(models.Model):
    user = models.ForeignKey(User, default=1)
    title=models.CharField(max_length=500)
    artist = models.CharField(max_length=250)
    audio = models.FileField(default='')
    def __str__(self):
        return self.title

class List(models.Model):
    user_list = models.ForeignKey(User, default=User)
    title_list=models.CharField(max_length=500)
    songs = models.ManyToManyField(Song) 
    def __str__(self):
        return self.title_list

形式

class SongForm(forms.ModelForm):
    class Meta:
        model = Song
        fields = ['title', 'artist',  'audio']


class ListForm(forms.ModelForm):
    #songs=forms.MultipleChoiceField(Song.objects.all(), widget=forms.CheckboxSelectMultiple)
    #songs= forms.MultipleChoiceField( widget=forms.CheckboxSelectMultiple)
    #songs=forms.ModelMultipleChoiceField(queryset=Song.objects.all(), widget=forms.CheckboxSelectMultiple) #here i dont know why the form dont save data
   #I want this
    songs=forms.ModelMultipleChoiceField(queryset=Song.objects.filter(user=actualuser),widget=forms.CheckboxSelectMultiple)
    class Meta:
        model = Lista
        fields = ['title_list','songs']
#views

def new_list(request):
    form=ListForm(request.POST or None, request.FILES or None)

if form.is_valid():
    lista = form.save(commit=False)
    lista.user_list = request.user
    lista.save()

    context = {
        'username': request.user.username,
        'lista': lista,
    }
    return render(request,'MyMusic/list_detail.html',context)

context={
    'form':form,
    'error_message': 'Error ',
}
return render(request,'MyMusic/list_form.html',context)

在表单视图中我只需要查看,我只想选择自己注册的歌曲,我也希望能看到一个不是实际的复选框(widget = forms.CheckboxSelectMultiple),但实际上这并不能保存数据。

1 个答案:

答案 0 :(得分:0)

对我而言的解决方案。

**Forms**
class ListForm(forms.ModelForm):
    def __init__(self,user, *args, **kwargs):
        super(ListForm, self).__init__(*args, **kwargs)
        self.fields['songs'] = forms.ModelMultipleChoiceField(queryset=Song.objects.filter(user=user)
                                                                  ,required=False,widget=forms.CheckboxSelectMultiple)
    class Meta:
        model = Lista
        fields = ['title_list','songs']
视图中的

def new_list(request):
    form=ListForm(request.user,request.POST or None, request.FILES or None)

if form.is_valid():
    lista = form.save(commit=False)
    lista.user_list = request.user
    lista.save()
    lista.canciones = form.cleaned_data['songs'] # avoid conflict to save checkbox

    context = {
        'username': request.user.username,
        'lista': lista,
    }
    return render(request,'MyMusic/list_detail.html',context)

context={
    'form':form,
    'error_message': 'Error ',
}
return render(request,'MyMusic/list_form.html',context)