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 from accounts.models import User 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']) class SelectSubjectForm(forms.ModelForm): class Meta: model = User fields = ('supplier',) labels = {'supplier': _('Current supplier')} def __init__(self, *args, **kwargs): self._user = kwargs.pop('current_user', None) super().__init__(*args, **kwargs) self.fields["supplier"].queryset = models.Subject.objects.exclude( id__in=self._user.get_customers(), ) self.helper = helper.FormHelper() self.helper.form_action = 'subjects:list' self.helper.form_method = 'post' self.helper.add_input(layout.Submit('submit', _('Save')))