Django表单字段不会被POST数据填充

时间:2012-11-21 17:37:31

标签: python django forms post

我有一个带有自定义构造函数的模型表单。它检查是否需要文件,如果为false,则删除文件字段。它还有两个隐藏的字段,我在我的视图中初始化。表单类如下:

class SubmitTask(forms.ModelForm):
    task = forms.ModelChoiceField(queryset=Task.objects.all(), widget=forms.HiddenInput())
    student = forms.ModelChoiceField(queryset=UserProfile.objects.all(), widget=forms.HiddenInput())    

    def __init__(self, file_required=False, *args, **kwargs):
            super(SubmitTask, self).__init__(*args, **kwargs)
            if file_required is True:
                    file = forms.FileField(
                            label='Select a file',
                            help_text='max: 2.5 MB'
                    )
            else:
                    del self.fields['file']

    class Meta:
            model = Submission
            exclude = ('date_submitted',)

我的问题是在初始化表单时填充了隐藏字段(我已经确认通过查看HTML代码确实初始化了它的值)。但是,POST请求期间不会填充隐藏字段的值。我在POST请求期间确认表单确实已绑定,并且我还在Firebug上确认POST还包含taskstudent值。这是我views.py

中涉及的方法
def view_task(request, id):
    task = Task.objects.get(pk=id)
    profile = request.user.get_profile()

    data = {}
    data['classroom'] = task.get_classroom()
    data['description'] = task.get_description()

    teacher_classrooms = Classroom.objects.filter(teacher=profile)
    teacher_tasks = Task.objects.filter(classroom__in=teacher_classrooms)

    if not submission and task not in teacher_tasks:
        form = SubmitTask(file_required=task.file_required, initial={'task':task.pk, 'student':profile.pk})

        data['form'] = form
        if request.method == 'POST':
            form = SubmitTask(request.POST, request.FILES)

            if form.is_valid():
                form.save()

    return render_to_response('classrooms/view_task.html',
        data, context_instance=RequestContext(request))

1 个答案:

答案 0 :(得分:1)

您的查看功能对我来说不正确:

提交变量来自何处,在初始化已发布的表单时,您缺少file_required参数,表单处理应该重新组织为:

if request.method == 'POST':
    form = SubmitTask(task.file_required, request.POST, request.FILES)
    ...
else:
    form = SubmitTask(task.file_required, ...)

data['form'] = form