Django在发布请求中设置表单字段值

时间:2018-01-02 23:02:36

标签: python django forms post

我正在尝试使用request.session中的数据在Post请求中的views.py中设置表单字段值,然后将该数据保存到db。但是,我无法弄清楚如何做到这一点。这是我尝试过的:

    if self.form.is_valid():
        #attempt 1
        request.POST._mutable = True
        self.form.data['field'] = request.session['key']

        #attempt 2
        self.form.fields['field'] = request.session['key']

        #attempt 3
        self.form.cleaned_data['field'] = request.session['key']

        self.object = self.form.save()

有办法做到这一点吗?

1 个答案:

答案 0 :(得分:1)

经过反复试验,我发现它有可能,但必须在表单验证声明之外完成。我是这样做的:

def post(self, request, *args, **kwargs):
    request.POST._mutable = True
    self.form.data['field'] = request.session['key']

    if self.form.is_valid():
        ........