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的问题吗?
答案 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)
实例化表单。