from ares_util.ares import validate_czech_company_id from ares_util.exceptions import InvalidCompanyIDError from crispy_forms import helper from crispy_forms import layout from django import forms from django.core.exceptions import ValidationError from django.forms import fields from django.utils.translation import gettext_lazy as _ from . import models class CreateSubjectForm(forms.Form): error_messages = { 'invalid_cin': _('Your provided CIN is not correct.'), 'already_existing': _('Subject with provided CIN already exists.'), } cin = fields.CharField( label=_('CIN'), max_length=8, help_text=_('Enter the subject CIN, rest will be generated automatically'), ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = helper.FormHelper() self.helper.form_action = 'subjects:create' self.helper.form_method = 'post' self.helper.add_input(layout.Submit('submit', _('Add'))) def clean_cin(self): cin = self.cleaned_data.get('cin') try: validate_czech_company_id(cin) except InvalidCompanyIDError: raise ValidationError(self.error_messages['invalid_cin']) try: models.Subject.objects.get(id=cin) except models.Subject.DoesNotExist: return cin raise ValidationError(self.error_messages['already_existing'])