class CotizacionForm(ModelForm): email = forms.EmailField(label="Correo Electrónico", required=False) nro_contacto = forms.CharField(label="Número de Contacto", required=False) nombres_contacto = forms.CharField(label="Nombres", required=False) apellidos_contacto = forms.CharField(label="Apellidos", required=False) contacto_nuevo = forms.BooleanField(label="Contacto nuevo", required=False) razon_social = forms.CharField(label="Razón Social", required=False) email_adicional = forms.EmailField(label="Email Adicional", required=False) observaciones = forms.Textarea() ciudad_despacho = forms.ModelChoiceField( queryset=Ciudad.objects.select_related('departamento', 'departamento__pais').all(), widget=autocomplete.ModelSelect2(url='geografia:ciudad-autocomplete'), required=False ) cliente_biable = forms.ModelChoiceField( queryset=Cliente.objects.all(), widget=autocomplete.ModelSelect2(url='biable:cliente-autocomplete'), required=False, label='Cliente CGuno' ) contacto = forms.ModelChoiceField( queryset=ContactoEmpresa.objects.all(), widget=autocomplete.ModelSelect2(url='contactos:contactos-autocomplete', forward=['cliente_biable']), required=False, label='Contacto' ) id = forms.IntegerField(required=False, widget=forms.HiddenInput) def clean(self): cleaned_data = super(CotizacionForm, self).clean() razon_social = cleaned_data.get("razon_social") cliente_biable = cleaned_data.get("cliente_biable") ciudad_despacho = cleaned_data.get("ciudad_despacho") ciudad = cleaned_data.get("ciudad") contacto = cleaned_data.get("contacto") email = cleaned_data.get("email") nombres_contacto = cleaned_data.get("nombres_contacto") apellidos_contacto = cleaned_data.get("apellidos_contacto") nro_contacto = cleaned_data.get("nro_contacto") if (not razon_social and not cliente_biable): # Only do something if both fields are valid so far. raise forms.ValidationError( "Debe tener o razón social o un cliente CGuno." " No puede estar vacios los dos campos" ) if (not ciudad_despacho and not ciudad): # Only do something if both fields are valid so far. raise forms.ValidationError( "Debe tener o ciudad alterna o ciudad." " No puede estar vacios los dos campos" ) if (not contacto and (not email or not nombres_contacto or not apellidos_contacto or not nro_contacto)): # Only do something if both fields are valid so far. raise forms.ValidationError( "Debe tener información de un contacto." ) class Meta: model = Cotizacion fields = [ 'id', 'razon_social', 'cliente_biable', 'sucursal_sub_empresa', 'cliente_nuevo', 'pais', 'ciudad', 'otra_ciudad', 'ciudad_despacho', 'nombres_contacto', 'apellidos_contacto', 'nro_contacto', 'email', 'observaciones', 'contacto', 'contacto_nuevo', 'email_adicional', ] def __init__(self, *args, **kwargs): super(CotizacionForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_id = 'id-cotizacionForm' self.helper.form_method = "post" self.helper.form_class = 'form-inline' self.helper.layout = Layout( Div( Field('id'), Field('razon_social'), Field('cliente_biable'), ), Div( Field('sucursal_sub_empresa'), ), Div( Field('cliente_nuevo') ), Div( Field('pais'), Field('ciudad'), ), Div( Field('ciudad_despacho'), ), Div( Field('otra_ciudad') ), Div( Field('contacto'), ), Div( Field('nombres_contacto'), Field('apellidos_contacto') ), Div( Field('nro_contacto'), ), PrependedText('email', '@', placeholder="Correo Electrónico"), PrependedText('email_adicional', '@', placeholder="Correo Electrónico Adicional"), Div( Field('contacto_nuevo'), ), HTML('<hr/>'), Field('observaciones'), HTML('<hr/>') ) self.helper.all().wrap(Field, css_class="form-control")
def report_form_factory(model, fkeys_filter_func=None, foreign_key_widget_func=None, crosstab_model=None, display_compute_reminder=True, **kwargs): """ Create a Reprot Form based on the report_model passed :param model: :param fkeys_filter_func: :param foreign_key_widget_func: :param crosstab_model: :param display_compute_reminder: :param kwargs: :return: """ foreign_key_widget_func = foreign_key_widget_func or _default_foreign_key_widget fkeys_filter_func = fkeys_filter_func or (lambda x: x) # gather foreign keys fkeys_map = get_foreign_keys(model) fkeys_map = fkeys_filter_func(fkeys_map) fkeys_list = [] fields = OrderedDict() fields['start_date'] = forms.DateTimeField( required=False, label=_('From date'), initial=app_settings.SLICK_REPORTING_DEFAULT_START_DATE, widget=forms.DateTimeInput(format='%m/%d/%Y %H:%M', attrs={'autocomplete': "off"}), ) fields['end_date'] = forms.DateTimeField( required=False, label=_('To date'), initial=app_settings.SLICK_REPORTING_DEFAULT_END_DATE, widget=forms.DateTimeInput(format='%m/%d/%Y %H:%M', attrs={'autocomplete': "off"})) for name, f_field in fkeys_map.items(): fkeys_list.append(name) fields[name] = f_field.formfield(**foreign_key_widget_func(f_field)) if crosstab_model and display_compute_reminder: fields['crosstab_compute_reminder'] = forms.BooleanField( required=False, label=_('display the crosstab reminder'), initial=True) new_form = type( 'ReportForm', ( BaseReportForm, forms.BaseForm, ), { "base_fields": fields, '_fkeys': fkeys_list, 'foreign_keys': fkeys_map, 'crosstab_model': crosstab_model, 'crosstab_display_compute_reminder': display_compute_reminder, }) return new_form
class ManageSubscriptionsForm(forms.Form): """ Form used on manage subscriptions page for the user's information, like email address and language preference. @param locale: locale string, e.g. "en-US". Will be used to set country and lang defaults if not otherwise provided in initial or bound data. @param args: Other standard form args @param kwargs: Other standard form kwargs """ format = forms.ChoiceField(widget=forms.RadioSelect(renderer=SideRadios), choices=FORMATS, initial='H') remove_all = forms.BooleanField(required=False) country = forms.ChoiceField( choices=[], # will set choices based on locale required=False) lang = forms.ChoiceField( choices=[], # will set choices based on newsletter languages required=False) def __init__(self, locale, *args, **kwargs): regions = product_details.get_regions(locale) regions = sorted(regions.iteritems(), key=itemgetter(1)) lang_choices = get_lang_choices() languages = [x[0] for x in lang_choices] lang = country = locale.lower() if '-' in lang: lang, country = lang.split('-', 1) lang = lang if lang in languages else 'en' self.newsletters = kwargs.pop('newsletters', []) # Get initial - work with a copy so we're not modifying the # data that was passed to us initial = kwargs.get('initial', {}).copy() if not initial.get('country', None): initial['country'] = country if not initial.get('lang', None): initial['lang'] = lang else: lang = initial['lang'] # Sometimes people are in ET with a language that is spelled a # little differently from our list. E.g. we have 'es' on our # list, but in ET their language is 'es-ES'. Try to find a match # for their current lang in our list and use that. If we can't # find one, then fall back to guessing from their locale, # ignoring what they had in ET. (This is just for the initial # value on the form; they can always change to another valid # language before submitting.) if lang not in languages: for valid_lang, _unused in lang_choices: # if the first two chars match, close enough if lang.lower()[:2] == valid_lang.lower()[:2]: lang = valid_lang break else: # No luck - guess from the locale lang = locale.lower() if '-' in lang: lang, _unused = lang.split('-', 1) initial['lang'] = lang kwargs['initial'] = initial super(ManageSubscriptionsForm, self).__init__(*args, **kwargs) self.fields['country'].choices = regions self.fields['lang'].choices = lang_choices self.already_subscribed = initial.get('newsletters', []) def clean(self): valid_newsletters = utils.get_newsletters() for newsletter in self.newsletters: if newsletter not in valid_newsletters: msg = _("%s is not a valid newsletter") % newsletter raise ValidationError(msg) return super(ManageSubscriptionsForm, self).clean()
def parse_params(self, request, s_team): team = get_object_or_404(Team, origin__slug=s_team, tournament=request.user.profile.tournament) self.team = team fields = {} accounts = Account.objects.filter( owners__tournament=team.tournament, owners=request.user.profile.active).distinct() if accounts.count() > 0: account = forms.ModelChoiceField(accounts, required=False) fields["account"] = account new_account_name = forms.CharField(max_length=100, label="if wanted, new account name", required=False) fields["new_account"] = new_account_name def clean(self): cleaned_data = super(self.__class__, self).clean() #print(cleaned_data) if cleaned_data.get( "account", None) == None and cleaned_data['new_account'] == '': raise forms.ValidationError( "You have to choose an Account or enter a new name") fields["clean"] = clean fees = expected_fees(team) for fee in fees: chk = forms.BooleanField(required=False, initial=True, label="%s : %.2f €" % (fee["name"], fee["amount"])) ep = None if fee['type'] == Payment.TEAM: ep = Payment.objects.filter(sender__in=accounts, ref_type=fee["type"], ref_team=team).first() elif fee['type'] == Payment.ROLE: ep = Payment.objects.filter( sender__in=accounts, ref_type=fee["type"], ref_role=fee["role"], ref_attendee=fee["attendee"]).first() elif fee['type'] == Payment.PROPERTY: ep = Payment.objects.filter( sender__in=accounts, ref_type=fee["type"], ref_property=fee["property"], ref_attendee=fee["attendee"]).first() if ep: chk.help_text = "already invoiced to account %d %s" % ( ep.sender.id, ep.sender) chk.initial = False fields["fee_%s_%d_%d_%d" % (fee["type"], fee.get("attendee", self.MinusZero()).id, fee.get("role", self.MinusZero()).id, fee.get("property", self.MinusZero()).id)] = chk self.form = type("FeeForm", (forms.Form, ), fields)
def __init__(self, form, request, formentry_model=FormEntry, fieldentry_model=FieldEntry, *args, **kwargs): """ Iterate through the fields of the ``forms.models.Form`` instance and create the form fields required to control including the field in the export (with a checkbox) or filtering the field which differs across field types. User a list of checkboxes when a fixed set of choices can be chosen from, a pair of date fields for date ranges, and for all other types provide a textbox for text search. """ self.form = form self.request = request self.formentry_model = formentry_model self.fieldentry_model = fieldentry_model self.form_fields = form.fields.all() self.entry_time_name = str( self.formentry_model._meta.get_field("entry_time").verbose_name) super(EntriesForm, self).__init__(*args, **kwargs) for field in self.form_fields: field_key = "field_%s" % field.id # Checkbox for including in export. self.fields["%s_export" % field_key] = forms.BooleanField( label=field.label, initial=True, required=False) if field.is_a(*fields.CHOICES): # A fixed set of choices to filter by. if field.is_a(fields.CHECKBOX): choices = ((True, _("Checked")), (False, _("Not checked"))) else: choices = field.get_choices() contains_field = forms.MultipleChoiceField( label=" ", choices=choices, widget=forms.CheckboxSelectMultiple(), required=False) self.fields["%s_filter" % field_key] = choice_filter_field self.fields["%s_contains" % field_key] = contains_field elif field.is_a(*fields.MULTIPLE): # A fixed set of choices to filter by, with multiple # possible values in the entry field. contains_field = forms.MultipleChoiceField( label=" ", choices=field.get_choices(), widget=forms.CheckboxSelectMultiple(), required=False) self.fields["%s_filter" % field_key] = multiple_filter_field self.fields["%s_contains" % field_key] = contains_field elif field.is_a(*fields.DATES): # A date range to filter by. self.fields["%s_filter" % field_key] = date_filter_field self.fields["%s_from" % field_key] = forms.DateField( label=" ", widget=SelectDateWidget(), required=False) self.fields["%s_to" % field_key] = forms.DateField( label=_("and"), widget=SelectDateWidget(), required=False) else: # Text box for search term to filter by. contains_field = forms.CharField(label=" ", required=False) self.fields["%s_filter" % field_key] = text_filter_field self.fields["%s_contains" % field_key] = contains_field # Add ``FormEntry.entry_time`` as a field. field_key = "field_0" label = self.formentry_model._meta.get_field("entry_time").verbose_name self.fields["%s_export" % field_key] = forms.BooleanField( initial=True, label=label, required=False) self.fields["%s_filter" % field_key] = date_filter_field self.fields["%s_from" % field_key] = forms.DateField( label=" ", widget=SelectDateWidget(), required=False) self.fields["%s_to" % field_key] = forms.DateField( label=_("and"), widget=SelectDateWidget(), required=False)
class AddUserForm(forms.Form): last_name = forms.CharField( max_length=100, label=_("Фамилия *"), required=True, widget=forms.TextInput(attrs={'autocapitalize': "words"})) first_name = forms.CharField( max_length=100, label=_("Имя *"), required=True, widget=forms.TextInput(attrs={'autocapitalize': "words"})) middle_name = forms.CharField( max_length=100, label=_("Отчество"), required=False, widget=forms.TextInput(attrs={'autocapitalize': "words"})) email = forms.EmailField(max_length=100, label=_("Email *"), required=True) username = forms.CharField(max_length=100, label=_("Логин *"), required=True) password = forms.CharField(max_length=100, label=_("Пароль *"), required=True) company_id = forms.ChoiceField(label=_("Компания"), choices=COMPANY_KEYS, required=False) staff = forms.BooleanField(label=_("Персонал коворкинга"), required=False, initial=False) def clean_first_name(self): return self.cleaned_data['first_name'].strip().title() def clean_middle_name(self): return self.cleaned_data['middle_name'].strip().title() def clean_last_name(self): return self.cleaned_data['last_name'].strip().title() def clean_email(self): email = self.cleaned_data['email'].strip().lower() if ExtUser.objects.filter(email=email).count() > 0: raise forms.ValidationError( _("Почтовый ящик '%s' уже используется.") % email) return email def create_user(self, username, password, first_name=None, middle_name=None, last_name=None, company=None, is_staff=False, email=None): try: u = ExtUser.objects.create(username=username, email=email, company=company, first_name=first_name, middle_name=middle_name, last_name=last_name, is_staff=is_staff) u.set_password(password) u.save() except Exception as e: print('***** ***** *****') print(e) print('***** ***** *****') return user def save(self): "Creates the User and Profile records with the field data and returns the user" if not self.is_valid(): raise Exception(_('Форма не прошла проверку')) first = self.cleaned_data['first_name'] middle = self.cleaned_data['middle_name'] last = self.cleaned_data['last_name'] email = self.cleaned_data['email'] username = self.cleaned_data['username'] password = self.cleaned_data['password'] company = None if ((self.cleaned_data['company_id'] == '') or (self.cleaned_data['company_id'] == None)) else Company.objects.get( pk=self.cleaned_data['company_id']) staff = self.cleaned_data['staff'] user = self.create_user(username, password, first, middle, last, company=company, is_staff=staff, email=email) return user class Meta: widgets = { 'last_name': forms.TextInput(attrs={ 'autocapitalize': 'on', 'autocorrect': 'off' }), 'first_name': forms.TextInput(attrs={ 'autocapitalize': 'on', 'autocorrect': 'off' }), 'middle_name': forms.TextInput(attrs={ 'autocapitalize': 'on', 'autocorrect': 'off' }), }
class AdminBandForm(forms.ModelForm): delete = forms.BooleanField()
class SymposiumForm(forms.Form): def member_type_label(self): return [ label for value, label in self.fields["member_type"].choices if value in self["member_type"].value() ] firstname = forms.CharField( label="Vorname", widget=forms.TextInput(attrs={"placeholder": "Vorname"})) lastname = forms.CharField( label="Nachname", widget=forms.TextInput(attrs={"placeholder": "Nachname"})) email = forms.CharField( label="E-Mail", widget=forms.TextInput(attrs={"placeholder": "E-Mail"}), ) takes_part_in_mv = forms.ChoiceField( label= "Ich nehme an der virtuellen Mitgliederversammlung des VFLL am Freitag, 17. September 2021", choices=TAKES_PART_CHOICES, ) member_type = forms.ChoiceField(label="Ich bin", choices=MEMBER_TYPE_CHOICES) vote_transfer = forms.CharField( label= "Ich nehme an der Mitgliederversammlung nicht teil und übertrage als ordentliches Mitglied meine Stimme für alle Abstimmungen und Wahlen inhaltlich unbegrenzt an:", widget=forms.TextInput(attrs={"placeholder": "Stimmübertragung an"}), required=False, ) vote_transfer_check = forms.BooleanField( widget=forms.CheckboxInput(attrs={"class": "form-radio"}), required=False, label= "Ich habe mich rückversichert, dass die Person, der ich meine Stimme übertrage, ordentliches Mitglied im VFLL ist und an der virtuellen Mitgliederversammlung teilnehmen wird.", ) mv_check = forms.BooleanField( widget=forms.CheckboxInput(attrs={"class": "form-radio"}), required=False, label=mark_safe( "Ich bin damit einverstanden, dass meine Kontaktdaten (Vor- und Nachname, <br/>E-Mail-Adresse) auf der internen Teilnahmeliste der Mitgliederversammlung stehen, die an Vorstand, Wahlleitung und Geschäftsstelle weitergegeben wird." ), ) takes_part_in_zw = forms.ChoiceField( label= "Ich nehme an der Online-Veranstaltung Zukunftswerkstatt Freies Lektorat am Samstag/Sonntag, 18./19. September 2021", choices=TAKES_PART_CHOICES, ) zw_check = forms.BooleanField( widget=forms.CheckboxInput(attrs={"class": "form-radio"}), required=False, label=mark_safe( "Ich bin damit einverstanden, dass meine Kontaktdaten (Vor- und Nachname, <br/>E-Mail-Adresse) auf der internen Teilnahmeliste der „Zukunftswerkstatt Freies Lektorat“ stehen, die an den Vorstand, die Geschäftsstelle und zwei Personen der boscop eG als Veranstaltungsbetreuende weitergegeben wird." ), ) def __init__(self, *args, **kwargs): self.event_label = kwargs.pop("event_label", "") super(SymposiumForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_error_title = "Fehler im Formular" self.error_text_inline = False self.helper.layout = Layout( Fieldset( "Persönliche Daten", "firstname", "lastname", "email", HTML(""" <p>Bitte beachten: Die Angabe einer aktuellen E-Mail-Adresse ist Voraussetzung für die Zusendung eines Zugangscodes für das digitale Wahltool Votingtech und einer Einladungsmail für das Videokonferenztool Clickmeeting – beide Tools werden während der Mitgliederversammlung genutzt.<br/> Ebenso wird ein Link zum Zoom-Raum für die „Zukunftswerkstatt Freies Lektorat“ versandt.</p> """), css_class="border-b-2 border-gray-900 pb-2 mb-4", ), Fieldset( "1. Mitgliederversammlung", InlineRadios( "takes_part_in_mv", required=True, ), InlineRadios( "member_type", required=True, ), "vote_transfer", "vote_transfer_check", ), Fieldset( "Einverständniserklärung", HTML(""" <p><i>Die Zustimmung zur Einverständniserklärung ist notwendig, um den technisch-organisatorischen Zugang zur Veranstaltung zu gewährleisten.</i></p> """), "mv_check", HTML(""" <hr class="my-12 pt-4"/> """), css_class="border-b-2 border-gray-900 pb-2 mb-4", ), Fieldset( "2. Zukunftswerkstatt", InlineRadios("takes_part_in_zw", required=True), ), Fieldset( "Einverständniserklärung", HTML(""" <p><i>Die Zustimmung zur Einverständniserklärung ist notwendig, um den technisch-organisatorischen Zugang zur Veranstaltung zu gewährleisten.</i></p> """), "zw_check", HTML(""" <p class="mt-4"><b>Falls ihr euch für die „Zukunftswerkstatt Freies Lektorat“ angemeldet habt und doch nicht teilnehmen könnt, bitten wir euch um eine frühzeitige Absage per <br/> E-Mail an: [email protected]. </b></p> """), HTML(""" <p class="mt-4"><b>Datenschutzhinweis:</b><br/> Wir verwenden deine Angaben ausschließlich zur Durchführung der Veranstaltungen des Verbands der Freien Lektorinnen und Lektoren e.V. Deine Daten werden nicht an unbefugte Dritte weitergegeben. Verantwortlich im Sinne der DSGVO ist der Vorstand des Verbands der Freien Lektorinnen und Lektoren e.V., Geschäftsstelle, Büro Seehausen + Sandberg, Merseburger Straße 5, 10823 Berlin.</p> """), css_class="border-b-2 border-gray-900 pb-2 mb-4", ), ButtonHolder( Submit( "submit", "Anmelden", css_class= "bg-red-500 hover:bg-red-700 text-white font-bold py-2 px-4 rounded-full", )), ) # self.helper.add_input(Submit("submit", "Anmelden")) def clean(self): cleaned_data = super().clean() vote_transfer = cleaned_data.get("vote_transfer") vote_transfer_check = cleaned_data.get("vote_transfer_check") takes_part_in_mv = cleaned_data.get("takes_part_in_mv") takes_part_in_zw = cleaned_data.get("takes_part_in_zw") mv_check = cleaned_data.get("mv_check") zw_check = cleaned_data.get("zw_check") member_type = cleaned_data.get("member_type") if takes_part_in_mv != "y": if vote_transfer and not vote_transfer_check: self.add_error("vote_transfer_check", "Bitte für Stimmübertragung bestätigen") if vote_transfer and member_type != "o": self.add_error( "vote_transfer", "Stimmübertragung nur für ordentliche Mitglieder möglich", ) if takes_part_in_zw != "y" and not vote_transfer: self.add_error( "vote_transfer", "Bitte mindestens eine Teilnahme (MV oder Zukunftswerkstatt) angeben oder für die MV eine Stimmübertragung festlegen!", ) else: if vote_transfer: self.add_error( "vote_transfer", "Stimmübertragung nur bei Nichtteilnahme möglich") if vote_transfer_check: self.add_error( "vote_transfer_check", "Stimmübertragung nur bei Nichtteilnahme möglich", ) if not mv_check: self.add_error( "mv_check", "Bestätigung der Einverständniserklärung notwendig für Teilnahme", ) if takes_part_in_zw == "y" and not zw_check: self.add_error( "zw_check", "Bestätigung der Einverständniserklärung notwendig für Teilnahme", ) def clean_email(self): data = self.cleaned_data["email"] if (EventMember.objects.filter( email=data, event__label=self.event_label).count() > 0): raise forms.ValidationError( "Es gibt bereits eine Anmeldung mit dieser E-Mail-Adresse.") return data
def populate_node_properties(self, graph, itemtype, initial=None): # Node properties for item_property in itemtype.properties.all().order_by("order"): datatype_dict = item_property.get_datatype_dict() label = item_property.key # TODO: Fix the required value rendering if item_property.required: label = "%s *" % label if initial: initial_value = initial.get(label, item_property.default) else: initial_value = item_property.default field_attrs = { "required": item_property.required, "initial": initial_value, "label": label, "help_text": item_property.description, } auto_increment_update = datatype_dict["auto_increment_update"] if item_property.datatype == datatype_dict["date"]: widget = forms.TextInput(attrs={"class": "date"}) field_attrs["widget"] = widget field = forms.DateField(**field_attrs) if item_property.datatype == datatype_dict["time"]: widget = forms.TextInput(attrs={"class": "time"}) field_attrs["widget"] = widget field = forms.TimeField(**field_attrs) elif item_property.datatype == datatype_dict["boolean"]: field = forms.BooleanField(**field_attrs) elif item_property.datatype == datatype_dict["number"]: field = forms.IntegerField(**field_attrs) elif item_property.datatype == datatype_dict["float"]: field = forms.FloatField(**field_attrs) elif item_property.datatype == datatype_dict["choices"]: field_attrs["choices"] = item_property.get_choices() field_attrs["initial"] = slugify(field_attrs["initial"] or "") if initial and item_property.key in initial: slug_value = slugify(initial[item_property.key]) initial[item_property.key] = slug_value field = forms.ChoiceField(**field_attrs) elif item_property.datatype == datatype_dict["text"]: field_attrs["widget"] = widget = forms.Textarea field = forms.CharField(**field_attrs) elif item_property.datatype == datatype_dict["auto_user"]: field_attrs["initial"] = self.username widget = forms.TextInput(attrs={"readonly": "readonly"}) field_attrs["widget"] = widget field = forms.CharField(**field_attrs) elif item_property.datatype == datatype_dict["auto_now"]: if not initial: field_attrs["initial"] = datetime.datetime.today() else: field_attrs["initial"] = item_property.value widget = forms.TextInput(attrs={"readonly": "readonly"}) field_attrs["widget"] = widget field = forms.CharField(**field_attrs) elif item_property.datatype == datatype_dict["auto_now_add"]: if not initial: field_attrs["initial"] = datetime.datetime.today() else: field_attrs["initial"] = item_property.value widget = forms.TextInput(attrs={"readonly": "readonly"}) field_attrs["widget"] = widget field = forms.CharField(**field_attrs) elif item_property.datatype == datatype_dict["auto_increment"]: if not item_property.auto: field_attrs["initial"] = 0 else: field_attrs["initial"] = item_property.auto widget = forms.TextInput(attrs={"readonly": "readonly"}) field_attrs["widget"] = widget field = forms.CharField(**field_attrs) elif (item_property.datatype == auto_increment_update): if not item_property.default: field_attrs["initial"] = '0' widget = forms.TextInput(attrs={"readonly": "readonly"}) field_attrs["widget"] = widget field = forms.CharField(**field_attrs) elif item_property.datatype == datatype_dict["collaborator"]: if settings.ENABLE_AUTOCOMPLETE_COLLABORATORS: if initial and item_property.key in initial: slug_value = slugify(initial[item_property.key]) initial[item_property.key] = slug_value username = slug_value widget_class = u"user_autocomplete %s" % username else: widget_class = u"user_autocomplete" widget = forms.TextInput(attrs={ "class": widget_class, }) field_attrs["widget"] = widget field_attrs["initial"] = "" field = forms.CharField(**field_attrs) else: collaborators = [(u'', NULL_OPTION)] owner = graph.owner.username collaborators.append((owner, owner)) collaborators.extend([ (collaborator.username, collaborator.username) for collaborator in graph.get_collaborators() ]) collaborators.sort() field_attrs["choices"] = collaborators field_attrs["initial"] = slugify(field_attrs["initial"] or "") if initial and item_property.key in initial: slug_value = slugify(initial[item_property.key]) initial[item_property.key] = slug_value field = forms.ChoiceField(**field_attrs) else: field = forms.CharField(**field_attrs) self.fields[item_property.key] = field if initial and ITEM_FIELD_NAME in initial: self.item_id = initial[ITEM_FIELD_NAME] field_attrs = { "required": True, "initial": self.item_id, "label": "", "widget": forms.HiddenInput(), } field = forms.CharField(**field_attrs) self.fields[ITEM_FIELD_NAME] = field
class TPOFactFindForm(forms.Form): MARITAL_STATUS = ( ('not_disclosed', 'Not Disclosed'), ('single', 'Single'), ('married', 'Married/Civil Partner'), ('divorced', 'Divorced/Person whose Civil Partnership has been dissolved'), ('widowed', 'Widowed/Surviving Civil Partner'), ('seperated', 'Separated'), ) EMPLOYMENT_STATUS = ( ('not_disclosed', 'Not Disclosed or Not Applicable'), ('not_employed', 'Not Employed'), ('worker', 'Worker'), ('employee', 'Employee'), ('self_employed', 'Self-employed or Contractor'), ('retired', 'Retired'), ('director', 'Director'), ('office_holder', 'Office Holder'), ) ANNUAL_INCOME = ( ('0', 'None'), ('<50k', '£0 - £50k'), ('50k - 150k', '£50k - £150k'), ('150k+', '£150k+'), ) TOTAL_ASSETS = ( ('0', 'None'), ('<250k', '£0 - £250k'), ('250k - 1m', '£250k - £1million'), ('1m+', '£1million+'), ) name = forms.CharField(label='Full name') address = forms.CharField(widget=forms.Textarea(attrs={'rows': '3', 'style': 'max-width: 100%;'})) office_number = forms.CharField() home_number = forms.CharField() mobile_number = forms.CharField() email = forms.EmailField() dob = forms.CharField(label='Date of Birth') marital_status = forms.ChoiceField(choices=MARITAL_STATUS) employment_status = forms.ChoiceField(choices=EMPLOYMENT_STATUS, help_text='<a href="https://www.gov.uk/employment-status/overview" target="_blank">Definition of employment status</a>') partner_employment_status = forms.ChoiceField(choices=EMPLOYMENT_STATUS, help_text='<a href="https://www.gov.uk/employment-status/overview" target="_blank">Definition of employment status</a>') occupation = forms.CharField() partner_occupation = forms.CharField() total_asset_value = forms.ChoiceField(choices=TOTAL_ASSETS, label='Your assets value') partner_total_asset_value = forms.ChoiceField(choices=TOTAL_ASSETS, label='Partners assets value') joint_total_asset_value = forms.ChoiceField(choices=TOTAL_ASSETS,label='Joint assets value') total_income = forms.ChoiceField(choices=ANNUAL_INCOME, label='Your income') partner_total_income = forms.ChoiceField(choices=ANNUAL_INCOME, label='Partners income') joint_total_income = forms.ChoiceField(choices=ANNUAL_INCOME, label='Joint income') protection = forms.BooleanField(required=False) retirement_planning = forms.BooleanField(required=False) estate_planning = forms.BooleanField(required=False) investment_planning = forms.BooleanField(required=False) def __init__(self, *args, **kwargs): super(TPOFactFindForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Fieldset( 'Section 1: Please outline which service areas you would like to discuss with one of our qualified Advisers', Div( 'protection', css_class='col-md-3' ), Div( 'retirement_planning', css_class='col-md-3' ), Div( 'investment_planning', css_class='col-md-3' ), Div( 'estate_planning', css_class='col-md-3' ), ), Fieldset( 'Section 2: Employment details', Div( 'employment_status', css_class='col-md-6' ), Div( 'partner_employment_status', css_class='col-md-6' ), Div( 'occupation', css_class='col-md-6' ), Div( 'partner_occupation', css_class='col-md-6' ), ), Fieldset( 'Section 3: Assets (Including cash savings, excluding property)', Div( 'total_asset_value', css_class='col-md-4' ), Div( 'partner_total_asset_value', css_class='col-md-4' ), Div( 'joint_total_asset_value', css_class='col-md-4' ), ), Fieldset( 'Section 4: Income (per annum)', Div( 'total_income', css_class='col-md-4' ), Div( 'partner_total_income', css_class='col-md-4' ), Div( 'joint_total_income', css_class='col-md-4' ), ), Fieldset( 'Section 5: Contact details', Div( 'name', css_class='col-md-6' ), Div( 'email', css_class='col-md-6' ), 'address', Div( 'office_number', css_class='col-md-4' ), Div( 'home_number', css_class='col-md-4' ), Div( 'mobile_number', css_class='col-md-4' ), ), Fieldset( 'Section 6: Personal infomation', Div( 'dob', css_class='col-md-6' ), Div( 'marital_status', css_class='col-md-6' ), ), Submit('Submit Enquiry', 'Submit Enquiry', css_class='pull-right') )
class EventMemberForm(forms.Form): # ref: https://stackoverflow.com/questions/9993939/django-display-values-of-the-selected-multiple-choice-field-in-a-template def selected_memberships_labels(self): return [ label for value, label in self.fields["memberships"].choices if value in self["memberships"].value() ] academic = forms.CharField( widget=forms.TextInput( attrs={ "class": "block w-full p-3 mt-2 text-gray-700 bg-gray-200 appearance-none focus:outline-none focus:bg-gray-300 focus:shadow-inner" }), required=False, ) firstname = forms.CharField( widget=forms.TextInput( attrs={ "class": "block w-full p-3 mt-2 text-gray-700 bg-gray-200 appearance-none focus:outline-none focus:bg-gray-300 focus:shadow-inner" }), required=True, ) lastname = forms.CharField( widget=forms.TextInput( attrs={ "class": "block w-full p-3 mt-2 text-gray-700 bg-gray-200 appearance-none focus:outline-none focus:bg-gray-300 focus:shadow-inner" }), required=True, ) address_line = forms.CharField( widget=forms.TextInput( attrs={ "class": "block w-full p-3 mt-2 text-gray-700 bg-gray-200 appearance-none focus:outline-none focus:bg-gray-300 focus:shadow-inner" }), required=False, ) company = forms.CharField( widget=forms.TextInput( attrs={ "class": "block w-full p-3 mt-2 text-gray-700 bg-gray-200 appearance-none focus:outline-none focus:bg-gray-300 focus:shadow-inner" }), required=True, ) street = forms.CharField( widget=forms.TextInput( attrs={ "class": "block w-full p-3 mt-2 text-gray-700 bg-gray-200 appearance-none focus:outline-none focus:bg-gray-300 focus:shadow-inner" }), required=True, ) city = forms.CharField( widget=forms.TextInput( attrs={ "class": "block w-full p-3 mt-2 text-gray-700 bg-gray-200 appearance-none focus:outline-none focus:bg-gray-300 focus:shadow-inner" }), required=True, ) state = forms.CharField( widget=forms.TextInput( attrs={ "class": "block w-full p-3 mt-2 text-gray-700 bg-gray-200 appearance-none focus:outline-none focus:bg-gray-300 focus:shadow-inner" }), label="Land", required=False, ) country = CountryField().formfield(widget=CountrySelectWidget( attrs={ "class": "mt-1 block w-full p-3 text-gray-700 bg-gray-200 focus:outline-none focus:bg-gray-300 sm:text-sm " })) postcode = forms.CharField( widget=forms.TextInput( attrs={ "class": "block w-full p-3 mt-2 text-gray-700 bg-gray-200 appearance-none focus:outline-none focus:bg-gray-300 focus:shadow-inner" }), required=True, ) email = forms.EmailField( widget=forms.EmailInput( attrs={ "class": "block w-full p-3 mt-2 text-gray-700 bg-gray-200 appearance-none focus:outline-none focus:bg-gray-300 focus:shadow-inner" }), required=True, ) phone = forms.CharField( widget=forms.TextInput( attrs={ "class": "block w-full p-3 mt-2 text-gray-700 bg-gray-200 appearance-none focus:outline-none focus:bg-gray-300 focus:shadow-inner" }), required=True, ) vfll = forms.BooleanField( widget=forms.CheckboxInput(attrs={"class": "form-radio"}), required=False) memberships = forms.MultipleChoiceField( widget=forms.CheckboxSelectMultiple( attrs={"class": "text-xs text-gray-600"}), choices=MEMBERSHIP_CHOICES, required=False, ) attention = forms.MultipleChoiceField( widget=forms.CheckboxSelectMultiple( attrs={"class": "text-xs text-gray-600"}), choices=ATTENTION_CHOICES, required=False, ) attention_other = forms.CharField( max_length=64, widget=forms.TextInput( attrs={ "class": "block w-full text-gray-700 bg-gray-200 appearance-none focus:outline-none focus:bg-gray-300 focus:shadow-inner" }), required=False, ) education_bonus = forms.BooleanField( widget=forms.CheckboxInput(attrs={"class": "form-radio"}), required=False) message = forms.CharField(label="Anmerkungen", widget=forms.Textarea, required=False) free_text_field = forms.CharField( widget=forms.Textarea( attrs={ "class": "block w-full p-3 mt-2 text-gray-700 bg-gray-200 appearance-none focus:outline-none focus:bg-gray-300 focus:shadow-inner" }), required=False, ) check = forms.BooleanField( widget=forms.CheckboxInput(attrs={"class": "form-radio"}), required=False)
def __init__(self, *args, **kwargs): """ Takes additional keyword arguments: :param category: The category to choose from :param event: The event this belongs to :param subevent: The event the parent cart position belongs to :param initial: The current set of add-ons :param quota_cache: A shared dictionary for quota caching :param item_cache: A shared dictionary for item/category caching """ category = kwargs.pop('category') event = kwargs.pop('event') subevent = kwargs.pop('subevent') current_addons = kwargs.pop('initial') quota_cache = kwargs.pop('quota_cache') item_cache = kwargs.pop('item_cache') self.price_included = kwargs.pop('price_included') self.sales_channel = kwargs.pop('sales_channel') super().__init__(*args, **kwargs) if subevent: item_price_override = subevent.item_price_overrides var_price_override = subevent.var_price_overrides else: item_price_override = {} var_price_override = {} ckey = '{}-{}'.format(subevent.pk if subevent else 0, category.pk) if ckey not in item_cache: # Get all items to possibly show items = category.items.filter_available( channel=self.sales_channel, allow_addons=True).select_related('tax_rule').prefetch_related( Prefetch('quotas', to_attr='_subevent_quotas', queryset=event.quotas.filter(subevent=subevent)), Prefetch('variations', to_attr='available_variations', queryset=ItemVariation.objects.filter( active=True, quotas__isnull=False).prefetch_related( Prefetch( 'quotas', to_attr='_subevent_quotas', queryset=event.quotas.filter( subevent=subevent))).distinct()), ).annotate(quotac=Count('quotas'), has_variations=Count('variations')).filter( quotac__gt=0).order_by('category__position', 'category_id', 'position', 'name') item_cache[ckey] = items else: items = item_cache[ckey] for i in items: if i.has_variations: choices = [('', _('no selection'), '')] for v in i.available_variations: cached_availability = v.check_quotas(subevent=subevent, _cache=quota_cache) if v._subevent_quotas: choices.append( (v.pk, self._label(event, v, cached_availability, override_price=var_price_override.get( v.pk)), v.description)) n = i.name if i.picture: n = escape(n) n += '<br>' n += '<a href="{}" class="productpicture" data-title="{}" data-lightbox="{}">'.format( i.picture.url, escape(escape(i.name)), i.id) n += '<img src="{}" alt="{}">'.format( thumb(i.picture, '60x60^'), escape(i.name)) n += '</a>' n = mark_safe(n) field = AddOnVariationField( choices=choices, label=n, required=False, widget=AddOnRadioSelect, help_text=rich_text(str(i.description)), initial=current_addons.get(i.pk), ) if len(choices) > 1: self.fields['item_%s' % i.pk] = field else: if not i._subevent_quotas: continue cached_availability = i.check_quotas(subevent=subevent, _cache=quota_cache) field = forms.BooleanField( label=self._label(event, i, cached_availability, override_price=item_price_override.get( i.pk)), required=False, initial=i.pk in current_addons, help_text=rich_text(str(i.description)), ) self.fields['item_%s' % i.pk] = field
class CreateForm(DataFormatForm): name = forms.CharField(widget=forms.TextInput( attrs={'style': 'width:100%'})) is_active = forms.BooleanField( required=False, widget=forms.CheckboxInput(attrs={'checked': 'checked'})) host = forms.CharField( initial='http://', widget=forms.TextInput(attrs={'style': 'width:100%'})) url_path = forms.CharField( initial='/', widget=forms.TextInput(attrs={'style': 'width:70%'})) match_slash = forms.BooleanField( required=False, widget=forms.CheckboxInput(attrs={'checked': 'checked'})) merge_url_params_req = forms.BooleanField( required=False, widget=forms.CheckboxInput(attrs={'checked': 'checked'})) url_params_pri = forms.ChoiceField(widget=forms.Select()) params_pri = forms.ChoiceField(widget=forms.Select()) serialization_type = forms.ChoiceField(widget=forms.Select()) sec_tls_ca_cert_id = forms.ChoiceField(widget=forms.Select()) method = forms.CharField(widget=forms.TextInput( attrs={'style': 'width:20%'})) soap_action = forms.CharField(widget=forms.TextInput( attrs={'style': 'width:100%'})) soap_version = forms.ChoiceField(widget=forms.Select()) service = forms.ChoiceField(widget=forms.Select(attrs={ 'class': 'required', 'style': 'width:100%' })) ping_method = forms.CharField(widget=forms.TextInput( attrs={'style': 'width:20%'})) pool_size = forms.CharField(widget=forms.TextInput( attrs={'style': 'width:10%'})) timeout = forms.CharField( widget=forms.TextInput(attrs={'style': 'width:10%'}), initial=MISC.DEFAULT_HTTP_TIMEOUT) security = forms.ChoiceField(widget=forms.Select()) has_rbac = forms.BooleanField(required=False, widget=forms.CheckboxInput()) content_type = forms.CharField(widget=forms.TextInput( attrs={'style': 'width:100%'})) connection = forms.CharField(widget=forms.HiddenInput()) transport = forms.CharField(widget=forms.HiddenInput()) cache_id = forms.ChoiceField(widget=forms.Select()) cache_expiry = forms.CharField( widget=forms.TextInput(attrs={'style': 'width:20%'}), initial=0) content_encoding = forms.CharField(widget=forms.TextInput( attrs={'style': 'width:20%'})) data_formats_allowed = SIMPLE_IO.HTTP_SOAP_FORMAT http_accept = forms.CharField( widget=forms.TextInput(attrs={'style': 'width:100%'}), initial=HTTP_SOAP.ACCEPT.ANY) def __init__(self, security_list=[], sec_tls_ca_cert_list={}, cache_list=[], soap_versions=SOAP_VERSIONS, prefix=None, post_data=None, req=None): super(CreateForm, self).__init__(post_data, prefix=prefix) self.fields['url_params_pri'].choices = [] for value, label in url_params_priority: self.fields['url_params_pri'].choices.append([value, label]) self.fields['params_pri'].choices = [] for value, label in params_priority: self.fields['params_pri'].choices.append([value, label]) self.fields['serialization_type'].choices = [] for item in HTTP_SOAP_SERIALIZATION_TYPE(): self.fields['serialization_type'].choices.append( [item.id, item.name]) self.fields['soap_version'].choices = [] for name in sorted(soap_versions): self.fields['soap_version'].choices.append([name, name]) self.fields['sec_tls_ca_cert_id'].choices = [] self.fields['sec_tls_ca_cert_id'].choices.append(INITIAL_CHOICES) self.fields['sec_tls_ca_cert_id'].choices.append( [ZATO_NONE, 'Skip validation']) for value, label in sec_tls_ca_cert_list.items(): self.fields['sec_tls_ca_cert_id'].choices.append([value, label]) self.fields['ping_method'].initial = DEFAULT_HTTP_PING_METHOD self.fields['pool_size'].initial = DEFAULT_HTTP_POOL_SIZE add_security_select(self, security_list) add_services(self, req) add_select(self, 'cache_id', cache_list)
class LayerStyleUploadForm(forms.Form): layerid = forms.IntegerField() name = forms.CharField(required=False) update = forms.BooleanField(required=False) sld = forms.FileField()
class UserForm(forms.ModelForm): is_manager = forms.BooleanField(required=False, label=_("Manager")) is_grade_publisher = forms.BooleanField(required=False, label=_("Grade publisher")) is_reviewer = forms.BooleanField(required=False, label=_("Reviewer")) is_inactive = forms.BooleanField(required=False, label=_("Inactive")) courses_participating_in = forms.ModelMultipleChoiceField(None, required=False, label=_("Courses participating in (active semester)")) class Meta: model = UserProfile fields = ('username', 'title', 'first_name', 'last_name', 'email', 'delegates', 'cc_users') field_classes = { 'delegates': UserModelMultipleChoiceField, 'cc_users': UserModelMultipleChoiceField, } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) courses_in_active_semester = Course.objects.filter(semester=Semester.active_semester()) excludes = [x.id for x in courses_in_active_semester if x.is_single_result] courses_in_active_semester = courses_in_active_semester.exclude(id__in=excludes) self.fields['courses_participating_in'].queryset = courses_in_active_semester if self.instance.pk: self.fields['courses_participating_in'].initial = courses_in_active_semester.filter(participants=self.instance) self.fields['is_manager'].initial = self.instance.is_manager self.fields['is_grade_publisher'].initial = self.instance.is_grade_publisher self.fields['is_reviewer'].initial = self.instance.is_reviewer self.fields['is_inactive'].initial = not self.instance.is_active def clean_username(self): username = self.cleaned_data.get('username') user_with_same_name = UserProfile.objects.filter(username__iexact=username) # make sure we don't take the instance itself into account if self.instance and self.instance.pk: user_with_same_name = user_with_same_name.exclude(pk=self.instance.pk) if user_with_same_name.exists(): raise forms.ValidationError(_("A user with the username '%s' already exists") % username) return username.lower() def clean_courses_participating_in(self): courses_participating_in = self.cleaned_data.get('courses_participating_in') if self.instance.pk: courses_voted_for = self.instance.courses_voted_for.filter(semester=Semester.active_semester()) removed_courses_voted_for = set(courses_voted_for) - set(courses_participating_in) if removed_courses_voted_for: names = [str(course) for course in removed_courses_voted_for] self.add_error("courses_participating_in", _("Courses for which the user already voted can't be removed: %s") % ", ".join(names)) return courses_participating_in def clean_email(self): email = self.cleaned_data.get('email') if email is None: return user_with_same_email = UserProfile.objects.filter(email__iexact=email) # make sure we don't take the instance itself into account if self.instance and self.instance.pk: user_with_same_email = user_with_same_email.exclude(pk=self.instance.pk) if user_with_same_email.exists(): raise forms.ValidationError(_("A user with the email '%s' already exists") % email) return email.lower() def save(self, *args, **kw): super().save(*args, **kw) new_course_list = list(self.instance.courses_participating_in.exclude(semester=Semester.active_semester())) + list(self.cleaned_data.get('courses_participating_in')) self.instance.courses_participating_in.set(new_course_list) manager_group = Group.objects.get(name="Manager") grade_publisher_group = Group.objects.get(name="Grade publisher") reviewer_group = Group.objects.get(name="Reviewer") if self.cleaned_data.get('is_manager'): self.instance.groups.add(manager_group) else: self.instance.groups.remove(manager_group) if self.cleaned_data.get('is_grade_publisher'): self.instance.groups.add(grade_publisher_group) else: self.instance.groups.remove(grade_publisher_group) if self.cleaned_data.get('is_reviewer') and not self.cleaned_data.get('is_manager'): self.instance.groups.add(reviewer_group) else: self.instance.groups.remove(reviewer_group) self.instance.is_active = not self.cleaned_data.get('is_inactive') self.instance.save()
class DeletePostForm(forms.Form): delete_confirm = forms.BooleanField( initial=False, label="Please confirm that you wish to delete this post.")
class ChangeGeneralSettingsForm(ChangeSettingsForm): settings = [ "forum_name", "forum_address", "index_header", "index_title", "index_meta_description", "logo", "logo_small", "logo_text", "og_image", "og_image_avatar_on_profile", "og_image_avatar_on_thread", "forum_footnote", "email_footer", ] forum_name = forms.CharField(label=_("Forum name"), min_length=2, max_length=255) forum_address = forms.URLField(label=_("Forum address"), max_length=255) index_header = forms.CharField( label=_("Header text"), help_text=_("This text will replace forum name in page header."), max_length=255, required=False, ) index_title = forms.CharField(label=_("Page title"), max_length=255, required=False) index_meta_description = forms.CharField( label=_("Meta Description"), help_text=_( "Short description of your forum that search and social sites may " "display next to link to your forum's index."), max_length=255, required=False, ) logo = forms.ImageField( label=_("Logo"), help_text=_("Image that will displayed in forum navbar."), required=False, ) logo_delete = forms.BooleanField(label=_("Delete logo image"), required=False) logo_small = forms.ImageField( label=_("Small logo"), help_text=_("Image that will be displayed in compact forum navbar. " "When set, it will replace icon pointing to forum index."), required=False, ) logo_small_delete = forms.BooleanField(label=_("Delete small logo image"), required=False) logo_text = forms.CharField( label=_("Text"), help_text= _("Text displayed in forum navbar. If logo image was uploaded, text will " "be displayed right next to it. Never displayed by the compact navbar." ), max_length=255, required=False, ) og_image = forms.ImageField( label=_("Image"), help_text=_( "Custom image that will appear next to links to your forum posted on " "social sites. Facebook recommends that this image should be " "1200 pixels wide and 630 pixels tall."), required=False, ) og_image_delete = forms.BooleanField(label=_("Delete image"), required=False) og_image_avatar_on_profile = YesNoSwitch( label=_("Replace image with avatar on user profiles")) og_image_avatar_on_thread = YesNoSwitch( label=_("Replace image with avatar on threads")) forum_footnote = forms.CharField( label=_("Forum footnote"), help_text=_("Short message displayed in forum footer."), max_length=300, required=False, ) email_footer = forms.CharField( label=_("E-mails footer"), help_text= _("Optional short message included at the end of e-mails sent by forum." ), max_length=255, required=False, ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) address = self.request.build_absolute_uri("/") self["forum_address"].help_text = _( "Misago uses this setting to build links in e-mails sent to site " 'users. Address under which site is running appears to be "%(address)s".' ) % { "address": address } def clean_forum_address(self): return self.cleaned_data["forum_address"].lower()
class DeleteCommentForm(forms.Form): delete_confirm = forms.BooleanField( initial=False, label="Delete comment?", )
class ManualMode(Form): water_pump = forms.BooleanField(required=False) solenoid_valve_ph = forms.BooleanField(required=False) solenoid_valve_conduct = forms.BooleanField(required=False) begin = forms.TimeField(required=False) end = forms.TimeField(required=False)
class UserCreationForm(forms.ModelForm): password1 = forms.CharField( label='비밀번호', widget=forms.PasswordInput(attrs={'class': 'form-control'})) password2 = forms.CharField( label='비밀번호 확인', widget=forms.PasswordInput(attrs={ 'class': 'form-control', 'placeholder': '비밀번호를 한번 더 입력해주세요.' })) agree = forms.BooleanField(label='동의') CHOICES = [('토', '21(토)'), ('일', '22(일)'), ('양일', '모두 가능')] interview_date = forms.CharField(label='면접가능 날짜', widget=forms.RadioSelect(choices=CHOICES)) class Meta: model = User fields = ('email', 'student_id', 'department', 'department2', 'name', 'phone', 'interview_date') widgets = { 'email': forms.TextInput(attrs={'class': 'form-control'}), 'name': forms.TextInput(attrs={'class': 'form-control'}), 'student_id': forms.TextInput(attrs={'class': 'form-control'}), 'department': forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': '경영학과' }), 'department2': forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': '생략 가능합니다.' }), 'phone': forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': '010-1234-5678' }), 'interview_date': forms.CharField( label='면접가능 날짜', widget=forms.RadioSelect( choices=[('토', '21(토)'), ('일', '22(일)'), ('양일', '모두 가능')])) } field_order = [ 'email', 'password1', 'password2', 'name', 'student_id', 'department', 'department2', 'phone', 'interview_date', 'agree' ] def clean_password2(self): password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError("비밀번호가 맞지 않습니다.") return password2 def clean_email(self): email = self.cleaned_data.get('email') try: match = User.objects.get(email=email) except User.DoesNotExist: return email raise forms.ValidationError('이미 사용중인 이메일 입니다.') def save(self, commit=True): user = super().save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() return user
class Upload_Form(forms.Form): selection = forms.ChoiceField(widget=forms.RadioSelect, choices=SELECTION, label="") verification = forms.BooleanField(required=False, label="A verifier ? ")
class ChangeSettingsForm(forms.Form): votes_public = forms.BooleanField() url = forms.URLField()
def __init__(self, *args, **kwargs): #pragma: no cover super(ChecklistFormMixin, self).__init__(*args, **kwargs) for checklist in Checklist.objects.all(): field_name = "checklist_{}".format(checklist.identifier) # required in HTML field, not required in server-side form validation self.fields[field_name] = forms.BooleanField(required=False)
class HorizontalMessageForm(forms.Form): text_input = forms.CharField() textarea = forms.CharField( widget=forms.Textarea(), ) radio_buttons = forms.ChoiceField( choices=( ('option_one', "Option one is this and that be sure to include why it's great"), ('option_two', "Option two can is something else and selecting it will deselect option one") ), widget=forms.RadioSelect, initial='option_two', ) checkboxes = forms.MultipleChoiceField( choices=( ('option_one', "Option one is this and that be sure to include why it's great"), ('option_two', 'Option two can also be checked and included in form results'), ('option_three', 'Option three can yes, you guessed it also be checked and included in form results') ), initial='option_one', widget=forms.CheckboxSelectMultiple, help_text="<strong>Note:</strong> Labels surround all the options for much larger click areas and a more usable form.", ) appended_text = forms.CharField( help_text="Here's more help text" ) appended_text2 = forms.CharField( help_text="And a bigger appended text field" ) prepended_text = forms.CharField() prepended_text_two = forms.CharField() multicolon_select = forms.MultipleChoiceField( choices=(('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5')), help_text=( 'This strange option climbing out of the box is in the examples too ' 'Only without Flexbox ' 'https://v4-alpha.getbootstrap.com/components/forms/#form-controls'), ) boolean_field = forms.BooleanField() file_field = forms.FileField() # Bootstrap4 helper = FormHelper() helper.layout = Layout( Field('text_input', css_class='form-control-lg'), Field('textarea', rows="3", css_class='form-control-lg'), Field('radio_buttons'), Field('checkboxes', style="background: #FAFAFA"), AppendedText('appended_text', '.00'), AppendedText('appended_text2', '.00', css_class='form-control-lg'), PrependedText('prepended_text', '<input type="checkbox" checked="checked" value="" id="" name="">', active=True), PrependedText('prepended_text_two', '@'), Field('multicolon_select'), Field('boolean_field'), Field('file_field'), Div( Div( Submit( 'save_changes', 'Save changes', css_class="btn-primary"), Submit('cancel', 'Cancel'), css_class='col-8 ml-auto' ), css_class='form-group row' ) ) helper.form_group_wrapper_class = 'row' helper.label_class = 'col-4' helper.field_class = 'col-8'
class WebserviceForm(DatasetForm): # Path to headers path_to_headers = forms.CharField( required=False, label=ugettext_lazy('WORKSPACE-PATHTOHEADERS-TEXT'), widget=forms.TextInput(attrs={ 'data-bind':'value:path_to_headers,events:[\'keyup\']' }) ) # Path to data path_to_data = forms.CharField( required=False, label=ugettext_lazy('WORKSPACE-PATHTODATA-TEXT'), widget=forms.TextInput(attrs={ 'data-bind':'value:path_to_data,events:[\'keyup\']' }) ) # Method Name method_name = forms.CharField( required=False, label=ugettext_lazy('WORKSPACE-METHODNAME-TEXT'), widget=forms.TextInput(attrs={ 'data-bind':'value:method_name,events:[\'keyup\']' }) ) # Name Space namespace = forms.CharField( required=False, label=ugettext_lazy('WORKSPACE-NAMESPACE-TEXT'), widget=forms.TextInput(attrs={ 'data-bind':'value:namespace,events:[\'keyup\']' }) ) # Token token = forms.CharField( required=False, label=ugettext_lazy('WORKSPACE-TOKEN-TEXT'), max_length=256, widget=forms.TextInput(attrs={ 'data-bind':'value:token,events:[\'keyup\']' }) ) # Algorithm algorithm = forms.CharField( required=False, label=ugettext_lazy('WORKSPACE-ALGORITHM-TEXT'), max_length=256, widget=forms.TextInput(attrs={ 'data-bind':'value:algorithm,events:[\'keyup\']' }) ) # Signature signature = forms.CharField( required=False, label=ugettext_lazy('WORKSPACE-SIGNATURE-TEXT'), widget=forms.TextInput(attrs={ 'data-bind':'value:signature,events:[\'keyup\']' }) ) # Use Cache use_cache = forms.BooleanField( required=False, label=ugettext_lazy('APP-CACHE-TEXT'), widget=forms.CheckboxInput(attrs={ 'data-bind':'checked:use_cache' }) ) # Attributes as Headers att_headers = forms.BooleanField( required=False, label=ugettext_lazy('APP-ATT-HEADERS-TEXT'), widget=forms.CheckboxInput(attrs={ 'data-bind':'checked:att_headers' }) ) # Username username = forms.CharField( required=False, label=ugettext_lazy('APP-USERNAME-TEXT'), widget=forms.TextInput(attrs={ 'data-bind':'value:username,events:[\'keyup\']' }) ) # Password password = forms.CharField( required=False, label=ugettext_lazy('APP-PASSWORD-TEXT'), widget=forms.PasswordInput(attrs={ 'data-bind':'value:password,events:[\'keyup\']' }) ) def __init__(self, data=None, *args, **kwargs): super(WebserviceForm, self).__init__(data, *args, **kwargs) WebserviceParamFormSet = formset_factory(WebserviceParamForm) self.param_formset = data is None and WebserviceParamFormSet(prefix='params') or WebserviceParamFormSet(data, prefix='params') self.fields['impl_type'].choices = kwargs.get('impl_type_choices', choices.WEBSERVICE_IMPLEMENTATION_CHOICES) self.fields['frequency'].choices = choices.ODATA_FREQUENCY + [("other", ugettext_lazy('APP-OTHER-TEXT'))] def is_valid(self): is_valid = super(WebserviceForm, self).is_valid() is_valid = is_valid and self.param_formset.is_valid() if not is_valid: # Django does not allow to change form.errors, so we use form._errors if self.param_formset: if self.param_formset._errors: self._errors = dict(self._errors) for error in self.param_formset._errors: self._errors.update(dict(error)) self._errors = ErrorDict(self._errors) self.cleaned_data['parameters'] = [form.cleaned_data for form in self.param_formset] if (int(self.cleaned_data['impl_type']) == choices.SourceImplementationChoices.REST and settings.PUBLICSTUFF_DOMAIN in self.cleaned_data['end_point']): self.cleaned_data['impl_type'] = choices.SourceImplementationChoices.PUS return is_valid
class CreateOrderFromDraftForm(forms.ModelForm): """Mark draft order as ready to fulfill.""" notify_customer = forms.BooleanField( label=pgettext_lazy( "Send email to customer about order created by staff users", "Send email with order confirmation to the customer", ), required=False, initial=True, ) class Meta: model = Order fields = [] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if not self.instance.get_user_current_email(): self.fields.pop("notify_customer") def clean(self): super().clean() errors = [] if self.instance.get_total_quantity() == 0: errors.append( forms.ValidationError( pgettext_lazy( "Create draft order form error", "Could not create order without any products", ))) if self.instance.is_shipping_required(): method = self.instance.shipping_method address = self.instance.address shipping_not_valid = ( method and address and address.country.code not in method.shipping_zone.countries ) # noqa if shipping_not_valid: errors.append( forms.ValidationError( pgettext_lazy( "Create draft order form error", "Shipping method is not valid for chosen shipping " "address", ))) if errors: raise forms.ValidationError(errors) return self.cleaned_data def save(self): self.instance.status = OrderStatus.UNFULFILLED if self.instance.user: self.instance.user_email = self.instance.user.email remove_address = False if not self.instance.is_shipping_required(): self.instance.shipping_method_name = None self.instance.shipping_price = zero_taxed_money() if self.instance.address: remove_address = True super().save() if remove_address: self.instance.address.delete() return self.instance
class ReviewAppForm(happyforms.Form): comments = forms.CharField(widget=forms.Textarea(), label=_lazy(u'Comments:')) canned_response = NonValidatingChoiceField(required=False) action = forms.ChoiceField(widget=forms.RadioSelect()) device_types = forms.CharField(required=False, label=_lazy(u'Device Types:')) browsers = forms.CharField(required=False, label=_lazy(u'Browsers:')) device_override = forms.TypedMultipleChoiceField( choices=[(k, v.name) for k, v in amo.DEVICE_TYPES.items()], coerce=int, label=_lazy(u'Device Type Override:'), widget=forms.CheckboxSelectMultiple, required=False) thread_perms = [('developer', _lazy('Developers')), ('reviewer', _lazy('Reviewers')), ('senior_reviewer', _lazy('Senior Reviewers')), ('staff', _lazy('Staff')), ('mozilla_contact', _lazy('Mozilla Contact'))] action_visibility = forms.TypedMultipleChoiceField( choices=thread_perms, coerce=unicode, label=_lazy('Action Visibility to Users:'), widget=forms.CheckboxSelectMultiple, required=False) notify = forms.BooleanField(required=False, label=_lazy( u'Notify me the next time the manifest is ' u'updated. (Subsequent updates will not ' u'generate an email)')) def __init__(self, *args, **kw): self.helper = kw.pop('helper') self.type = kw.pop('type', amo.CANNED_RESPONSE_APP) super(ReviewAppForm, self).__init__(*args, **kw) # We're starting with an empty one, which will be hidden via CSS. canned_choices = [['', [('', _('Choose a canned response...'))]]] responses = CannedResponse.objects.filter(type=self.type) # Loop through the actions. for k, action in self.helper.actions.iteritems(): action_choices = [[c.response, c.name] for c in responses if c.sort_group and k in c.sort_group.split(',')] # Add the group of responses to the canned_choices array. if action_choices: canned_choices.append([action['label'], action_choices]) # Now, add everything not in a group. for r in responses: if not r.sort_group: canned_choices.append([r.response, r.name]) self.fields['canned_response'].choices = canned_choices self.fields['action'].choices = [ (k, v['label']) for k, v in self.helper.actions.items() ] device_types = AddonDeviceType.objects.filter( addon=self.helper.addon).values_list('device_type', flat=True) if device_types: self.initial['device_override'] = device_types def is_valid(self): result = super(ReviewAppForm, self).is_valid() if result: self.helper.set_data(self.cleaned_data) return result
class ContributionForm(forms.ModelForm): contributor = forms.ModelChoiceField(queryset=UserProfile.objects.exclude_inactive_users()) responsibility = forms.ChoiceField(widget=forms.RadioSelect(), choices=Contribution.RESPONSIBILITY_CHOICES) course = forms.ModelChoiceField(Course.objects.all(), disabled=True, required=False, widget=forms.HiddenInput()) questionnaires = forms.ModelMultipleChoiceField( Questionnaire.objects.contributor_questionnaires().filter(obsolete=False), required=False, widget=CheckboxSelectMultiple, label=_("Questionnaires") ) does_not_contribute = forms.BooleanField(required=False, label=_("Does not contribute to course")) class Meta: model = Contribution fields = ('course', 'contributor', 'questionnaires', 'order', 'responsibility', 'textanswer_visibility', 'label') widgets = {'order': forms.HiddenInput(), 'textanswer_visibility': forms.RadioSelect(choices=Contribution.TEXTANSWER_VISIBILITY_CHOICES)} field_classes = { 'contributor': UserModelChoiceField, } def __init__(self, *args, course=None, **kwargs): self.course = course # work around https://code.djangoproject.com/ticket/25880 if self.course is None: assert 'instance' in kwargs self.course = kwargs['instance'].course super().__init__(*args, **kwargs) if self.instance.responsible: self.fields['responsibility'].initial = Contribution.IS_RESPONSIBLE elif self.instance.can_edit: self.fields['responsibility'].initial = Contribution.IS_EDITOR else: self.fields['responsibility'].initial = Contribution.IS_CONTRIBUTOR if self.instance.contributor: self.fields['contributor'].queryset |= UserProfile.objects.filter(pk=self.instance.contributor.pk) self.fields['questionnaires'].queryset = Questionnaire.objects.contributor_questionnaires().filter( Q(obsolete=False) | Q(contributions__course=self.course)).distinct() if self.instance.pk: self.fields['does_not_contribute'].initial = not self.instance.questionnaires.exists() if not self.course.can_manager_edit: # form is used as read-only course view disable_all_fields(self) def clean(self): if not self.cleaned_data.get('does_not_contribute') and not self.cleaned_data.get('questionnaires'): self.add_error('does_not_contribute', _("Select either this option or at least one questionnaire!")) def save(self, *args, **kwargs): responsibility = self.cleaned_data['responsibility'] is_responsible = responsibility == Contribution.IS_RESPONSIBLE is_editor = responsibility == Contribution.IS_EDITOR self.instance.responsible = is_responsible self.instance.can_edit = is_responsible or is_editor if is_responsible: self.instance.textanswer_visibility = Contribution.GENERAL_TEXTANSWERS return super().save(*args, **kwargs)
class NewsletterFooterForm(forms.Form): """ Form used to subscribe to a single newsletter, typically in the footer of a page (see newsletters/middleware.py) but sometimes on a dedicated page. """ email = forms.EmailField(widget=EmailInput(attrs={'required': 'required'})) # first/last_name not yet included in email_newsletter_form helper # currently used on /contribute/friends/ (custom markup) first_name = forms.CharField(widget=forms.TextInput, required=False) last_name = forms.CharField(widget=forms.TextInput, required=False) fmt = forms.ChoiceField(widget=forms.RadioSelect(renderer=SideRadios), choices=FORMATS, initial='H') privacy = forms.BooleanField(widget=PrivacyWidget) source_url = forms.CharField(required=False) newsletters = forms.CharField(widget=forms.HiddenInput, required=True, max_length=100) # has to take a newsletters argument so it can figure # out which languages to list in the form. def __init__(self, newsletters, locale, data=None, *args, **kwargs): regions = product_details.get_regions(locale) regions = sorted(regions.iteritems(), key=itemgetter(1)) try: newsletters = validate_newsletters(newsletters) except ValidationError: # replace with most common good newsletter # form validation will work with submitted data newsletters = 'mozilla-and-you' lang = locale.lower() if '-' in lang: lang, country = lang.split('-', 1) else: country = '' regions.insert(0, ('', _lazy('Select country'))) lang_choices = get_lang_choices(newsletters) languages = [x[0] for x in lang_choices] if lang not in languages: # The lang from their locale is not one that our newsletters # are translated into. Initialize the language field to no # choice, to force the user to pick one of the languages that # we do support. lang = '' lang_choices.insert(0, ('', _lazy('Available Languages'))) super(NewsletterFooterForm, self).__init__(data, *args, **kwargs) required_args = { 'required': 'required', 'aria-required': 'true', } country_widget = widgets.Select(attrs=required_args) self.fields['country'] = forms.ChoiceField(widget=country_widget, choices=regions, initial=country, required=False) lang_widget = widgets.Select(attrs=required_args) self.fields['lang'] = forms.TypedChoiceField(widget=lang_widget, choices=lang_choices, initial=lang, required=False) self.fields['newsletters'].initial = newsletters def clean_newsletters(self): return validate_newsletters(self.cleaned_data['newsletters']) def clean_source_url(self): su = self.cleaned_data['source_url'].strip() if su: # limit to 255 characters by truncation return su[:255] return su
class SignupForm(UserCreationForm): agreed_to_terms = forms.BooleanField(required=True) class Meta: model = get_user_model() fields = ('email', 'password1', 'password2', 'agreed_to_terms')