Skip to content
Advertisement

How to use a custom validation method taking request parameters

I have a really simple form on which I’m doing some validation:

JavaScript

But I need to add another validation (which is based on the user making the request).

I tried to add the parameter to the clean method:

JavaScript

Unfortunately, I cannot call the is_valid() in the view with a parameter:

JavaScript

I get the following error message:

is_valid() takes 1 positional argument but 2 were given

I also tried to add a new method to the form:

JavaScript

and call it from the view:

JavaScript

In that case, the exception really gets thrown and crashes the application.

My goals are:

  • to make the validation dependant on a criteria in the request
  • to display an error message normally when the validation fails

What would be the correct way to implement the custom validation ?

Advertisement

Answer

I would create a simple mixin class

JavaScript

and then use the FormContextMixin class with your form class as

JavaScript

Thus, you can initialize the form with any arbitrary data as

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement