Django multiselect不会返回/渲染保存在数据库中的选定选项
form.py
class testform(forms.ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
temp = User.objects.values_list('username', flat=True).filter(groups__name = "Artist")
OPTIONS1 = zip(temp, temp)
self.fields['column'].choices = [OPTIONS for OPTIONS in OPTIONS1]
column = forms.MultipleChoiceField(required = True, choices= [])
选择选项就像
views.py
def index(request):
if request.method == "POST":
form = testform(request.POST)
if form.is_valid():
form.save()
return redirect('index')
else:
form = testform()
return render(request, 'dummy/index.html', {
'edit_form' : form})
数据被保存为选中状态
['artist1', 'artist2', 'artist3']
但是在重新访问同一页面时,它不会显示该实例的所选选项,而是“选择多个”框没有上述3个选项的选择
检索视图
def dummyedit(request, id):
obj = bfs_projects.objects.get(id = id)
if request.method == "POST":
form = testform(request.POST, instance =obj)
if form.is_valid():
form.save()
return redirect('index')
else:
form = testform(instance =obj)
return render(request, 'dummy/index.html', { 'edit_form' : form, })
models.py
class bfs_projects(models.Model):
column = models.CharField(max_length = 255)
非常感谢您的帮助, 预先感谢