如何在django中的视图中创建实例时将参数发送到表单类

时间:2013-11-21 05:50:52

标签: django django-forms django-views

Hai我在视图中有以下代码

def fillappraisaltestform(request,temp_id):
    if request.method == 'POST': # If the form has been submitted...
        form = FillAppraisalTestForm(request.POST) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            # Process the data in form.cleaned_data
            # ...
            comments = form.cleaned_data['Comments']
            return HttpResponseRedirect('/thanks/') # Redirect after POST
    else:
        form = FillAppraisalTestForm(temp_id) # An unbound form


    return render(request, 'schdeules/fill_appraisal_test_form.html', {'form': form,})

我的表单代码是

class QuestionIteratedFieldsMetaclass(type):
    def __new__(cls, name, bases, attrs):
        attrs['base_fields'] = get_declared_fields(bases, attrs)

        for question in tbtrnappraisalquestion.objects.filter(intTemplateID_id=temp_id).order_by('intPartID','intSectionID','intOrder'):
            attrs['base_fields']['textbox_question%s' % question.intQuesID] = forms.CharField(label = question.txtQuestion,required=True)

        new_class = super(QuestionIteratedFieldsMetaclass,
                 cls).__new__(cls, name, bases, attrs)
    if 'media' not in attrs:
        new_class.media = media_property(new_class)
    return new_class   

class FillAppraisalTestForm(six.with_metaclass(QuestionIteratedFieldsMetaclass, forms.BaseForm),temp_id):
    pass

我的问题是如何将模板ID从视图发送到表单然后再发送到QuestionIteratedFieldsMetaclass.so,我可以获得该特定模板ID的问题吗?

1 个答案:

答案 0 :(得分:0)

我不知道你为什么在这里使用元类,它完全矫枉过正。只需使用标准模型并覆盖__init__即可达到相同的效果。

class FillAppraisalTestForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        temp_id = kwargs.pop('temp_id', None)
        super(FillAppraisalTestForm, self).__init__(*args, **kwargs)
        for question in tbtrnappraisalquestion.objects.filter(intTemplateID_id=temp_id).order_by('intPartID','intSectionID','intOrder'):
            self.fields['textbox_question%s' % question.intQuesID] = forms.CharField(label=question.txtQuestion, required=True)

现在,您可以使用FillAppraisalTestForm(request.POST, temp_id=temp_id)实例化表单。