首页 > 解决方案 > 更新:动态 MultipleChoiceField 将实例更改为字符串

问题描述

我有一个具有多项选择字段的 django 表单。该字段应该是动态的,即只应显示与当前登录的用户关联的记录。到目前为止,我已经设法把它放在一起;

表格.py

class myForm(forms.ModelForm):

    def __init__(self, someUser, *args, **kwargs):
        super(myForm, self).__init__(*args, **kwargs)

        someRecords = models.SomeModel.objects.filter(someUser = someUser)
        #The line above gets records associated with a specific user

        displayNames = []
        for i in someRecords:
            displayNames.append((i.someField, i.someOtherField + ' ' + i.someOtherField2))
            #I am basically making a list of tuples, containing a field and a concatnation of two other fields. The latter will be what is displayed in the select box

        self.fields['theSelectField'] = forms.ChoiceField(choices = displayNames)

        class Meta:
            #I defined model, fields and labels here

视图.py

def myFormPage(request):
    someUser = request.user.someextensionofuser.someUser
    form = forms.myForm(someUser)
    context = {'form': form}
    if request.method == 'POST':
        form = forms.myForm(someUser, data = request.POST)
        if form.is_valid():
            #Do Stuff if form is valid. However,this stuff doesn't get done, the page refreshes instead

所以我设法使选择选项动态化。但是,现在我无法提交数据。

编辑:其中一条评论帮助我解决了前面提到的问题。我已经更新了 views.py 代码。但是,现在我遇到了这个错误;

无法分配“'someString'”:“someModel.someField”必须是“someForeignModel”实例

选项值似乎是字符串而不是对对象的引用。我该如何解决这个问题?

标签: pythondjangopostmodelchoicefield

解决方案


这限制了您的选择字段的可能选项:

self.fields['theSelectField'].queryset = SomeModel.objects.filter(someUser = someUser)

在您的视图中,您可能希望使用基于类的视图,因为它会自动处理大量内容并节省您的时间。看看这里:https ://ccbv.co.uk/


推荐阅读