Django - ModelForm Dynamic field update

后端 未结 4 844
情书的邮戳
情书的邮戳 2021-01-06 11:50

I\'m trying to update certain fields a ModelForm, these fields are not fixed. (I have only tutor that is autopopulated by the view)

Model:



        
4条回答
  •  既然无缘
    2021-01-06 12:46

    I've had to do something similar before, and while it isn't exactly pretty, it is quite effective. It involves dynamically creating a type at runtime, and using that type. For some documentation, you can see DynamicModels for django.

    Here we go.. your requirements.

    • You want to be able to update a model using a form
    • You want to selectively specify which fields are to be updated at run-time

    So, some code:

    def create_form(model, field_names):
        # the inner class is the only useful bit of your ModelForm
        class Meta:
            pass
        setattr(Meta, 'model', model)
        setattr(Meta, 'include', field_names)
        attrs = {'Meta': Meta}
    
        name = 'DynamicForm'
        baseclasses = (forms.ModelForm,)
        form = type('DynamicForm', baseclasses, attrs)
        return form
    
    def my_awesome_view(request):
        fields = ['start_time', 'end_time']
        form = create_form(Session, fields)
        # work with your form!
    

提交回复
热议问题