class GenerateForm(forms.Form): seed = forms.Field(required=False) mode = forms.ChoiceField(required=False, choices=MODES, initial='open') flags = forms.Field(required=False, initial='') debug_mode = forms.BooleanField(required=False, initial=False) race_mode = forms.BooleanField(required=False, initial=False)
class BookingForm(forms.Form): """ BookingForm serve to validate input and create a new booking. doc: https://docs.djangoproject.com/fr/2.2/topics/forms/modelforms/ """ name = forms.CharField( label="", max_length=100, min_length=4, widget=forms.TextInput( attrs={ 'class': 'form-control form-control-lg form-control-a', 'placeholder': 'Nom *' }), required=True) email = forms.EmailField( label='', widget=forms.EmailInput( attrs={ 'class': 'form-control form-control-lg form-control-a', 'placeholder': 'Email *' }), required=True) phone = forms.CharField( label='', max_length=30, min_length=4, widget=forms.TextInput( attrs={ 'class': 'form-control form-control-lg form-control-a', 'placeholder': 'Téléphone *' }), required=True) place = forms.ChoiceField( label='', widget=forms.Select( attrs={'class': 'form-control form-control-lg form-control-a'}), required=True, choices=PlaceNames.choices) message = forms.CharField(label='', min_length=4, widget=forms.Textarea( attrs={ 'class': 'form-control', 'cols': '45', 'rows': '8', 'placeholder': 'Message *' }), required=True) start = forms.DateField( label='', input_formats=['%d/%m/%Y'], widget=forms.DateInput( attrs={ 'class': 'form-control form-control-lg form-control-a', 'placeholder': '01/01/2020 *' }), required=True) end = forms.DateField( label='', input_formats=['%d/%m/%Y'], widget=forms.DateInput( attrs={ 'class': 'form-control form-control-lg form-control-a', 'placeholder': '31/12/2020 *' }), required=True)
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['status'] = forms.ChoiceField(choices=tuple(PACKAGE_STATUSES))
class FixedRateBondsBestBuysForm(BestBuyForm): tax_rate = forms.ChoiceField(choices=ACCOUNT_TYPE_CHOICES, required=False)
class MonthlyIncomeAccountForm(BestBuyForm): tax_rate = forms.ChoiceField(choices=ACCOUNT_TYPE_CHOICES, required=False) pass
class MissionAutomaticStaffingForm(forms.Form): """Form to create automatically staffing for given mission""" duration = forms.ChoiceField(choices=zip(range(1, 13), range(1, 13))) mode = forms.ChoiceField(choices=(("after", _("after current staffing")), ("replace", _("replace current staffing"))))
class SettingsForm(forms.Form): """ Administration settings form """ default_contact_type = forms.ModelChoiceField( label='Default Contact Type', queryset=[]) default_imap_folder = forms.ChoiceField(label='Default IMAP Folder', choices=(('ALL', 'ALL'), ('UNSEEN', _('UNSEEN'))), required=False) signature = forms.CharField(widget=forms.Textarea, required=False) def __init__(self, user, *args, **kwargs): "Sets choices and initial value" super(SettingsForm, self).__init__(*args, **kwargs) self.user = user self.fields['default_contact_type'].label = _('Default Contact Type') self.fields['default_contact_type'].queryset = Object.filter_permitted(user, ContactType.objects, mode='x') try: conf = ModuleSetting.get_for_module('anaf.messaging', 'default_contact_type', user=user)[0] default_contact_type = ContactType.objects.get(pk=long(conf.value)) self.fields[ 'default_contact_type'].initial = default_contact_type.id except: pass self.fields['default_imap_folder'].label = _('Default IMAP Folder') try: conf = ModuleSetting.get_for_module('anaf.messaging', 'default_imap_folder', user=user)[0] self.fields['default_imap_folder'].initial = conf.value except: self.fields[ 'default_imap_folder'].initial = settings.ANAF_MESSAGING_IMAP_DEFAULT_FOLDER_NAME self.fields['signature'].label = _('Signature') try: conf = ModuleSetting.get_for_module('anaf.messaging', 'signature', user=user, strict=True)[0] signature = conf.value self.fields['signature'].initial = signature except: pass def save(self): "Form processor" try: ModuleSetting.set_for_module('default_contact_type', self.cleaned_data[ 'default_contact_type'].id, 'anaf.messaging') except: pass try: ModuleSetting.set_for_module('default_imap_folder', self.cleaned_data[ 'default_imap_folder'], 'anaf.messaging') except: pass try: ModuleSetting.set_for_module('signature', self.cleaned_data['signature'], 'anaf.messaging', user=self.user) except: pass
class XPIForm(happyforms.Form): """ Validates a new XPI. * Checks for duplicate GUID """ platform = forms.ChoiceField( choices=[(p.shortname, p.name) for p in amo.PLATFORMS.values() if p != amo.PLATFORM_ANY], required=False, ) release_notes = forms.CharField(required=False) xpi = forms.FileField(required=True) def __init__(self, request, data, files, addon=None, version=None): self.addon = addon self.request = request if version: self.version = version self.addon = version.addon super(XPIForm, self).__init__(data, files) def clean_platform(self): return self.cleaned_data['platform'] or amo.PLATFORM_ALL.shortname def clean_xpi(self): # TODO(basta): connect to addon validator. xpi = self.cleaned_data['xpi'] self.cleaned_data.update(parse_addon(xpi, self.addon)) return xpi def create_addon(self, license=None): data = self.cleaned_data a = Addon(guid=data['guid'], name=data['name'], type=data['type'], status=amo.STATUS_UNREVIEWED, homepage=data['homepage'], summary=data['summary']) a.save() AddonUser(addon=a, user=self.request.user).save() self.addon = a # Save Version, attach License self.create_version(license=license) amo.log(amo.LOG.CREATE_ADDON, a) log.info('Addon %d saved' % a.id) return a def _save_file(self, version): data = self.cleaned_data xpi = data['xpi'] hash = hashlib.sha256() f = File(version=version, platform=amo.PLATFORM_DICT[data['platform']].id, size=xpi.size) filename = f.generate_filename() path = os.path.join(user_media_path('addons'), str(version.addon.id)) with storage.open(os.path.join(path, filename), 'wb') as destination: for chunk in xpi.chunks(): hash.update(chunk) destination.write(chunk) f.hash = 'sha256:%s' % hash.hexdigest() f.save() return f def _save_apps(self, version): # clear old app versions version.apps.all().delete() apps = self.cleaned_data['apps'] for app in apps: av = ApplicationsVersions.objects.create(version=version, min=app.min, max=app.max, application=app.id) amo.log(amo.LOG.ADD_APPVERSION, version, version.addon, app.appdata.short, av) def create_version(self, license=None): data = self.cleaned_data v = Version(addon=self.addon, license=license, version=data['version'], releasenotes=data['release_notes']) v.save() amo.log(amo.LOG.ADD_VERSION, v.addon, v) self._save_apps(v) self._save_file(v) return v def update_version(self, license=None): data = self.cleaned_data v = self.version v.license = license v.version = data['version'] v.releasenotes = data['release_notes'] v.save() amo.log(amo.LOG.EDIT_VERSION, v.addon, v) self._save_apps(v) self._save_file(v) return v
class SignupForm(forms.Form): username = forms.CharField( label='아이디', widget=forms.TextInput( attrs={ 'class': 'form-control' } ) ) email = forms.EmailField( required=False, label='이메일', widget=forms.TextInput( attrs={ 'class': 'form-control' } ) ) password = forms.CharField( label='비밀번호', widget=forms.PasswordInput( attrs={ 'class': 'form-control' } ) ) password2 = forms.CharField( label='비밀번호확인', widget=forms.PasswordInput( attrs={ 'class': 'form-control' } ) ) image_profile = forms.ImageField( required=False, ) introduction = forms.CharField( required=False, label='자기소개', widget=forms.Textarea( attrs={ 'class': 'form-control' } ) ) gender = forms.ChoiceField( choices=( ('m', '남성'), ('f', '여성'), ('x', '선택안함'), ) ) site = forms.CharField( required=False, label='사이트', widget=forms.TextInput( attrs={ 'class': 'form-control' } ) ) def clean_username(self): username = self.cleaned_data['username'] reputation = User.objects.filter(username=username).exists() if reputation: raise ValidationError('이미 사용중인 아이디입니다.') return username def clean(self): super().clean() password = self.cleaned_data['password'] password2 = self.cleaned_data['password2'] if password != password2: self.add_error('password2', '비밀번호와 비밀번호 확인의 값이 일치하지 않습니다.') return self.cleaned_data def signup(self): fields = [ 'username', 'email', 'password', 'img-profile', 'introduction', 'site', ] # create_user_dict = {key: value for key, value in self.cleaned_data.items() if key in fields} # def check(item): # return item[0] in fields # create_user_dict = {} # create_user_dict = dict(filter(check, self.cleaned_data.items())) create_user_dict = dict(filter(lambda item: item[0] in fields, self.cleaned_data.items())) print(create_user_dict) user = User.objects.create_user(**create_user_dict) return user
class AddContactForm(forms.Form): def __init__(self,*args,**kwargs): stage_form = kwargs.pop('stage_form',False) super (AddContactForm,self).__init__(*args,**kwargs) if stage_form: self.fields['stage'].required=False, self.fields['stage'].widget = forms.HiddenInput() title = forms.CharField( max_length = 20, required=False, label='Title' ) first_name = forms.CharField( max_length = 120, label='First Name' ) last_name = forms.CharField( max_length = 120, label = 'Last Name' ) spouse_name = forms.CharField( max_length = 120, required=False, label='Spouse\'s name' ) phone_number = USPhoneNumberField( label="Phone Number", required=False, ) email_address = forms.EmailField( required=False, label = 'Email Address' ) street_address = forms.CharField( max_length=200, required=False, label = 'Street Address', ) city = forms.CharField( max_length=100, required=False, label = 'City' ) state = forms.ChoiceField( choices=STATE_CHOICES, required=False, label='State' ) zip = forms.RegexField( required=False, regex='^\d{5}(?:[-\s]\d{4})?$', error_messages = {'invalid': 'Please enter a valid zip code (5 digit zip or zip+4 accepted).'}, label='ZIP Code' ) stage = forms.ChoiceField( choices=STAGE_OPTIONS, required=True, label = 'What to do next with this person:' )
class AddReferralForm(forms.Form): def clean(self): cleaned_data = super(AddReferralForm,self).clean() cleaned_data['stage_data'] = {} cleaned_data['stage_data']['new_stage'] = cleaned_data['stage'] title = cleaned_data('title') first_name = cleaned_data('first_name') last_name = cleaned_data('last_name') spouse_name = cleaned_data('spouse_name') phone_number = cleaned_data('phone_number') email_address = cleaned_data('email_address') street_address = cleaned_data('street_address') city = cleaned_data('city') state = cleaned_data('state') zip = cleaned_data('zip') note = cleaned_data('note') stage = cleaned_data('stage') if not first_name and not last_name and not stage: raise forms.ValidationError("Incomplete form") return cleaned_data def __init__(self,*args,**kwargs): self.user = kwargs.pop('user',User) self.contact = kwargs.pop('contact',False) super (AddReferralForm,self).__init__(*args,**kwargs) self.fields['stage'] = forms.TypedChoiceField( choices=STAGE_OPTIONS, required=True, label = 'What\'s next?', ) self.fields['stage'].widget.attrs = {'class':'refStageSelect'} title = forms.CharField( max_length = 20, required=False, label='Title' ) first_name = forms.CharField( max_length = 120, required=False, label='First Name' ) last_name = forms.CharField( max_length = 120, required=False, label = 'Last Name' ) spouse_name = forms.CharField( max_length = 120, required=False, label='Spouse\'s name' ) phone_number = USPhoneNumberField( label="Phone Number", required=False, ) email_address = forms.EmailField( required=False, label = 'Email Address' ) street_address = forms.CharField( max_length=200, required=False, label = 'Street Address', ) city = forms.CharField( max_length=100, required=False, label = 'City' ) state = forms.ChoiceField( choices=STATE_CHOICES, required=False, label='State' ) zip = forms.RegexField( required=False, regex='^\d{5}(?:[-\s]\d{4})?$', error_messages = {'invalid': 'Please enter a valid zip code (5 digit zip or zip+4 accepted).'}, label='ZIP Code' ) note = forms.CharField( max_length=500, required=False, )
class ArticleForm(forms.Form): title = forms.CharField(max_length=200, required=True, label='Title') author = forms.CharField(max_length=40, required=True, label='Author') text = forms.CharField(max_length=3000, required=True, label='Text', widget=widgets.Textarea) cotegory = forms.ChoiceField(choices=CATEGORY_CHOICES, required=False, label='Category')
class SignupForm(forms.Form): username = forms.CharField(max_length=30, label=_("User Name*"), help_text="Your desired user name or handle.") first_name = forms.CharField(max_length=100, label=_("First Name*")) last_name = forms.CharField(max_length=100, label=_("Last Name*")) nickname = forms.CharField(max_length=100, required=False) mobile_phone_number = PhoneNumberField(required=False, label=_("Mobile Phone Number")) email = forms.EmailField(max_length=75, required=False) sex = forms.ChoiceField(choices=SEX_CHOICES, required=False, help_text="Enter sex, not gender identity.") birth_date = forms.DateField(label='Birth Date', widget=forms.SelectDateWidget(years=YEARS), required=False) password1 = forms.CharField(widget=forms.PasswordInput, max_length=128, label=_("Password")) password2 = forms.CharField(widget=forms.PasswordInput, max_length=128, label=_("Password (again)")) agree_tos = forms.BooleanField(label=_(agree_tos_label)) required_css_class = 'required' def clean_first_name(self): return self.cleaned_data.get("first_name", "").strip().upper() def clean_last_name(self): return self.cleaned_data.get("last_name", "").strip().upper() def clean_nickname(self): return self.cleaned_data.get("nickname", "").strip().upper() def clean_password2(self): password1 = self.cleaned_data.get("password1", "") password2 = self.cleaned_data["password2"] if password1 != password2: raise forms.ValidationError( _("The two password fields didn't match.")) try: validate_password(password1) except ValidationError as err: raise forms.ValidationError(err.error_list[0]) return password2 def clean_email(self): email = self.cleaned_data.get('email', "").strip().lower() if email: username = self.cleaned_data.get('username') if email and User.objects.filter(email=email).exclude( username=username).count(): raise forms.ValidationError( _('This email address is already registered.')) return email else: return email def clean_username(self): username = self.cleaned_data.get('username').strip().lower() if User.objects.filter(username=username).count() > 0: raise forms.ValidationError(_('This username is already taken.')) return username def clean_four_digit_suffix(self): four_digit_suffix = self.cleaned_data.get('four_digit_suffix') if four_digit_suffix: if not RepresentsPositiveInt(four_digit_suffix, length=4): raise forms.ValidationError( _('Your for digit suffix must be exactly 4 digits')) return four_digit_suffix def save(self): new_user = User.objects.create_user( username=self.cleaned_data['username'], first_name=self.cleaned_data['first_name'], last_name=self.cleaned_data['last_name'], password=self.cleaned_data['password1'], email=self.cleaned_data['email'], is_active=True) UserProfile.objects.create( user=new_user, mobile_phone_number=self.cleaned_data['mobile_phone_number'], nickname=self.cleaned_data.get('nickname', ""), sex=self.cleaned_data.get('sex', ""), birth_date=self.cleaned_data.get('birth_date', ""), agree_tos=settings.CURRENT_TOS_VERSION, agree_privacy_policy=settings.CURRENT_PP_VERSION) # Send a verification email create_activation_key(new_user) return new_user
class ReservationForm(forms.Form): hotel = forms.CharField(widget=forms.TextInput(attrs={'readonly': 'readonly'})) check_in = forms.DateField(initial=datetime.date.today, required=True) t_check_out = datetime.datetime.now()+timedelta(days=1) check_out = forms.DateField(initial=t_check_out, required=True) room_choice = forms.ChoiceField(required=True, choices=Room.ROOM_TYPE_CHOICES) discount = forms.CharField(required=False, widget=forms.TextInput(attrs={'readonly': 'readonly'})) service = EmptyMultipleChoiceField(widget=forms.CheckboxSelectMultiple()) #, initial=get_services()) breakfast = EmptyChoiceField() breakfast_number_orders = forms.IntegerField(required=False, min_value=0, max_value=8) # should be capaicity? credit_card_number = forms.CharField(required=True, max_length=20) # c_card_date = forms.DateField(required=True) MONTH_CHOICES = ( ("1", "Jan"), ("2", "Feb"), ("3", "Mar"), ("4", "Apr"), ("5", "May"), ("6", "Jun"), ("7", "Jul"), ("8", "Aug"), ("9", "Sep"), ("10", "Oct"), ("11", "Nov"), ("12", "Dec") ) YEAR_CHOICES = ( ("2020", "2020"), ("2021", "2021"), ("2022", "2022"), ("2023", "2023"), ("2024", "2024"), ("2025", "2025"), ) credit_card_month = forms.ChoiceField(required=True, choices=MONTH_CHOICES) credit_card_year = forms.ChoiceField(required=True, choices=YEAR_CHOICES, initial=("2021", "2021")) credit_card_name = forms.CharField(required=True, max_length=20) credit_card_type = forms.ChoiceField(required=True, choices=CreditCard.CC_CHOICES) credit_card_code = forms.CharField(required=True, max_length=4) credit_card_address = forms.CharField(required=True, max_length=40) def __init__(self, *args, **kwargs): super(ReservationForm, self).__init__(*args, **kwargs) for field in iter(self.fields): self.fields[field].widget.attrs.update({ 'class': 'form-control' }) @staticmethod def get_services(hotel: Hotel) -> Dict: rv = {} #h = Hotel.objects.get(pk=self.initial['hotel'].pk) s = hotel.service_set.all() for i in s: rv[i.sid] = i.s_type return [(k, v) for k, v in rv.items()] @staticmethod def get_breakfast(hotel: Hotel) -> Dict: rv = {} #h = Hotel.objects.get(pk=self.initial['hotel'].pk) s = hotel.breakfast_set.all() for i in s: rv[i.bid] = i.b_type return [(k, v) for k, v in rv.items()] @staticmethod def get_rooms(hotel: Hotel) -> Dict: rv = {} s = hotel.room_set.all() for i in s: rv[i.room_id] = f'{i.room_type} - room number: {i.room_no} - floor: {i.floor}' return [(k, v) for k, v in rv.items()] @staticmethod def get_discounts(room_key: int, check_in: fields.DateField, check_out: fields.DateField) -> str: rv = '' room = Room.objects.get(pk = room_key) d = room.discountedroom_set.all() t = d.filter(start_date__range=(check_in.initial(), check_out.initial.date())) for i in t: rv += f' {i.discount}' return rv
class ProdutoForm(forms.ModelForm): custo = forms.DecimalField( max_digits=16, decimal_places=2, localize=True, widget=forms.TextInput(attrs={ 'class': 'form-control decimal-mask', 'placeholder': 'R$ 0,00' }), initial=Decimal('0.00'), label='成本', required=False) venda = forms.DecimalField( max_digits=16, decimal_places=2, localize=True, widget=forms.TextInput(attrs={ 'class': 'form-control decimal-mask', 'placeholder': 'R$ 0,00' }), initial=Decimal('0.00'), label='售价', required=False) # Estoque estoque_inicial = forms.DecimalField( max_digits=16, decimal_places=2, localize=True, widget=forms.TextInput(attrs={'class': 'form-control decimal-mask'}), label='Qtd初始存货量', initial=Decimal('0.00'), required=False) fornecedor = forms.ChoiceField( choices=[(None, '----------')], widget=forms.Select(attrs={'class': 'form-control'}), label='Fornecedor', required=False) local_dest = forms.ModelChoiceField( queryset=LocalEstoque.objects.all(), widget=forms.Select(attrs={'class': 'form-control'}), empty_label=None, label='Localização do estoque de destino', required=False) def __init__(self, *args, **kwargs): super(ProdutoForm, self).__init__(*args, **kwargs) self.fields['estoque_minimo'].localize = True self.fields['fornecedor'].choices = list( self.fields['fornecedor'].choices) + [ (fornecedor.id, fornecedor) for fornecedor in Fornecedor.objects.all() ] class Meta: model = Produto fields = ( 'codigo', 'codigo_barras', 'descricao', 'categoria', 'marca', 'unidade', 'ncm', 'venda', 'custo', 'inf_adicionais', 'origem', 'cest', 'cfop_padrao', 'grupo_fiscal', 'estoque_minimo', 'controlar_estoque', ) widgets = { 'codigo': forms.TextInput(attrs={'class': 'form-control'}), 'codigo_barras': forms.TextInput(attrs={'class': 'form-control'}), 'descricao': forms.TextInput(attrs={'class': 'form-control'}), 'categoria': forms.Select(attrs={'class': 'form-control'}), 'marca': forms.Select(attrs={'class': 'form-control'}), 'unidade': forms.Select(attrs={'class': 'form-control'}), 'ncm': forms.TextInput(attrs={'class': 'form-control'}), 'inf_adicionais': forms.Textarea(attrs={'class': 'form-control'}), 'origem': forms.Select(attrs={'class': 'form-control'}), 'cest': forms.TextInput(attrs={'class': 'form-control'}), 'cfop_padrao': forms.Select(attrs={'class': 'form-control'}), 'grupo_fiscal': forms.Select(attrs={'class': 'form-control'}), 'estoque_minimo': forms.TextInput(attrs={'class': 'form-control decimal-mask'}), 'controlar_estoque': forms.CheckboxInput(attrs={'class': 'form-control'}), } labels = { 'codigo': _('代码'), 'codigo_barras': _('条码(GTIN/EAN)'), 'descricao': _('说明'), 'categoria': _('分类'), 'marca': _('品牌'), 'unidade': _('单位'), 'ncm': _('NCM'), 'inf_adicionais': _('备注'), 'origem': _('产地'), 'cest': _('CEST'), 'cfop_padrao': _('CFOP(标准)'), 'grupo_fiscal': _('税务组(模式)'), 'estoque_minimo': _('Qtd最低限度'), 'controlar_estoque': _('是否控制这个产品的库存?'), }
class GeneralParametersForm(param_forms.AdminParametersForm): """General parameters.""" app = "core" sep1 = SeparatorField(label=ugettext_lazy("Authentication")) authentication_type = forms.ChoiceField( label=ugettext_lazy("Authentication type"), choices=[('local', ugettext_lazy("Local")), ('ldap', "LDAP")], initial="local", help_text=ugettext_lazy("The backend used for authentication"), widget=HorizontalRadioSelect() ) password_scheme = forms.ChoiceField( label=ugettext_lazy("Default password scheme"), choices=[("sha512crypt", "sha512crypt"), ("sha256crypt", "sha256crypt"), ("blfcrypt", "bcrypt"), ("md5crypt", ugettext_lazy("md5crypt (weak)")), ("sha256", ugettext_lazy("sha256 (weak)")), ("md5", ugettext_lazy("md5 (weak)")), ("crypt", ugettext_lazy("crypt (weak)")), ("plain", ugettext_lazy("plain (weak)"))], initial="sha512crypt", help_text=ugettext_lazy("Scheme used to crypt mailbox passwords"), widget=forms.Select(attrs={"class": "form-control"}) ) rounds_number = forms.IntegerField( label=ugettext_lazy("Rounds"), initial=70000, help_text=ugettext_lazy( "Number of rounds to use (only used by sha256crypt and " "sha512crypt). Must be between 1000 and 999999999, inclusive." ), widget=forms.TextInput(attrs={"class": "form-control"}) ) secret_key = forms.CharField( label=ugettext_lazy("Secret key"), initial=random_key(), help_text=ugettext_lazy("Key used to encrypt/decrypt passwords"), widget=forms.TextInput(attrs={"class": "form-control"}) ) default_password = forms.CharField( label=ugettext_lazy("Default password"), initial="password", help_text=ugettext_lazy( "Default password for automatically created accounts.") ) random_password_length = forms.IntegerField( label=ugettext_lazy("Random password length"), min_value=8, initial=8, help_text=ugettext_lazy( "Length of randomly generated passwords.") ) # LDAP specific settings ldap_sep = SeparatorField(label=ugettext_lazy("LDAP settings")) ldap_server_address = forms.CharField( label=ugettext_lazy("Server address"), initial="localhost", help_text=ugettext_lazy( "The IP address or the DNS name of the LDAP server"), widget=forms.TextInput(attrs={"class": "form-control"}) ) ldap_server_port = forms.IntegerField( label=ugettext_lazy("Server port"), initial=389, help_text=ugettext_lazy("The TCP port number used by the LDAP server"), widget=forms.TextInput(attrs={"class": "form-control"}) ) ldap_secured = forms.ChoiceField( label=ugettext_lazy("Use a secured connection"), choices=constants.LDAP_SECURE_MODES, initial="none", help_text=ugettext_lazy( "Use an SSL/STARTTLS connection to access the LDAP server") ) ldap_auth_method = forms.ChoiceField( label=ugettext_lazy("Authentication method"), choices=[('searchbind', ugettext_lazy("Search and bind")), ('directbind', ugettext_lazy("Direct bind"))], initial='searchbind', help_text=ugettext_lazy("Choose the authentication method to use"), widget=forms.Select(attrs={"class": "form-control"}) ) ldap_bind_dn = forms.CharField( label=ugettext_lazy("Bind DN"), initial='', help_text=ugettext_lazy( "The distinguished name to use when binding to the LDAP server. " "Leave empty for an anonymous bind" ), required=False, widget=forms.TextInput(attrs={"class": "form-control"}) ) ldap_bind_password = forms.CharField( label=ugettext_lazy("Bind password"), initial='', help_text=ugettext_lazy( "The password to use when binding to the LDAP server " "(with 'Bind DN')" ), widget=forms.PasswordInput( attrs={"class": "form-control"}, render_value=True), required=False ) ldap_search_base = forms.CharField( label=ugettext_lazy("Users search base"), initial="", help_text=ugettext_lazy( "The distinguished name of the search base used to find users" ), required=False, widget=forms.TextInput(attrs={"class": "form-control"}) ) ldap_search_filter = forms.CharField( label=ugettext_lazy("Search filter"), initial="(mail=%(user)s)", help_text=ugettext_lazy( "An optional filter string (e.g. '(objectClass=person)'). " "In order to be valid, it must be enclosed in parentheses." ), required=False, widget=forms.TextInput(attrs={"class": "form-control"}) ) ldap_user_dn_template = forms.CharField( label=ugettext_lazy("User DN template"), initial="", help_text=ugettext_lazy( "The template used to construct a user's DN. It should contain " "one placeholder (ie. %(user)s)" ), required=False, widget=forms.TextInput(attrs={"class": "form-control"}) ) ldap_password_attribute = forms.CharField( label=ugettext_lazy("Password attribute"), initial="userPassword", help_text=ugettext_lazy("The attribute used to store user passwords"), widget=forms.TextInput(attrs={"class": "form-control"}) ) ldap_is_active_directory = YesNoField( label=ugettext_lazy("Active Directory"), initial=False, help_text=ugettext_lazy( "Tell if the LDAP server is an Active Directory one") ) ldap_admin_groups = forms.CharField( label=ugettext_lazy("Administrator groups"), initial="", help_text=ugettext_lazy( "Members of those LDAP Posix groups will be created as domain " "administrators. Use ';' characters to separate groups." ), required=False ) ldap_group_type = forms.ChoiceField( label=ugettext_lazy("Group type"), initial="posixgroup", choices=constants.LDAP_GROUP_TYPES, help_text=ugettext_lazy( "The LDAP group type to use with your directory." ) ) ldap_groups_search_base = forms.CharField( label=ugettext_lazy("Groups search base"), initial="", help_text=ugettext_lazy( "The distinguished name of the search base used to find groups" ), required=False ) dash_sep = SeparatorField(label=ugettext_lazy("Dashboard")) rss_feed_url = forms.URLField( label=ugettext_lazy("Custom RSS feed"), required=False, help_text=ugettext_lazy( "Display custom RSS feed to resellers and domain administrators" ) ) hide_features_widget = YesNoField( label=ugettext_lazy("Hide features widget"), initial=False, help_text=ugettext_lazy( "Hide features widget for resellers and domain administrators" ) ) notif_sep = SeparatorField(label=ugettext_lazy("Notifications")) sender_address = lib_fields.UTF8EmailField( label=_("Sender address"), initial="*****@*****.**", help_text=_( "Email address used to send notifications." ) ) api_sep = SeparatorField(label=ugettext_lazy("Public API")) enable_api_communication = YesNoField( label=ugettext_lazy("Enable communication"), initial=True, help_text=ugettext_lazy( "Enable communication with Modoboa public API") ) check_new_versions = YesNoField( label=ugettext_lazy("Check new versions"), initial=True, help_text=ugettext_lazy( "Automatically checks if a newer version is available") ) send_statistics = YesNoField( label=ugettext_lazy("Send statistics"), initial=True, help_text=ugettext_lazy( "Send statistics to Modoboa public API " "(counters and used extensions)") ) sep3 = SeparatorField(label=ugettext_lazy("Miscellaneous")) inactive_account_threshold = forms.IntegerField( label=_("Inactive account threshold"), initial=30, help_text=_( "An account with a last login date greater than this threshold " "(in days) will be considered as inactive" ), widget=forms.TextInput(attrs={"class": "form-control"}) ) top_notifications_check_interval = forms.IntegerField( label=_("Top notifications check interval"), initial=30, help_text=_( "Interval between two top notification checks (in seconds)" ), widget=forms.TextInput(attrs={"class": "form-control"}) ) log_maximum_age = forms.IntegerField( label=ugettext_lazy("Maximum log record age"), initial=365, help_text=ugettext_lazy("The maximum age in days of a log record"), widget=forms.TextInput(attrs={"class": "form-control"}) ) items_per_page = forms.IntegerField( label=ugettext_lazy("Items per page"), initial=30, help_text=ugettext_lazy("Number of displayed items per page"), widget=forms.TextInput(attrs={"class": "form-control"}) ) default_top_redirection = forms.ChoiceField( label=ugettext_lazy("Default top redirection"), choices=[], initial="user", help_text=ugettext_lazy( "The default redirection used when no application is specified" ), widget=forms.Select(attrs={"class": "form-control"}) ) # Visibility rules visibility_rules = { "ldap_sep": "authentication_type=ldap", "ldap_server_address": "authentication_type=ldap", "ldap_server_port": "authentication_type=ldap", "ldap_secured": "authentication_type=ldap", "ldap_auth_method": "authentication_type=ldap", "ldap_bind_dn": "ldap_auth_method=searchbind", "ldap_bind_password": "******", "ldap_search_base": "ldap_auth_method=searchbind", "ldap_search_filter": "ldap_auth_method=searchbind", "ldap_user_dn_template": "ldap_auth_method=directbind", "ldap_password_attribute": "authentication_type=ldap", "ldap_is_active_directory": "authentication_type=ldap", "ldap_admin_groups": "authentication_type=ldap", "ldap_group_type": "authentication_type=ldap", "ldap_groups_search_base": "authentication_type=ldap", "check_new_versions": "enable_api_communication=True", "send_statistics": "enable_api_communication=True", } def __init__(self, *args, **kwargs): super(GeneralParametersForm, self).__init__(*args, **kwargs) self.fields["default_top_redirection"].choices = enabled_applications() def clean_secret_key(self): if len(self.cleaned_data["secret_key"]) not in [16, 24, 32]: raise forms.ValidationError( _("Key must be either 16, 24, or 32 bytes long") ) return self.cleaned_data["secret_key"] def clean_ldap_user_dn_template(self): tpl = self.cleaned_data["ldap_user_dn_template"] try: test = tpl % {"user": "******"} except (KeyError, ValueError): raise forms.ValidationError(_("Invalid syntax")) return tpl def clean_rounds_number(self): value = self.cleaned_data["rounds_number"] if value < 1000 or value > 999999999: raise forms.ValidationError(_("Invalid rounds number")) return value def clean_default_password(self): """Check password complexity.""" value = self.cleaned_data["default_password"] password_validation.validate_password(value) return value def clean(self): """Custom validation method Depending on 'ldap_auth_method' value, we check for different required parameters. """ super(GeneralParametersForm, self).clean() cleaned_data = self.cleaned_data if cleaned_data["authentication_type"] != "ldap": return cleaned_data if cleaned_data["ldap_auth_method"] == "searchbind": required_fields = ["ldap_search_base", "ldap_search_filter"] else: required_fields = ["ldap_user_dn_template"] for f in required_fields: if f not in cleaned_data or cleaned_data[f] == u'': self.add_error(f, _("This field is required")) return cleaned_data def to_django_settings(self): """Apply LDAP related parameters to Django settings. Doing so, we can use the django_auth_ldap module. """ try: import ldap from django_auth_ldap.config import ( LDAPSearch, PosixGroupType, GroupOfNamesType) ldap_available = True except ImportError: ldap_available = False values = dict(param_tools.get_global_parameters("core")) if not ldap_available or values["authentication_type"] != "ldap": return if not hasattr(settings, "AUTH_LDAP_USER_ATTR_MAP"): setattr(settings, "AUTH_LDAP_USER_ATTR_MAP", { "first_name": "givenName", "email": "mail", "last_name": "sn" }) ldap_uri = "ldaps://" if values["ldap_secured"] == "ssl" else "ldap://" ldap_uri += "%s:%s" % ( values["ldap_server_address"], values["ldap_server_port"]) setattr(settings, "AUTH_LDAP_SERVER_URI", ldap_uri) if values["ldap_secured"] == "starttls": setattr(settings, "AUTH_LDAP_START_TLS", True) if values["ldap_group_type"] == "groupofnames": setattr(settings, "AUTH_LDAP_GROUP_TYPE", GroupOfNamesType()) searchfilter = "(objectClass=groupOfNames)" else: setattr(settings, "AUTH_LDAP_GROUP_TYPE", PosixGroupType()) searchfilter = "(objectClass=posixGroup)" setattr(settings, "AUTH_LDAP_GROUP_SEARCH", LDAPSearch( values["ldap_groups_search_base"], ldap.SCOPE_SUBTREE, searchfilter )) if values["ldap_auth_method"] == "searchbind": setattr(settings, "AUTH_LDAP_BIND_DN", values["ldap_bind_dn"]) setattr( settings, "AUTH_LDAP_BIND_PASSWORD", values["ldap_bind_password"] ) search = LDAPSearch( values["ldap_search_base"], ldap.SCOPE_SUBTREE, values["ldap_search_filter"] ) setattr(settings, "AUTH_LDAP_USER_SEARCH", search) else: setattr( settings, "AUTH_LDAP_USER_DN_TEMPLATE", values["ldap_user_dn_template"] ) if values["ldap_is_active_directory"]: if not hasattr(settings, "AUTH_LDAP_GLOBAL_OPTIONS"): setattr(settings, "AUTH_LDAP_GLOBAL_OPTIONS", { ldap.OPT_REFERRALS: False }) else: settings.AUTH_LDAP_GLOBAL_OPTIONS[ldap.OPT_REFERRALS] = False
class PaymentMethodsForm(forms.Form): method = forms.ChoiceField(label=pgettext_lazy( 'Payment methods form label', 'Method'), choices=settings.CHECKOUT_PAYMENT_CHOICES, widget=forms.RadioSelect, initial=settings.CHECKOUT_PAYMENT_CHOICES[0][0])
def __init__(self, *args, **kwargs): super(ConfirmRequestForm, self).__init__(*args, **kwargs) self.fields['verified'] = forms.ChoiceField(label=u'', choices=SELECT_CHOICES, widget=forms.Select(), required=True)
class AddToBasketForm(BaseForm): def __init__(self, *args, **kwargs): request = kwargs.pop('request') product = kwargs.pop('product') prefix = kwargs.pop('prefix', None) with_varieties = kwargs.pop('with_varieties', True) self._price_calculation = kwargs.pop('price_calculation', False) super(AddToBasketForm, self).__init__(*args, **kwargs) self._configure_for_product(request, product, prefix, with_varieties) quantity = forms.ChoiceField(required=True, initial=1, widget=forms.Select(attrs={'class': 'input-mini'})) product_id = forms.IntegerField(required=True, widget=forms.HiddenInput()) prefix = forms.CharField(required=False, max_length=32, widget=forms.HiddenInput()) @property def can_be_added_to_basket(self): """ Return True, if this product can be added to the basket. """ return self._product.can_be_added_to_basket(self._request) @property def fieldnames(self): """ Return list of all form fields, excluding hidden fields but including varieties text label fields. """ fields = [] for field in self.fields: if field in ['quantity', 'product_id', 'prefix']: continue fields.append(field) return ','.join(fields) @property def product_price(self): """ Return the initial product price based on the initial state of this form. """ if self._has_skus and self._combination and self._combination.get('sku') and self._combination.get('sku').price: # SKU based return self._combination.get('sku').price else: # Varieties (first variety option for each variety) price = self._product.price for variety in self._varieties: price += variety._assignments[0].price return price @property def variety_option_ids(self): """ Return a list of all possible variety combinations that is used by javascript on the front-end in order to determine valid combinations while choosing variety options. """ from cubane.ishop.templatetags.shop_tags import get_shop_price result = [] for combination in self._combinations: price = combination.get('sku').price if not price: price = self._product.price result.append({ 'ids': combination.get('ids'), 'price': { 'value': price, 'display': get_shop_price(price) } }) return to_json(result) def _get_product_variety_combinations(self, product): """ Return a list of all possible combinations for variety options for the given product based on SKU records. """ skus = product.product_sku.filter(enabled=True).prefetch_related('variety_options') # build list of varity options combinations = [] option_ids = [] for sku in skus: combination = [option.pk for option in sku.variety_options.all()] for _id in combination: if _id not in option_ids: option_ids.append(_id) combinations.append({ 'sku': sku, 'ids': combination }) return combinations def get_variety_options(self): """ Return a list of variety options that have been chosen for the given product assuming this form has already been validated. """ # get option ids from cleaned data ids = [] for k, v in self.cleaned_data.items(): if k in ['quantity', 'product_id', 'prefix']: continue if k.endswith('--label'): continue ids.append(int(v)) # fetch options from database assignments = list(VarietyAssignment.objects.select_related('variety_option', 'variety_option__variety').filter(variety_option__id__in=ids, product=self._product).order_by('variety_option__variety__title')) return [assignment.variety_option for assignment in assignments] def get_variety_option_labels(self, variety_options): """ Return a dict of labels assigning additional custom label text for individual variety options that have been chosen. We assume that the form has already been validated. """ labels = {} for k, v in self.cleaned_data.items(): if not k.endswith('--label'): continue variety_slug = k[:-len('--label')] for option in variety_options: if option.variety.slug == variety_slug: labels[unicode(option.pk)] = v return labels def get_quantity(self): """ Return the quantity assuming this form has already been validated. """ return int(self.cleaned_data.get('quantity')) def get_max_quantity(self, request): """ Return maximum quantity that is left for this product or settings max quantity. """ return request.settings.max_quantity def _get_initial_product_combination(self, combinations, varieties): """ Return the best (closest) variety combination that is valid for this product based on the given list of all valid combinations. The closest match is determined by calculating a distance d, which is the distance between the variety sequence index 'seq' of the variety option. """ lowest_d = sys.maxint best = None for combination in combinations: d = 0 for option_id in combination.get('ids'): for variety in varieties: for option in variety._variety_options: if option.id == option_id: d += option.seq if d < lowest_d: lowest_d = d best = combination return best def _get_matching_variety_by_option_id(self, option_id, varieties): """ Return the matching variety that the variety with the given assignment id belongs to based on the given list of all varieties. """ for variety in varieties: for option in variety._variety_options: if option.id == option_id: return variety return None def _filter_assignments_by_skus(self, assignments, has_skus, combinations): """ Return a new list of assignments that only contains assignments that actually appear within the list of valid SKU combinations, if we actually use SKUs. """ # SKUs are not used if not has_skus: return assignments result = [] for assignment in assignments: # keep options that are not taking part ion SKU numbers... if not assignment.variety_option.variety.sku: result.append(assignment) continue # try to find matching combination found = False for combination in combinations: if assignment.variety_option.pk in combination.get('ids'): result.append(assignment) break return result def _configure_for_product(self, request, product, prefix, with_varieties=True): """ Configure form based on given product. """ self._request = request self._product = product self._prefix = prefix self._variety_label_info = [] self.fields['prefix'].initial = prefix # determine all possible combinations of varieties for this product if with_varieties: self._has_skus = self._product.sku_enabled and self._product.product_sku.all().count() > 0 if self._has_skus: self._combinations = self._get_product_variety_combinations( self._product ) else: self._combinations = [] else: self._has_skus = False self._combinations = [] # load all assigned varieties if with_varieties: assignments = list(VarietyAssignment.objects.select_related( 'variety_option', 'variety_option__image', 'variety_option__variety', 'variety_option__variety__parent', 'variety_option__variety__parent__parent', 'variety_option__variety__parent__parent__parent', 'product' ).filter( product=product, variety_option__enabled=True, variety_option__variety__enabled=True ).exclude( variety_option__variety__style=Variety.STYLE_ATTRIBUTE ).order_by( 'variety_option__seq', 'variety_option__id' # older versions may not have a valid seq. )) else: assignments = [] # eliminate assigned varieties that do not appear in any SKU, if # the product is managed by SKU combinations. Some varieties are not # taking part in SKUs directly and will appear regardless... if with_varieties: assignments = self._filter_assignments_by_skus( assignments, self._has_skus, self._combinations ) # isolate varieties based on assignments (keep order) self._varieties = [] if with_varieties: for assignment in assignments: if assignment.variety_option.variety not in self._varieties: self._varieties.append(assignment.variety_option.variety) # split options per variety if with_varieties: for variety in self._varieties: variety._variety_options = [] variety._assignments = [] for assignment in assignments: if assignment.variety_option.variety.id == variety.id: variety._variety_options.append(assignment.variety_option) variety._assignments.append(assignment) # sort varieties by seq. number, so that they appear in the order # as defined in the backend, but always present SKU-relevant varieties # first... if with_varieties: def _sort(v): sorting = [not v.sku] if v.parent is not None: sorting.append(v.parent.seq) if v.parent.parent is not None: sorting.append(v.parent.parent.seq) if v.parent.parent.parent is not None: sorting.append(v.parent.parent.parent.seq) sorting.append(v.seq) return sorting self._varieties.sort(key=_sort) # rebuild list of varieties, so that varieties where the customer cannot # choose from (because there is only one option available) are presented # first. Other than that, the defined seq. order is not changed. if with_varieties: single_option_varieties = [] multiple_options_varieties = [] for v in self._varieties: if len(v._variety_options) == 1: single_option_varieties.append(v) else: multiple_options_varieties.append(v) self._varieties = single_option_varieties + multiple_options_varieties # determine the total number of possible combinations combinations = 1 if with_varieties: for variety in self._varieties: if variety.sku: combinations *= len(variety._variety_options) # determine if we need to change the style from default drop down # to list automatically. Whenever we have at least one possible # combination not available we cannot present this as a drop down, # because individual options in a drop down control cannot be # rendered as being unavailable by default... if with_varieties: should_be_list = len(self._combinations) != combinations and self._has_skus else: should_be_list = False # generate variety form fields self.varieties_fields = OrderedDict() if with_varieties: for variety in self._varieties: # determine if we need to change the style from default drop down # to list automatically. Whenever we have at least one possible # combination not available we cannot present this as a drop down, # because individual options in a drop down control cannot be # rendered as being unavailable by default... if variety.sku and variety.style == Variety.STYLE_SELECT and should_be_list: variety.style = Variety.STYLE_LIST # create variety select field self.varieties_fields.update({ variety.slug: VarietyField( request, variety, variety._assignments, has_skus=self._has_skus, label=variety.display_title) }) # insert name label if any option of the variety supports # a custom name label variety_option_with_label_ids = map(lambda option: unicode(option.pk), filter(lambda option: option.text_label, variety._variety_options)) if variety_option_with_label_ids: label_fieldname = '%s--label' % variety.slug self.varieties_fields.update({ label_fieldname: forms.CharField( label='', required=False, max_length=10000, widget=forms.Textarea(attrs={ 'placeholder': 'Label Text...', 'class': 'variety-text-label', 'data-variety-name': variety.slug, 'data-varity-option-ids': ','.join(variety_option_with_label_ids), }) ) }) self.varieties_fields[label_fieldname].group_class = 'variety-label-text' # add information in order to clean data self._variety_label_info.append({ 'variety_fieldname': variety.slug, 'option_ids': variety_option_with_label_ids, 'label_fieldname': label_fieldname }) # inject product id self.fields['product_id'].initial = product.id # setup choices for quantity... self.fields['quantity'].choices = [ (i, unicode(i)) for i in range(1, self.get_max_quantity(request) + 1) ] # apply form fields self.fields = OrderedDict(list(self.varieties_fields.items()) + list(self.fields.items())) # determine the start configuration of all varieties based on selecting # a valid start combination that is as close as possible to the first # option for every variety. initial = self._get_default_initial() # update initials with query arguments for k in initial.keys(): if k in request.GET: initial[k] = request.GET.get(k) # apply initial values for k, v in initial.items(): self.fields[k].initial = v def clean(self, *args, **kwargs): d = super(AddToBasketForm, self).clean(*args, **kwargs) # clean label (text required) if not self._price_calculation: for label_info in self._variety_label_info: variety_fieldname = label_info.get('variety_fieldname') option_ids = label_info.get('option_ids') label_fieldname = label_info.get('label_fieldname') variety_option_id = d.get(variety_fieldname) if variety_option_id and unicode(variety_option_id) in option_ids: # label selected, make sure that a label has actually been # provided; otherwise generate form error... label_value = d.get(label_fieldname) if not label_value: self.field_error(label_fieldname, 'Label text is required.') return d def _get_default_initial(self): """ Return the default initial value set for all varieties, which is usually the first option for each variety. """ initial = {} if self._has_skus: self._combination = self._get_initial_product_combination(self._combinations, self._varieties) if self._combination: for option_id in self._combination.get('ids'): variety = self._get_matching_variety_by_option_id(option_id, self._varieties) if variety: initial[variety.slug] = option_id else: # set the initial variety option to the first option available for variety in self._varieties: initial[variety.slug] = variety._variety_options[0].pk return initial
class ResultEntryForm(forms.Form): NAMES = { "pm": "Prime Minister", "mg": "Member of Government", "lo": "Leader of the Opposition", "mo": "Member of the Opposition" } GOV = ["pm", "mg"] OPP = ["lo", "mo"] RANKS = ( (1, 1), (2, 2), (3, 3), (4, 4), ) winner = forms.ChoiceField(label="Which team won the round?", choices=Round.VICTOR_CHOICES) def __init__(self, *args, **kwargs): # Have to pop these off before sending to the super constructor round_object = kwargs.pop('round_instance') no_fill = False if 'no_fill' in kwargs: kwargs.pop('no_fill') no_fill = True super(ResultEntryForm, self).__init__(*args, **kwargs) # If we already have information, fill that into the form if round_object.victor != 0 and not no_fill: self.fields["winner"].initial = round_object.victor self.fields['round_instance'] = forms.IntegerField( initial=round_object.pk, widget=forms.HiddenInput()) gov_team, opp_team = round_object.gov_team, round_object.opp_team gov_debaters = [(-1, '---')] + [(d.id, d.name) for d in gov_team.debaters.all()] opp_debaters = [(-1, '---')] + [(d.id, d.name) for d in opp_team.debaters.all()] #TODO: Combine these loops? for d in self.GOV: self.fields["%s_debater" % (d)] = forms.ChoiceField( label="Who was %s?" % (self.NAMES[d]), choices=gov_debaters) self.fields["%s_speaks" % (d)] = forms.DecimalField( label="%s Speaks" % (self.NAMES[d]), validators=[validate_speaks]) self.fields["%s_ranks" % (d)] = forms.ChoiceField( label="%s Rank" % (self.NAMES[d]), choices=self.RANKS) for d in self.OPP: self.fields["%s_debater" % (d)] = forms.ChoiceField( label="Who was %s?" % (self.NAMES[d]), choices=opp_debaters) self.fields["%s_speaks" % (d)] = forms.DecimalField( label="%s Speaks" % (self.NAMES[d]), validators=[validate_speaks]) self.fields["%s_ranks" % (d)] = forms.ChoiceField( label="%s Rank" % (self.NAMES[d]), choices=self.RANKS) if round_object.victor != 0 and not no_fill: for d in self.GOV + self.OPP: try: stats = RoundStats.objects.get(round=round_object, debater_role=d) self.fields["%s_debater" % (d)].initial = stats.debater.id self.fields["%s_speaks" % (d)].initial = stats.speaks self.fields["%s_ranks" % (d)].initial = int( round(stats.ranks)) except: pass def clean(self): cleaned_data = self.cleaned_data #This is where we validate that the person entering data didn't mess up significantly gov, opp = self.GOV, self.OPP debaters = gov + opp try: speak_ranks = [(cleaned_data["%s_speaks" % (d)], cleaned_data["%s_ranks" % (d)], d) for d in debaters] sorted_by_ranks = sorted(speak_ranks, key=lambda x: x[1]) #Check to make sure everyone has different ranks if set([r[0] for r in self.RANKS]) != set( [int(x[1]) for x in sorted_by_ranks]): for debater in debaters: self._errors["%s_speaks" % (debater)] = self.error_class( ["Ranks must be different"]) #Check to make sure that the lowest ranks have the highest scores high_score = sorted_by_ranks[0][0] for (speaks, rank, debater) in sorted_by_ranks: if speaks > high_score: self._errors["%s_speaks" % debater] = self.error_class( ["These speaks are too high for the rank"]) high_score = speaks #Check to make sure that the team with most points wins gov_speaks = sum([cleaned_data["%s_speaks" % (d)] for d in gov]) opp_speaks = sum([cleaned_data["%s_speaks" % (d)] for d in opp]) cleaned_data["winner"] = int(cleaned_data["winner"]) if cleaned_data["winner"] == 0: self._errors["winner"] = self.error_class( ["Someone has to win!"]) if cleaned_data["winner"] == 1 and opp_speaks > gov_speaks: self._errors["winner"] = self.error_class(["Low Point Win!!"]) if cleaned_data["winner"] == 2 and gov_speaks > opp_speaks: self._errors["winner"] = self.error_class(["Low Point Win!!"]) for deb in gov + opp: #TODO: Take out this strange cast to int, perhaps have real error valus? if int(cleaned_data["%s_debater" % deb]) == -1: self._errors["%s_debater" % deb] = self.error_class( ["You need to pick a debater"]) except Exception, e: print "Caught error %s" % (e) self._errors["winner"] = self.error_class( ["Non handled error, preventing data contamination"]) return cleaned_data
class MassActionForm(forms.Form): """ Mass action form for Messages """ mark = forms.ChoiceField(label=_("With selected"), choices=(('', '-----'), ('read', _('Mark Read')), ('unread', _('Mark Unread')), ( 'delete', _('Delete Completely')), ('trash', _('Move to Trash'))), required=False) stream = forms.ModelChoiceField(queryset=[], required=False) user = None markall = forms.ChoiceField(label=_("Mark all"), choices=(('', '-----'), ('markall', _('Mark all as Read'))), required=False) instance = None def __init__(self, user, *args, **kwargs): if 'instance' in kwargs: self.instance = kwargs['instance'] del kwargs['instance'] self.user = user super(MassActionForm, self).__init__(*args, **kwargs) self.fields['stream'].queryset = Object.filter_permitted( user, MessageStream.objects, mode='x') self.fields['stream'].label = _("Move to") self.fields['mark'] = forms.ChoiceField(label=_("With selected"), choices=(('', '-----'), ('read', _('Mark Read')), ('unread', _('Mark Unread')), ('delete', _('Delete Completely')), ('trash', _('Move to Trash'))), required=False) self.fields['markall'] = forms.ChoiceField(label=_("Mark all"), choices=(('', '-----'), ('markall', _('Mark all as Read'))), required=False) def save(self, *args, **kwargs): "Save override to omit empty fields" if self.instance and self.is_valid(): if self.cleaned_data['stream']: self.instance.stream = self.cleaned_data['stream'] if self.user and self.cleaned_data['mark']: if self.cleaned_data['mark'] == 'read': try: self.instance.read_by.add(self.user) except Exception: pass if self.cleaned_data['mark'] == 'unread': try: self.instance.read_by.remove(self.user) except Exception: pass self.instance.save() if self.user and self.cleaned_data['mark']: if self.cleaned_data['mark'] == 'delete': self.instance.delete() if self.cleaned_data['mark'] == 'trash': self.instance.trash = True self.instance.save() elif self.user and self.cleaned_data['markall']: query = Q(reply_to__isnull=True) & ~Q(read_by=self.user) for message in Object.filter_permitted(self.user, Message.objects.filter(query), mode='x'): try: message.read_by.add(self.user) except Exception: pass
class MemberForm(forms.ModelForm): MR,MS,MRS =("Mr.","Ms.","Mrs.") gender_status = (("","Select Gender"), (MR,"Mr."),(MS,"Ms."),(MRS,"Mrs")) gender = forms.ChoiceField(required =True,choices=gender_status) email = forms.CharField(required = False,widget=forms.TextInput(attrs={'placeholder': 'Email Address'})) telephone = forms.CharField(required = False,widget=forms.TextInput(attrs={'placeholder': 'telephone'})) firstname = forms.CharField(required = True,widget=forms.TextInput(attrs={'placeholder': 'First name'})) lastname = forms.CharField(required = True,widget=forms.TextInput(attrs={'placeholder': 'Last name'})) middlename = forms.CharField(required = False,widget=forms.TextInput(attrs={'placeholder': 'Middle name'})) member_id = forms.CharField(required = True,widget=forms.TextInput()) address = forms.CharField( label='Address',required =True, widget=forms.TextInput(attrs={'placeholder': 'Current Address'}) ) class Meta: model = MemberModel fields =["member_id","gender","firstname","middlename","lastname","email","address","telephone","active","birthday"] def clean_email(self,*args, **kwargs): print(".....clean_emaill") email = self.cleaned_data.get('email') validator = EmailValidator() email =email.strip() if(len(email )> 0): try: validator(email) except ValidationError: print("Please enter valid email address.") raise forms.ValidationError("Please enter valid email address.") return email def ValidateUsername(self,username): print("validating-------------") codeCtr=1 qs = User.objects.filter(username__iexact = username) if qs.count() == 0: print (f"not found... username:{username}") return username else: qs = Tmp_UsernameModel.objects.filter(username__iexact = username) if qs.count() == 0: print("new record on code_counter:", username) Tmp_UsernameModel.objects.create(username=username,code_counter= codeCtr ) else: qs = Tmp_UsernameModel.objects.filter(username__iexact = username) codeCtr = qs[0].code_counter + 1 qs.update(code_counter = codeCtr ) #return 1 success or 0 failed print("code ctr must increment") newCodeCtr = str(codeCtr).strip() if len(newCodeCtr) == 1: # convert the 1 digit value from db to 2 digits newCodeCtr = newCodeCtr username = username+ newCodeCtr return username def clean_member_id(self,*args, **kwargs): print(".....clean_ member_id") member_id = self.cleaned_data.get('member_id').strip().lower() if member_id == "default": member_id = self.ValidateUsername(member_id) # validator = EmailValidator() # email =email.strip() # if(len(email )> 0): # try: # validator(email) # except ValidationError: # print("Please enter valid email address.") # raise forms.ValidationError("Please enter valid email address.") print(f"clean_member_id: {member_id}") return member_id
class RegularSavingsAccountForm(forms.Form): monthly_deposit = CurrencyField( widget=CurrencyInput(attrs={'class': 'text'}), required=True, initial=Decimal('0.00')) tax_rate = forms.ChoiceField(choices=ACCOUNT_TYPE_CHOICES, required=False)
class Peticion(forms.Form): seleccion = forms.ChoiceField(choices=[('Desprendible de pago', 'Desprendible de pago'), ('Certificado de tabajo', 'Certificado de tabajo'), ('Certificado de EPS', 'Certificado de EPS')], widget=forms.Select(), label="Escoja el documeto que desea solicitar")
class RateTrackerForm(forms.Form): """ When the user is searching if they specify a Fixed Rate Bond type, the Account Name is not applicable and not required. """ provider = forms.ModelChoiceField( Provider.objects.all().exclude( title="Kent Reliance Building Society").exclude( title="Sainsbury's Finance"), empty_label='Select provider', widget=forms.Select(attrs={'class': 'required number'})) account_type = forms.ChoiceField( widget=forms.Select(attrs={'class': 'required number'}), choices=_get_rt_account_type_choices()) balance = CurrencyField( widget=CurrencyInput(attrs={'class': 'text commaNumber'}), initial=1, help_text= 'Your interest rate changes depending upon the account balance.') product = forms.IntegerField(widget=forms.TextInput(attrs={ 'class': 'text', 'min': '1' }), required=False) maturity_date = forms.DateField( widget=MonthYearWidget(years=_get_maturity_years()), required=False) opening_date = forms.DateField(widget=MonthYearWidget(years=_get_years()), required=False) def __init__(self, *args, **kwargs): super(RateTrackerForm, self).__init__(*args, **kwargs) self.set_reminder = False self.high_balance = False self.opening_date_required = False def in_bestbuy_list(self, account_type): for val in get_maturity_based_bestbuys().values('id'): if account_type == val['id']: return True return False def clean(self): super(RateTrackerForm, self).clean() data = self.cleaned_data account_type = data.get('account_type', None) balance = data.get('balance', None) if account_type in EMPTY_VALUES: self.errors['account_type'] = 'Please enter an account type' return if self.in_bestbuy_list(int(account_type)): # Maturity date is a required field self.set_reminder = True maturity_date = data.get('maturity_date', None) if maturity_date in EMPTY_VALUES: self.errors['maturity_date'] = 'Please enter a maturity date' else: today = datetime.datetime.date(datetime.datetime.now()) if maturity_date < today: self.errors[ 'maturity_date'] = 'Please enter a maturity date in the future' else: # we need either product or maturity date to be populated product = data.get('product', None) if product in EMPTY_VALUES: self.errors['product'] = 'Please choose an Account Name' return try: if Product.objects.get(pk=product).show_opening_date(): opening_date = self.cleaned_data.get('opening_date', None) if opening_date in EMPTY_VALUES: self.opening_date_required = True self.errors[ 'opening_date'] = 'Please enter an opening date' raise forms.ValidationError( 'Please enter an opening date') except Product.DoesNotExist: self.errors['product'] = 'Please choose an Account Name' return if balance in EMPTY_VALUES or balance <= 0: self.errors['balance'] = 'Please enter your balance' return data
class FoodMediaForm(forms.Form): """ For validating form data of dish media API requestes """ media_type = forms.ChoiceField(choices=MediaType.choices(), required=True) save_location = forms.ChoiceField(choices=FoodSaveLocations.choices(), required=True) media_file = forms.FileField(required=True)
class FriendRequestForm(forms.Form): CHOICES = [('accepted', 'accept'), ('rejected', 'reject')] request_status = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect)
class CollectionOrderForm(ModelForm): """ Add collection in group form. """ grading_policy_name = forms.ChoiceField( choices=((k, v) for k, v in GRADING_POLICY_NAME_TO_CLS.items()), required=True, widget=PolicyChoiceWidget) class Meta: """ Inner class with metadata options for CollectionOrderForm. """ model = CollectionOrder fields = ('collection', 'slug', 'engine', 'grading_policy_name', 'strict_forward', 'ui_option', 'ui_next') labels = { 'ui_option': _('UI Option'), 'ui_next': _('Additional NEXT Button') } help_texts = { 'collection': _("You can choose the available collection or create a new Collection above." ) } def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') self.group = kwargs.pop('group') read_only = kwargs.pop('read_only') if 'read_only' in kwargs else False super().__init__(*args, **kwargs) self.fields['collection'].queryset = self.fields[ 'collection'].queryset.filter(owner_id=self.user.id) if read_only: self.fields['collection'].widget = HiddenInput() self.fields['collection'].widget.attrs['readonly'] = read_only def clean(self): super().clean() engine, policy = self.cleaned_data.get( 'engine'), self.cleaned_data.get('grading_policy_name') engine_cls = engine.engine_driver policy_cls = GRADING_POLICY_NAME_TO_CLS.get(policy) if policy_cls is None: raise forms.ValidationError( {'grading_policy_name': ['Not correct policy']}) required_engine = policy_cls.require.get('engine') if required_engine and not isinstance(engine_cls, required_engine): engine_err_msg = 'This Engine doesn\'t support chosen Policy. Please choose another policy or engine.' policy_err_msg = 'This policy can be used only with {} engine(s). Choose another policy or engine.'.format( ", ".join([ engine.__name__.strip('Engine') for engine in required_engine ])) raise forms.ValidationError({ 'engine': [engine_err_msg], 'grading_policy_name': [policy_err_msg] }) return self.cleaned_data def save(self, **kwargs): self.instance.group = self.group self.instance.collection = self.cleaned_data['collection'] self.instance.engine = self.cleaned_data['engine'] self.instance.grading_policy = self.cleaned_data['grading_policy'] self.instance.save()
class LinkTagResourcesAdminForm(forms.Form): tag = forms.CharField(required=True) type = forms.ChoiceField(choices=[(x, x.capitalize()) for x in ["assoc", "nonassoc"]]) data = forms.MultipleChoiceField(choices=[], required=False) search = forms.CharField(required=False) def __init__(self, *args, **kwargs): self.project = kwargs.pop("project") super(LinkTagResourcesAdminForm, self).__init__(*args, **kwargs) # we cant filter any further at this stage as we dont know the # action yet - ie un/link self.fields["data"].choices = Resource.objects.filter( project=self.project).values_list("path", "pk") @cached_property def tag_tool(self): return TagsTool(projects=[self.project]).get(self.cleaned_data["tag"]) def clean(self): cleaned_data = super(LinkTagResourcesAdminForm, self).clean() if self.errors: return try: tag_tool = self.tag_tool except IndexError: return self.add_error("tag", "Unrecognized tag: %s" % cleaned_data["tag"]) if self.cleaned_data["data"]: # If there is valid data, then submit the form try: self.cleaned_data["data"] = self._clean_paths_for_submit() except forms.ValidationError as e: return self.add_error("data", e) self.cleaned_data["action"] = ( tag_tool.link_resources if self.cleaned_data["type"] == "nonassoc" else tag_tool.unlink_resources) else: # If data is not set, get a list of paths that can be used # in the form self.cleaned_data["data"] = self._clean_paths_for_select() self.cleaned_data["action"] = None @property def action_type(self): """Returns the action type name, used for error message""" return self.cleaned_data.get("type") is not None and ( "link" if self.cleaned_data["type"] == "nonassoc" else "unlink") @property def resources(self): return (self.tag_tool.linkable_resources if self.cleaned_data["type"] == "nonassoc" else self.tag_tool.linked_resources) def _clean_paths_for_select(self): """Returns a list of paths that can be un/linked for a given search filter """ qs = self.resources if self.cleaned_data["search"]: qs = qs.filter(path__contains=self.cleaned_data["search"]) return qs.values_list("path") def _clean_paths_for_submit(self): """Validates and returns a list of paths that can be un/linked for given submission data """ paths = list(self.resources.filter(path__in=self.cleaned_data["data"])) if len(paths) != len(self.cleaned_data["data"]): # the length of the paths requested to be added/removed # should be the same as the validated paths length. raise forms.ValidationError( "Unable to %s the resources requested" % self.action_type) return paths def save(self): # if action is not set then return the list of paths if self.cleaned_data["action"] is None: return list(self.cleaned_data["data"]) # if action (link/unlink) is set then call with submitted paths self.cleaned_data["action"](self.cleaned_data["data"]) # and generate a new list of paths for select return list(self._clean_paths_for_select())
class CorpMembershipAppForm(TendenciBaseForm): description = forms.CharField( required=False, widget=TinyMCE(attrs={'style': 'width:70%'}, mce_attrs={ 'storme_app_label': CorpMembershipApp._meta.app_label, 'storme_model': CorpMembershipApp._meta.module_name.lower() }), help_text=_('Will show at the top of the application form.')) confirmation_text = forms.CharField( required=False, widget=TinyMCE(attrs={'style': 'width:70%'}, mce_attrs={ 'storme_app_label': CorpMembershipApp._meta.app_label, 'storme_model': CorpMembershipApp._meta.module_name.lower() }), help_text=_('Will show on the confirmation page.')) notes = forms.CharField( label=_('Notes'), required=False, widget=forms.Textarea(attrs={'rows': '3'}), help_text=_( 'Notes for editor. Will not display on the application form.')) status_detail = forms.ChoiceField(choices=( ('active', _('Active')), ('inactive', _('Inactive')), ('admin hold', _('Admin Hold')), )) class Meta: model = CorpMembershipApp fields = ( 'name', 'slug', 'corp_memb_type', 'authentication_method', 'memb_app', 'payment_methods', 'include_tax', 'tax_rate', 'description', 'confirmation_text', 'notes', 'allow_anonymous_view', 'user_perms', 'member_perms', 'group_perms', 'status_detail', ) def __init__(self, *args, **kwargs): super(CorpMembershipAppForm, self).__init__(*args, **kwargs) if self.instance.pk: self.fields['description'].widget.mce_attrs[ 'app_instance_id'] = self.instance.pk self.fields['confirmation_text'].widget.mce_attrs[ 'app_instance_id'] = self.instance.pk else: self.fields['description'].widget.mce_attrs['app_instance_id'] = 0 self.fields['confirmation_text'].widget.mce_attrs[ 'app_instance_id'] = 0 def clean(self): cleaned_data = super(CorpMembershipAppForm, self).clean() is_public = cleaned_data.get('allow_anonymous_view') corp_memb_types = cleaned_data.get('corp_memb_type') if is_public and corp_memb_types: public_types = [ not cm_type.admin_only for cm_type in corp_memb_types ] if not any(public_types): raise forms.ValidationError( _('Please select a public corporate membership type. \ All types currently selected are admin only.')) return cleaned_data