passing arguments to a dynamic form in django

前端 未结 2 1910
时光说笑
时光说笑 2020-12-28 15:56

I have a Dynamic Form in forms. How can I pass an argument from my view when I instantiate my form?

Something like:

form = DynamicForm(\"some string         


        
相关标签:
2条回答
  • 2020-12-28 16:37

    Add it as keyword argument, say it's called my_arg. Make sure to pop() the keyword arg before calling super(), because the parent class's init method doesn't accept extra keyword arguments.

    class DynamicForm(Form):
      def __init__(self, *args, **kwargs):
        my_arg = kwargs.pop('my_arg')
        super(DynamicForm, self).__init__(*args, **kwargs)
        for item in range(5):
            self.fields['test_field_%d' % item] = CharField(max_length=255)
    

    And when you create form it's like this:

    form = DynamicForm(..., my_arg='value')
    
    0 讨论(0)
  • 2020-12-28 16:46

    You can also achieve this by overriding the get_form_kwargs of the FormMixin, available in class based views.

    class CustomDynamicFormView(FormView):  # inherit any view with formmixin...
          form_class = DynamicForm
          
          def get_form_kwargs(self):
              kwargs = super(CustomDynamicFormView, self).get_form_kwargs()
              kwargs['custom_variable'] = 'my custom variable'
              return kwargs
    

    Then in your form

    class DynamicForm(forms.Form):
        def __init__(self, *args, **kwargs):
            my_var = kwargs.pop('custom_variable') 
            # remove this b4 calling super otherwise it will complian
            super(DynamicForm, self).__init__(*args, **kwargs)
            # do what you want with my_var
    

    For more information check here

    0 讨论(0)
提交回复
热议问题