python - 更新:动态 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”实例
选项值似乎是字符串而不是对对象的引用。我该如何解决这个问题?
解决方案
这限制了您的选择字段的可能选项:
self.fields['theSelectField'].queryset = SomeModel.objects.filter(someUser = someUser)
在您的视图中,您可能希望使用基于类的视图,因为它会自动处理大量内容并节省您的时间。看看这里:https ://ccbv.co.uk/
推荐阅读
- mysql - 在 azure 中使用 java 函数应用程序获取 SSL 和连接错误
- blueprism - 将 Excel 中的宏注入 BluePrism
- swift - Firebase 实时数据库和 Xcode:允许每个用户读取自己的数据而不是所有数据
- android - 如何从另一个领域对象中使用一个领域对象?
- performance-testing - 无法理解 jprofiler 的调用树视图
- android - PreferenceManager.setDefaultValues 不适用于自定义首选项
- python - 如何处理 Django 嵌套模板标签
- mysql - MYSQL:INNER JOIN 与 BIG TABLES 的替代方案(太慢了)
- android - Flutter:资源链接失败
- dataframe - 将聚合列添加到无需连接的数据透视表