Django ModelForm fails validation with no errors

前端 未结 4 620
不知归路
不知归路 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:53

    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
    

提交回复
热议问题