Prepopulate Django (non-Model) Form

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

    You can use model_to_dict() to convert an instance to a dictionary, and then populate a form with that. Something like this should work:

    from django.forms.models import model_to_dict
    ...
    my_obj = MyModel.objects.get(abc=123)
    form = MyForm(initial=model_to_dict(my_obj))
    

    Note: I'm using django version 1.3

提交回复
热议问题