M
M
maxclax2014-12-24 19:03:02
Django
maxclax, 2014-12-24 19:03:02

How to implement dynamic model field validation in Django?

In the model I have fields:

# платежная система, на которую персона запросила вывод средств
eps = models.ForeignKey(EPS, verbose_name='Куда')

# номер счета, на который персона запросила вывод
account = models.CharField(verbose_name="На счет", max_length=50,
                               validators=[RegexValidator(eps.account_PCRE, message=_('Неверный формат счета'))]
    )

The eps model has the account_PCRE field, which contains a regular expression for checking the account.
When I try above, I get an error:
validators=[RegexValidator(eps.account_PCRE, message=_('Неверный формат счета'))]
AttributeError: 'ForeignKey' object has no attribute 'account_PCRE'

I need to dynamically, depending on the received eps, substitute a regular expression from it to check account.
The form itself looks like this:
class WithdrawalsForm(forms.ModelForm):
    class Meta:
        model = Withdrawals
        fields = ['eps', 'account']
        widgets = {
            'account': forms.TextInput(attrs={'class': 'inputboxsmall', 'data-inputmask': ''})
        }

I do not understand how to get the correct result? It may be necessary to do the check in the form itself, but this will duplicate the code in other forms. It can take out in the view, there will be dubbing of the code. Tell me what are the options.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Rostislav Grigoriev, 2014-12-24
@maxclax

You can raise the desired ValidationError in the clean method in the model itself:
https://docs.djangoproject.com/en/1.6/ref/models/i...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question