0

Suppose I have a ModelForm for my Model with custom validation logic, and I want to reuse that to validate an existing model instance. Is there any way to do this?

I thought I could just do something like MyModelForm(instance=foo).is_valid(), but that doesn't work for multiple reasons.

I'd like to reuse the existing form validation to avoid duplication of code, but I can't find any way to do so.

Edit: I'm using Django 1.10, in case that makes a difference.

Antimony
  • 37,781
  • 10
  • 100
  • 107
  • 2
    Could you move the custom validation to the model’s clean method? Then you can call `instance.full_clean()` to validate a model instance, and any model forms for the model will also call the `clean` method as part of the form validation. – Alasdair Apr 05 '18 at 22:32
  • Are you sure that's what the book recommends? They must be doing something different in order to make it work, so it would be interesting to see what code they suggest. – Antimony Apr 06 '18 at 00:23
  • @PauloAlmeida Because the first argument is expected to be a dictionary. If you try passing in an instance, you'll get an attribute error inside `value_from_datadict`. – Antimony Apr 06 '18 at 16:43
  • @Paulo Maybe you're using a different version of Django. I'm using 1.10.8. – Antimony Apr 06 '18 at 17:36
  • @Antimony I deleted my previous comments because they were mostly noise. Turns out the form only gets instantiated with `valid=True` (with bogus data) in Pycharm, for reasons I don't understand. If you consider going with the dictionary, [this answer](https://stackoverflow.com/a/29088221/1081569) may be useful, particulary the `model_to_dict` function. – Paulo Almeida Apr 06 '18 at 20:19
  • I ended up just moving my validation code into the model, and then calling it where appropriate (ModelForm calls it implicitly) – Antimony Apr 06 '18 at 22:16

0 Answers0