[Django]-Initial form data from model – Django

7👍

The initial data needs to be a dict (or at least have a dict-like interface, which a Django model does not have).

You can construct a dict from your model using django.forms.models.model_to_dict:

from django.forms.models import model_to_dict
b_as_dict = model_to_dict(b)

This is the same function Django’s built in ModelForm class uses to set its initial data, and while you’ve specified that you don’t want to use a ModelForm it may be more convenient to find some way of structuring your code that allows you to do so.

7👍

There is a more direct way of using model data than dict. See sample in documentation.

b = get_object_or_404(Business, user=request.user)
form = f(instance = b)
👤LuoTao

Leave a comment