将自定义值添加到Django ModelChoiceField时不是有效的选择错误

时间:2018-06-30 11:46:10

标签: python django

我正在使用Django 1.9,正在将查询集传递给表单,以便可以在ModelChoiceField中显示数据,在ModelChoiceField中,我添加了两个自定义值。尽管当我提交表单时出现错误,请选择一个有效的选择。该选择不是可用的选择之一。

views.py

def add_basic_album_details(request):

users = User.object.all()

if request.method=="POST":

    form = AddBasicAlbumDetails(users,request.POST)

    if form.is_valid():

        name = form.cleaned_data['name']
        owner = form.cleaned_data['owner']

        album = Album(
            name=name,
            owner=owner,
        )

        album.save()

        return redirect('album_detail',album.id)



else:
    form = AddBasicAlbumDetails(users=users)
return render(request,'add_basic_album_details.html',{
    'form':form
})

forms.py

class AddBasicAlbumDetails(forms.Form):
    def __init__(self,users,
        *args, **kwargs):
        super(AddBasicAlbumDetails, self).__init__(*args, **kwargs)


        self.fields['user']= ModelChoiceField(
                queryset=users,
                label = 'Owner',
                widget = Select(attrs={
                    'class': ' form-control selectpicker',
                    'data-live-search':'true',
                }),
                empty_label = "Not known",
                required=True
            )

            users = self.fields['user']                                    
            users.choices = list(users.choices) + [(0, 'Not applicable'),(1,'Enter user details')]


        self.fields['name'] = forms.CharField(
                max_length=100,
                required=True,
                label='Name',
                widget=TextInput(attrs={'class' : ' form-control span12 small-margin-top small-margin-bottom'}),
            )

0 个答案:

没有答案