无法通过Django表单保存多个值

无法通过Django表单保存多个值,django,python-3.x,Django,Python 3.x,post请求使用相同的键发送多个值,例如values=foo&values=bar 在Django视图和表单中,我在请求对象中只看到一个值。不确定在Django请求对象中获取多个值需要做什么 // model class AttributeInstance(models.Model): somefilter = models.CharField(max_length=255, blank=True) values = models.TextField() //form clas

post请求使用相同的键发送多个值,例如values=foo&values=bar

在Django视图和表单中,我在请求对象中只看到一个值。不确定在Django请求对象中获取多个值需要做什么

// model
class AttributeInstance(models.Model):
    somefilter = models.CharField(max_length=255, blank=True)
    values = models.TextField()

//form
class ABCModelForm(forms.ModelForm):
    class Meta:
        model = ABCModel
        fields = ('somefilter', 'value')

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if not self.data:
            self.fields['values'] = forms.MultipleChoiceField(())

// view
class ABCModelView(FormView):
    def get(self, request):
        form = ABCModelForm()
        return render(self.request, 'core/abc_model_edit.html', {'form': form})
    def post(self, request):
        try:
            form = ABCModelForm(request.POST)
            form.save()
            form = ABCModelForm()
            return render(self.request, 'core/abc_model_edit.html', {'form': form})
        except Exception as e:
            return HttpResponse(status='400')


<!-- HTML -->
<!-- fills the multiple choice field on runtime based on somefilter -->
<!-- the multiple choice UI element looks like below after rendering -->
<form method="post" id="abcModelForm" novalidate="">
   <input type="hidden" name="csrfmiddlewaretoken" value="abcdcdcd">
   <table>
      <tbody>
         <tr>
            <th><label for="id_somefilter">Description:</label></th>
            <td><input type="text" name="somefilter" maxlength="255" id="id_somefilter"></td>
         </tr>
         <tr>
            <th>
               <label for="id_values">Values:</label>
            </th>
            <td>
               <select name="values" required="" id="id_values" multiple="multiple">
                  <option value="dodo">dodo</option>
                  <option value="bobo">bobo</option>
                  <option value="foo">foo</option>
                  <option value="bar">bar</option>
               </select>
            </td>
         </tr>
      </tbody>
   </table>
   <button type="submit">Save</button>
</form>
//模型
类属性实例(models.Model):
somefilter=models.CharField(最大长度=255,空白=True)
values=models.TextField()
//形式
类ABCModelForm(forms.ModelForm):
类元:
模型=ABCModel
字段=('somefilter','value')
定义初始化(self,*args,**kwargs):
super()
如果不是自我数据:
self.fields['values']=forms.multiplechicefield(())
//看法
ABCModelView类(FormView):
def get(自我,请求):
form=ABCModelForm()
返回呈现(self.request,'core/abc_model_edit.html',{'form':form})
def post(自我,请求):
尝试:
form=ABCModelForm(request.POST)
form.save()
form=ABCModelForm()
返回呈现(self.request,'core/abc_model_edit.html',{'form':form})
例外情况除外,如e:
返回HttpResponse(status='400')
说明:
价值观:
渡渡鸟
波波
福
酒吧
拯救

知道Django似乎无法优雅地处理表单数据中的多个值,这让人沮丧

我使用Intellij调试器检查request.POST。我可以在key
value
的列表中看到多个值,但QueryDict(顾名思义)似乎理解一个key只能有一个值,并删除其余的值。现在我已经添加了下面的hack,但不是很满意。仍在寻找更清洁的解决方案

payload = dict(request.POST) 
payload = {
    key: (value if key == 'values' else value[0])
    for key, value in payload.items()
}
queryDict = QueryDict(json.dumps(payload))
form = AttributeInstanceForm(queryDict)

// this is how payload looks after conversion from QueryDict
{
  'description': ['hmm'], 
  'values': ['foo', 'bar', 'gogo']
}

我正在使用
内容类型:application/x-www-form-urlencoded

这简直是胡说八道。当然,Django可以为一个字段处理多个值,否则您认为multipleChiceField应该如何工作
request.POST.getlist('field_name')
获取字段的值列表。但是,这与您的问题无关,因为所有这些都是由表单本身处理的。很抱歉,request.POST.getlist('field_name')没有给我字段值。也许我用的方法不对。与其说它是胡说八道,不如提出一个可行的解决方案:(我不能,因为我根本不明白你想做什么。为什么你只在没有数据的情况下将一个字段设置为多选?你希望用多个值做什么,因为你的模型只能接受单个值?模型字段应该是一个值列表,但这些值被限制为属于特定的集合d。)根据用户在其他字段中的选择。我为模型字段选择了JSONField数据类型,为表单选择了MULTIPECHOICEFILD。我愿意接受不涉及黑客攻击的更好的替代方案