2

I am able to set the minimum value validator on the model:

class MyModel(Model):
    my_field = models.fields.IntegerField(default=250, validators=[MinValueValidator(30)])

Then I create a form using the previous model:

class MyForm(ModelForm):
    class Meta:
        model = MyModel
        fields = ('my_field',)

The form gets validated, the correct error message is displayed (when entered value is <30), but even when entered wrong value, it gets saved on the instance!

I was able to make it work by specifying (again) the min value on the form:

class MyForm(ModelForm):
    my_field = form.IntegerField(min_value=30)

    class Meta:
        model = MyModel
        fields = ('my_field',)

But this way the code is not dry - I need to specify the value and field type twice.

Is there any way I could avoid this? Or at least get the min_value from the model validator?

2 Answers 2

1

Validators don't have anything to do with saving the model - other than the fact they should be checked before saving.

docs

Note that validators will not be run automatically when you save a model, but if you are using a ModelForm, it will run your validators on any fields that are included in your form.

Either ensure that you are strict with how you allow objects to be created or you may need to override save or provide a pre_save signal

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for your answer. How come the "form_invalid" gets fired then, stating that "something's wrong", but the instance gets saved anyways?
@Julius - Thats nothing to do with validators, its most likely a bug in your own code, form_invalid doesn't call save
@Julius - Random stab in the dark but I'm guessing that your form_invalid is calling super.form_valid
No, it's not - checked that already :) I think I found the problem... My instance is referred from the Site, that is, my get_form looks like this: return form_class(instance=get_current_site(self.request).configuration, **self.get_form_kwargs()) Now I believe that changed values are set and stay until I restart the server. Is there a way to reset the form?
@Julius - That would be a different question for which you should raise a new question for it if needed
0

I think all the problem you have is this .fields you added, and you didn't call models.Model properly. Every other thing seem to be in order. my_field = models**.fields**.IntegerField(default=250, validators=[MinValueValidator(30)])

Try this:

class MyModel(models.Model):
    my_field = models.IntegerField(default = '250', validators = MinValueValidator(30)])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.