2017-10-13 2 views
1

나는이 같은 __init__ 기능에 self.fields에 추가되는 복수의 동적 필드 (더 클래스 속성)을 가진 형태로 만들어 넣 형태 : 이제장고 : 동적 필드

class CustomForm(django.forms.Form): 
    def __init__(dynamic_fields, *args, **kwargs): 
     super(CustomForm, self).__init__(*args, **kwargs) 
     for name, field in dynamic_fields.items(): 
      self.fields[name] = field 

dynamic_fields = {'val1': IntegerField(), 'val2': FloatField()} 
CustomForm(dynamic_fields) 

을 나는 방법을 모른다 POST 요청 후에 양식을로드하십시오. 일반적으로, 내가 좋아하는 일을 할 것입니다 :

custom_form = CustomForm(request.POST) 
if custom_form.is_valid(): 
    data = custom_form.cleaned_data 
    ... 

그러나 필드가 super가 호출 될 때 양식을 알 수없는, 나는 수동으로 나중에 필드를로드하는 방법을 모른다

. 아이디어? 그것은 Form 클래스의 __init__ 함수와 유사 Form 클래스에서 불과 설정 데이터 속성에 근무 나를 위해

class CustomForm(django.forms.Form): 
    def __init__(dynamic_fields, *args, **kwargs): 
     self.base_fields.update(dynamic_fields) 
     super(CustomForm, self).__init__(*args, **kwargs) 

dynamic_fields = {'val1': IntegerField(), 'val2': FloatField()} 
CustomForm(dynamic_fields) 
+0

필드 키는 항상 동일한 필드 유형을 가리 킵니까? – grrrrrr

+0

아니, 모든 유효한 장고 필드 형식의 필드 형식이 될 수 – Henhuy

답변

1

당신은 super__init__를 호출하기 전에 base_fields를 업데이트 할 수 있습니다. 또한, is_bound 속성은 is_valid() 방법을 통해 양식을 검증하기 위해 설정해야합니다 :

class CustomForm(django.forms.Form): 
    def __init__(dynamic_fields, data=None, *args, **kwargs): 
     super(CustomForm, self).__init__(*args, **kwargs) 
     for name, field in dynamic_fields.items(): 
      self.fields[name] = field 
     self.is_bound = data is not None 
     self.data = data or {} 

그러나 이것은 올바른 해결 방법은 경우에 나는 아주 확실하지 않다?!

+0

이것은 트릭을! 'custom = CustomForm (dynamic_fields, request.POST) '를 호출 한 후에'custom.is_valid()'를 계속 호출하고'custum.cleaned_data'를 통해 데이터를 얻을 수 있습니다. 감사! – Henhuy

+0

한 페이지에 여러 개의 'CustomForms'을 사용하면 솔루션이 작동하지 않는다는 것을 알았습니다. 왜냐하면'base_fields'는 클래스 속성이기 때문입니다. 따라서 필드를 변경하면 ** 모든 ** CustomForms 필드가 변경되어 모든 양식의 필드 복사본이 만들어집니다. – Henhuy

+0

확실히 솔루션은 꽤 해킹입니다. 그러나 나는 그것이 당신이하려는 것을 본질이라고 생각합니다. 'BaseForm'의'__init__ '에서'fields' 속성은'self.base_fields'를 복사함으로써 생성됩니다. 그래서'update' 호출 전에'CustomForm'''''에'self.base_fields'의 복사본을 만들고'super's'init'를 호출 한 후에 그것을 재설정하는 것이 트릭을해야한다고 생각합니다 – lmr2391