Ok, I have been staring at this for hours trying to figure out what\'s going on, to no avail. I am trying to create a ModelForm using the \'instance\' keyword to pass it an exi
Not so much a solution for OP but this was a problem I ran into, specifically when running unit tests on ModelForms, it was a nuisance to keep on having to bind the form then also define an instance with the very same data. I created a small helper function to make things easier which others may find useful — I'm only using this for testing purposes and would be cautious to deploy it anywhere else without significant tweaks (if at all)
def testing_model_form(instance, model_form_class):
"""
A function that creates instances ModelForms useful for testing, basically takes an instance as an argument and will take care
of automatic binding of the form so it can be validated and errors checked
"""
fields = model_form_class.Meta.fields
data_dict = {}
for field in fields:
if hasattr(instance, field):
# The field is present on the model instance
data_dict[field] = getattr(instance, field)
x = model_form_class(data=data_dict)
x.instance = instance
return x