Prepopulate Django (non-Model) Form

后端 未结 4 2072
生来不讨喜
生来不讨喜 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:42

    There are two ways of populating a Django form.

    The first is to pass a dictionary as the first argument when you instantiate it (or pass it as the data kwarg, which is the same thing). This is what you do when you want to use POST data to populate and validate the form.

    data_dict = {'charfield1': 'data1', 'charfield2': 'data2', 'choicefield': 3}
    form = MyForm(data_dict)
    

    However, this will trigger validation on the form, so only works if you are actually passing in valid and complete data to begin with - otherwise you will start off with errors.

    The other way to populate a form is to use the initial parameter (documented here). This gives initial values for the form fields, but does not trigger validation. It's therefore suitable if you're not filling in all values, for example.

    form = MyForm(initial=data_dict)
    

    To populate a choicefield via initial, use the pk value.

提交回复
热议问题