Prepopulate Django (non-Model) Form

后端 未结 4 2046
生来不讨喜
生来不讨喜 2020-12-12 14:59

I\'m trying to prepopulate the data in my django form based on some information, but NOT using ModelForm, so I can\'t just set the instance.

This seems like it shoul

4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-12 15:21

    For what it's worth, the FormView class-based view way to do this would be to override the FormView's get_initial function. get_initial returns the initial keyword arguments used by get_form_kwargs to instantiate the form.

    Docs:

    • for get_initial, here,
    • for get_form_kwargs, here.

    Sample code:

    from django.views.generic.edit import FormView
    
    class MyFormView(FormView):
    
        def get_initial(self):
            initial = super(MyFormView, self).get_initial()
            # update initial field defaults with custom set default values:
            initial.update({'charfield1': 'foo', 'charfield2': 'bar'})
            return initial
    

提交回复
热议问题