Django ModelForm fails validation with no errors

前端 未结 4 615
不知归路
不知归路 2021-02-14 02:37

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

4条回答
  •  甜味超标
    2021-02-14 02:45

    If u still want to validate the object that was in the database, you can serialize it first and then create the Form with it.

    from django.utils import simplejson
    from django.core.serializers import serialize
    
    (...)
    
    fields_dict = simplejson.loads(serialize('json', [obj]))[0]['fields']
    form = forms.MyForm(fields_dict)
    if form.is_valid
    

    This is probably not the best way to do it but the only one that I have found to get a bound form from a model. I need it because I want to validate the current data in the database. I create a question since I don't think this is the best way of doing it:

    Transform an unbound form to a bound one?

提交回复
热议问题