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

时间:2018-07-07 10:37:45

标签: django python-3.x

发布请求使用相同的键发送多个值,例如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>

1 个答案:

答案 0 :(得分:-1)

令人沮丧的是,Django似乎并没有优雅地处理表单数据中的多个值。

我使用Intellij调试器检查request.POST。我可以在键values的列表中看到多个值,但是顾名思义,QueryDict似乎理解键的值只能为一个,而其余值将被丢弃。目前,我已经添加了以下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']
}

我正在使用Content-Type: application/x-www-form-urlencoded