class FiltroPorValorForm(forms.Form): CHOICES_EM_CONDOMINIO = ((True, "Apenas em condomínio fechado"), ("", "Indiferente")) CHOICES_MOBILIADO = (("mobiliado", "Mobiliado"), ("nao_mobiliado", "Não Mobiliado"), ("", "Indiferente")) CHOICES_STATUS = (("publicado", "Publicado"), ("arquivado", "Arquivado")) valor_min = CustomInteger() valor_max = CustomInteger() min_quarto = CustomInteger(initial=3) min_vaga = CustomInteger(initial=2) min_banheiro = CustomInteger(initial=1) min_suite = CustomInteger(initial=1) area_min = CustomInteger(initial=180) codigo_referencia = MultipleInteger(label="Código Referência", required=False) bairros = forms.MultipleChoiceField(required=False) em_condominio = forms.ChoiceField(choices=CHOICES_EM_CONDOMINIO, widget=forms.RadioSelect(), initial=CHOICES_EM_CONDOMINIO[-1], label="Condomínio Fechado?", required=False) mobiliado = forms.ChoiceField(choices=CHOICES_MOBILIADO, widget=forms.RadioSelect(), initial=CHOICES_MOBILIADO[-1], label="Mobília", required=False) status = forms.ChoiceField(choices=CHOICES_STATUS, widget=forms.RadioSelect(), initial=CHOICES_STATUS[0], label="Status", required=False) condominio = forms.ChoiceField(widget=forms.Select(), label="Condomínio", required=False) def __init__(self, tipo_imovel=None, tipo_interesse=None, cidade=None, *args, **kwargs): super(FiltroPorValorForm, self).__init__(*args, **kwargs) qs = BairroComImoveis.objects.filter( tipo_imovel=tipo_imovel, cidade__nome=cidade).select_related('cidade', 'bairro' ) if tipo_interesse == 'comprar': qs = qs.filter(contador_venda__gt=0) self.fields["valor_min"].initial = 160000 self.fields["valor_max"].initial = 600000 else: self.fields["valor_min"].initial = 700 self.fields["valor_max"].initial = 2500 qs = qs.filter(contador_locacao__gt=0) bairro_list = [(bairro.bairro.id, bairro) for bairro in qs] bairro_list = sorted(bairro_list, key = lambda tup: tup[1].bairro.descricao) condominio_list = [('', '---------------')] condominio_list += [(condominio.id, condominio.nome) for condominio in Condominio.objects.filter(cidade__nome=cidade).select_related('cidade', )] self.fields['bairros'].widget = BairroComImoveisCheckboxSelectMultiple( attrs={'tipo_interesse': tipo_interesse}) self.fields["condominio"].choices = condominio_list self.fields["condominio"].initial = condominio_list[0] self.fields['bairros'].choices = bairro_list
class LecturerSignUpForm(UserCreationForm): # Declare user option fields to form first_name = forms.CharField(required=True, widget=forms.TextInput( attrs={'placeholder': 'First name'})) other_name = forms.CharField(required=True, widget=forms.TextInput( attrs={'placeholder': 'Other name'})) last_name = forms.CharField(required=True, widget=forms.TextInput( attrs={'placeholder': 'Surname '})) birth_place = forms.ChoiceField(required=True, choices=STATES) sex = forms.ChoiceField(required=True, choices=GENDER) birth_date = forms.DateField(required=True, widget=forms.DateInput) email = forms.EmailField(widget=forms.EmailInput( attrs={'placeholder': 'Enter email address'}), required=True) phone = forms.CharField(required=True, widget=forms.PhoneNumberInput( attrs={'placeholder': 'Mobile Number'})) address = forms.CharField(required=False, widget=forms.TextInput(attrs={'placeholder': 'House/Street/City/Town '}), max_length=100) faculty = forms.ModelChoiceField( queryset=Faculty.objects.all(), required=False) class Meta: model = User fields = ('first_name', 'other_name', 'last_name', 'sex', 'birth_place', 'address', 'phone', 'email', 'faculty', 'birth_date', 'username',) # Add placeholder to UserCreationForm fields def __init__(self, *args, **kwargs): super(LecturerSignUpForm, self).__init__(*args, **kwargs) self.fields['username'].widget.attrs.update( {'placeholder': 'Choose A Unique Username'}) self.fields['password1'].widget.attrs.update( {'placeholder': 'Choose A Password'}) self.fields['password2'].widget.attrs.update( {'placeholder': 'Verify Password'}) # Check if inputted email has not been used by another user def clean_email(self): email = self.cleaned_data['email'] check = User.objects.values('email') if email in check: msg = 'this email has been used!' self.add_error('email', msg) return email def save(self, commit=True): user = super().save(commit=False) user.is_lecturer = True if commit: user.save() # Create lecturer object with user id Lecturer.objects.create(user=user) return user
def get_ordering_field(self): if self._meta.order_by: if isinstance(self._meta.order_by, (list, tuple)): if isinstance(self._meta.order_by[0], (list, tuple)): # e.g. (('field', 'Display name'), ...) choices = [(f[0], f[1]) for f in self._meta.order_by] else: choices = [ (f, _('%s (descending)' % capfirst(f[1:])) if f[0] == '-' else capfirst(f)) for f in self._meta.order_by ] else: # add asc and desc field names # use the filter's label if provided choices = [] for f, fltr in self.filters.items(): choices.extend([ (fltr.name or f, fltr.label or capfirst(f)), ("-%s" % (fltr.name or f), _('%s (descending)' % (fltr.label or capfirst(f)))) ]) return forms.ChoiceField(label="Ordering", required=False, choices=choices)
class CloneActionForm(forms.Form): """form for clone_action: choose which type to chooses""" action_type = forms.ChoiceField(required=True, choices=[], label=_('New type')) def __init__(self, action_type, *args, **kwargs): super(CloneActionForm, self).__init__(*args, **kwargs) choices = [ (action_type.id, action_type.name) for action_type in action_type.next_action_types.all().order_by('order_index') ] self.fields['action_type'].choices = choices # If only 1 choice = change it to a confirmation if len(choices) == 1: self.fields['action_type'].initial = choices[0][0] self.fields['action_type'].widget = forms.HiddenInput() self.single_choice = True self.action_type_name = choices[0][1] else: self.single_choice = False self.action_type_name = '' def clean_action_type(self): action_type = self.cleaned_data['action_type'] try: return models.ActionType.objects.get(id=action_type) except models.ActionType.DoesNotExist: raise forms.ValidationError(_("Invalid type"))
class ActionForm(forms.Form): action = forms.ChoiceField(label=_('Action'), choices=()) objects = forms.ModelMultipleChoiceField(queryset=None, widget=forms.MultipleHiddenInput, required=False) def __init__(self, *args, **kwargs): self.actions = kwargs.pop('actions') self.queryset = kwargs.pop('queryset') super(ActionForm, self).__init__(*args, **kwargs) self.fields['action'].choices = self.get_action_choices() self.fields['objects'].queryset = self.queryset def get_action_choices(self): return [('', _(u'Select an action …'))] + [ (key, action.name) for key, action in self.actions.items() ] def get_selected_queryset(self): return self.cleaned_data['objects'] def perform_action(self, backend, request): action_slug = self.cleaned_data['action'] action = self.actions[action_slug] queryset = self.get_selected_queryset() action.perform(backend, request, queryset)
class UndoReadForm(forms.Form): action = forms.ChoiceField( choices=( ('undo-read', 'undo-read'), ), widget=forms.HiddenInput, initial='undo-read', ) pks = forms.CharField(widget=forms.HiddenInput) def __init__(self, user=None, *args, **kwargs): self.user = user super(UndoReadForm, self).__init__(*args, **kwargs) def clean_pks(self): return json.loads(self.cleaned_data['pks']) def save(self): pks = self.cleaned_data['pks'] index = es.user_alias(self.user.pk) ops = [{ '_op_type': 'update', '_index': index, '_type': 'entries', '_id': pk, 'doc': {'read': False}, } for pk in pks] with es.ignore_bulk_error(404, 409): es.bulk(ops, raise_on_error=True, params={'refresh': True}) return len(pks)
def __init__(self, *args, **kwargs): super(PdfTemplateForm, self).__init__(*args, **kwargs) if getattr(settings, 'BALAFON_PDF_TEMPLATES', None): choices = settings.BALAFON_PDF_TEMPLATES else: choices = ( ('pdf/labels_24.html', _('etiquettes 24')), ('pdf/labels_21.html', _('etiquettes 21')), ('pdf/agipa_21.html', _('Agipa 21')), ('pdf/labels_16.html', _('etiquettes 16')), ('pdf/address_strip.html', _('bande adresse')), ) self.fields['template'] = forms.ChoiceField( choices=choices, required=True, label=_('template'), help_text=_('Select the type of document to generate') ) self.fields['template'].widget.attrs.update({'class': 'form-control'}) extra_fields = getattr(settings, 'BALAFON_PDF_FORM_EXTRA_FIELDS', None) if extra_fields: for field_name, field_label, initial_value in extra_fields: self.fields[field_name] = forms.CharField(label=field_label, initial=initial_value) self.fields[field_name].widget.attrs.update({'class': 'form-control'})
class RadioForm(forms.Form): numbers = forms.ChoiceField(choices=( ('1', '1'), ('2', '2'), ('3', '3'), ), widget=otree.forms.RadioSelectHorizontal)
class FeedbackForm(forms.ModelForm): class Meta: model = Feedback fields = '__all__' severity = forms.ChoiceField( label="Priority", choices=(("High", "High"), ("Medium", "Medium"), ("Low", "Low")), widget=forms.Select, initial='2', required=True, ) helper = FormHelper() helper.form_method = 'post' helper.form_class = 'form-horizontal' helper.label_class = 'col-sm-2' helper.field_class = 'col-sm-6' helper.form_error_title = 'Form Errors' helper.error_text_inline = True helper.help_text_inline = True helper.html5_required = True helper.layout = Layout( Fieldset('', 'submitter', 'note', 'page', 'severity'), Submit('submit', 'Submit', css_class='btn-default'), Reset('reset', 'Reset', css_class='btn-warning'))
def __init__(self, *args, **kwargs): """Accepts ``environments`` queryset and ``current`` env id.""" environments = kwargs.pop("environments", []) current = kwargs.pop("current", None) super(EnvironmentSelectionForm, self).__init__(*args, **kwargs) # list of categories, ordered by name self.categories = [] # maps category to set of elements self.elements_by_category = {} # maps environment ID to list of element IDs, ordered by category self.elementids_by_envid = {} # elements in current environment current_elements = [] env_element_through_model = model.Environment.elements.through env_element_relationships = env_element_through_model.objects.filter( environment__in=environments).select_related() # first construct the ordered list of categories (and current elements) cat_set = set() for ee in env_element_relationships: cat_set.add(ee.element.category) if ee.environment.id == current: current_elements.append(ee.element) self.categories = sorted(cat_set, key=lambda c: c.name) num_categories = len(self.categories) # populate elements by category and environment for ee in env_element_relationships: byenv = self.elementids_by_envid.setdefault( ee.environment.id, [None] * num_categories) category_index = self.categories.index(ee.element.category) byenv[category_index] = ee.element.id bycat = self.elements_by_category.setdefault( ee.element.category, set()) bycat.add(ee.element) # construct choice-field for each env type for category in self.categories: self.fields["category_{0}".format( category.id)] = forms.ChoiceField( choices=[("", "---------")] + [(e.id, e.name) for e in sorted(self.elements_by_category[category], key=lambda e: e.name)], label=category.name, required=False) # set initial data based on current user environment for element in current_elements: field_name = "category_{0}".format(element.category.id) self.initial[field_name] = element.id
class ReadForm(forms.Form): READ_ALL = 'read-all' READ_PAGE = 'read-page' action = forms.ChoiceField( choices=( (READ_ALL, 'read all'), (READ_PAGE, 'read page'), ), widget=forms.HiddenInput, initial='read-all', ) def __init__(self, es_entries=None, feed=None, category=None, user=None, pages_only=False, *args, **kwargs): self.es_entries = es_entries self.feed = feed self.category = category self.user = user self.pages_only = pages_only super().__init__(*args, **kwargs) if self.pages_only: self.fields['entries'] = forms.CharField(widget=forms.HiddenInput) def clean_entries(self): return json.loads(self.cleaned_data['entries']) def save(self): index = es.user_alias(self.user.pk) if self.pages_only: pks = self.cleaned_data['entries'] else: # Fetch all IDs for current query. entries = self.es_entries.filter(read=False).aggregate('id').fetch( per_page=0) pks = [ bucket['key'] for bucket in entries['aggregations']['entries'] ['query']['id']['buckets'] ] ops = [{ '_op_type': 'update', '_index': index, '_type': 'entries', '_id': pk, 'doc': { 'read': True }, } for pk in pks] if pks: with es.ignore_bulk_error(404, 409): es.bulk(ops, raise_on_error=True, params={'refresh': True}) return pks
def __init__(self, *args, **kwargs): super(YesNoSearchFieldForm, self).__init__(*args, **kwargs) choices = ( (1, _('Yes')), (0, _('No')), ) field = forms.ChoiceField(choices=choices, label=self.label) self._add_field(field)
class ActionForm(forms.Form): action = forms.ChoiceField(choices=( ('images', 'images'), ('unread', 'unread'), ('read_later', 'read_later'), ('star', 'star'), ('unstar', 'unstar'), ))
class AddExtraSaleForm(BetterBsForm): """A form for adding a new extra sale""" analysis_code = forms.ChoiceField(label=_('Analysis code'), required=True) amount = forms.DecimalField(max_digits=9, decimal_places=2, required=True, label=_('Amount')) vat_rate = forms.ChoiceField(label=_('VAT rate'), required=True) date = forms.DateField(label=_('Date'), required=True) def __init__(self, *args, **kwargs): super(AddExtraSaleForm, self).__init__(*args, **kwargs) self.valid_action_types = [ item.action_type for item in StoreManagementActionType.objects.all() ] self.fields['analysis_code'].choices = [ (analysis_code.id, analysis_code.name) for analysis_code in SaleAnalysisCode.objects.filter( action_type__in=self.valid_action_types) ] self.fields['vat_rate'].choices = [ (vat_rate.id, vat_rate.name) for vat_rate in VatRate.objects.all() ] self.fields['date'].initial = date.today() def clean_analysis_code(self): """validate the analysis code""" analysis_code_id = self.cleaned_data['analysis_code'] try: return SaleAnalysisCode.objects.get( id=analysis_code_id, action_type__in=self.valid_action_types) except SaleAnalysisCode.DoesNotExist: forms.ValidationError(ugettext('Invalid analysis code')) def clean_vat_rate(self): """validate the analysis code""" vat_rate_id = self.cleaned_data['vat_rate'] try: return VatRate.objects.get(id=vat_rate_id) except VatRate.DoesNotExist: forms.ValidationError(ugettext('Invalid analysis code'))
def __init__(self, recipe, *args, **kwargs): super(SubRecipeSelectForm, self).__init__(*args, **kwargs) self.fields['subrecipe'] = forms.ChoiceField( choices=[(sr.pk, sr.title) for sr in recipe.subrecipe_set.all()], label=_("Parte"), ) self.helper = FormHelper() self.helper.form_class = 'form-inline' self.helper.form_id = 'select-subrecipe-form'
class FormWithCity(BetterBsForm, _CityBasedForm): """Form with city""" country = forms.ChoiceField(required=False, label=_('Country')) zip_code = forms.CharField(required=False, label=_('zip code')) city = forms.CharField(required=False, label=_('City')) def __init__(self, *args, **kwargs): super(FormWithCity, self).__init__(*args, **kwargs) self._post_init(*args, **kwargs)
def __init__(self, *args, **kwargs): super(BuscaInicialForm, self).__init__(*args, **kwargs) self.fields['tipo_interesse'] = forms.ChoiceField( choices=InteresseBase.TIPOS_INTERESSE) self.fields['tipo_interesse'].label = "Interesse" self.fields['tipo_imovel'] = forms.ChoiceField( choices=tuple(Imovel.TIPO_IMOVEL)) self.fields['tipo_imovel'].label = "Tipo do imóvel" cidades_qs = Cidade.objects.all() cidade_list = [(cidade.nome, cidade.nome) for cidade in cidades_qs] self.fields['cidade'] = forms.ChoiceField( choices=cidade_list) opcoes_list = (('residencial', 'Residencial'), ('comercial', 'Comercial'), ) self.fields['residencial_comercial'] = forms.ChoiceField( label='', choices=tuple(opcoes_list), initial='residencial', widget=RadioSelect())
class ExamQuestionForm(forms.ModelForm): type = forms.ChoiceField(required=True, choices=TYPES, widget=forms.RadioSelect) text = forms.CharField(required=True, widget=forms.Textarea( attrs={'rows': 2, 'placeholder': 'Enter your Question.'}), max_length=4000, help_text='The max length of the question is 4000.') class Meta: model = ExamQuestion fields = ('text', 'type')
def __init__(self, foirequest, *args, **kwargs): super(FoiRequestStatusForm, self).__init__(*args, **kwargs) self.foirequest = foirequest self.fields['refusal_reason'] = forms.ChoiceField( label=_("Refusal Reason"), choices=[('', _('No or other reason given'))] + (foirequest.law.get_refusal_reason_choices()), required=False, widget=forms.Select(attrs={'class': 'form-control'}), help_text= _('When you are (partially) denied access to information, the Public Body should always state the reason.' ))
def __init__(self, user, *args, **kwargs): self.user = user super(DwollaPaymentForm, self).__init__(*args, **kwargs) event = self.order.event dwolla_obj = self.user if self.user.is_authenticated() else self.order self.dwolla_account = dwolla_obj.get_dwolla_account(event.api_type) if self.dwolla_account and self.dwolla_account.is_connected(): self.sources = dwolla_get_sources(self.dwolla_account, event) source_choices = [(source['Id'], source['Name']) for source in self.sources] self.fields['source'] = forms.ChoiceField(choices=source_choices, initial="Balance")
class AttendeeFilterSetForm(forms.Form): ORDERING_CHOICES = ( ("last_name", "Last Name"), ("-last_name", "Last Name (descending)"), ("first_name", "First Name"), ("-first_name", "First Name (descending)"), ("-purchase_date", "Purchase Date (newest first)"), ) HOUSING_STATUS_CHOICES = ( ("", "---------"), ) + Attendee.HOUSING_STATUS_CHOICES # TODO: Automatically generate fields from the parent filterset. bought_items__item_option = GroupedModelChoiceField( label="Bought Item", queryset=ItemOption.objects.all(), group_by_field="item", group_label=lambda x: x.name, required=False, ) bought_items__discounts__discount = forms.ModelChoiceField( label="Discount", queryset=Discount.objects.all(), required=False) housing_status = forms.ChoiceField(label="Housing Status", choices=HOUSING_STATUS_CHOICES, required=False) o = forms.ChoiceField(label="Sort by", choices=ORDERING_CHOICES, required=False) def __init__(self, event, *args, **kwargs): self.event = event super(AttendeeFilterSetForm, self).__init__(*args, **kwargs) option_qs = ItemOption.objects.filter( item__event=self.event).select_related('item') self.fields['bought_items__item_option'].queryset = option_qs self.fields['bought_items__item_option'].empty_label = 'Any Items' discount_qs = Discount.objects.filter(event=self.event) self.fields['bought_items__discounts__discount'].queryset = discount_qs self.fields[ 'bought_items__discounts__discount'].empty_label = 'Any Discounts'
class TmaForm(forms.ModelForm): title = forms.ChoiceField(choices=TMA, required=True) class Meta: model = Tma fields = ['title', 'course'] # Filter Tma courses list for appointed lecturer def __init__(self, *args, **kwargs): self.request = kwargs.pop("request") super().__init__(*args, **kwargs) self.fields["course"].queryset = Course.objects.filter( lecturer=self.request.user.lecturer)
class ModelFormWithCity(BetterBsModelForm, _CityBasedForm): """ModelForm with city""" city = forms.CharField( required=False, label=_('City'), widget=CityAutoComplete(attrs={ 'placeholder': _('Enter a city'), 'size': '80' })) country = forms.ChoiceField(required=False, label=_('Country')) def __init__(self, *args, **kwargs): super(ModelFormWithCity, self).__init__(*args, **kwargs) self._post_init(*args, **kwargs)
class BasicForm(forms.Form): """ TODO:-------------------------- input TextInput OK inputN NumberInput OK inputEmail EmailInput textarea TextInput OK drowpdown Select OK drowpdown SelectMultiple OK checkbox CheckboxInput checkbox2 MultiCheckbox? radiobox RadioSelect date DateInput time TimeInput datetime DateTimeInput """ COLORS_CHOICES = [ ('blue', 'Blue'), ('green', 'Green'), ('black', 'Black'), ] name = forms.CharField(max_length=32, widget=widgets.TextInput()) year = forms.IntegerField(widget=widgets.NumberInput()) description = forms.CharField(max_length=32, widget=widgets.Textarea(attrs={'rows': '4'})) color = forms.ChoiceField(widget=widgets.Select(), choices=COLORS_CHOICES) colors = forms.MultipleChoiceField(widget=widgets.Select(attrs={'multiple': True}), choices=COLORS_CHOICES) is_boolean = forms.CharField(max_length=32, widget=widgets.CheckboxInput()) option = forms.ChoiceField(widget=widgets.RadioSelect(), choices=COLORS_CHOICES) is_not_boolean = forms.CharField(max_length=32, widget=widgets.CheckboxInput()) option_again = forms.CharField(max_length=32, widget=widgets.CheckboxInput()) def __init__(self, *args, **kwargs): super(BasicForm, self).__init__(*args, **kwargs) self.fields["year"].initial = 2021
def __init__(self, queryset, *args, **kwargs): super(PublicBodySuggestionsForm, self).__init__(*args, **kwargs) self.fields['suggestion'] = forms.ChoiceField( label=_("Suggestions"), widget=forms.RadioSelect, choices= ((s.public_body.id, mark_safe( '''%(name)s - <a class="info-link" href="%(url)s">%(link)s</a><br/> <span class="help">%(reason)s</span>''' % { "name": escape(s.public_body.name), "url": s.public_body.get_absolute_url(), "link": _("More Info"), "reason": _("Reason for this suggestion: %(reason)s") % { "reason": escape(s.reason) } })) for s in queryset))
class SubscriptionForm(forms.Form): subscribe = forms.BooleanField(label=_('Subscribe?'), required=False) name = forms.CharField(label=_('Name'), required=False) url = forms.URLField(label=_('URL')) category = forms.ChoiceField(label=_('Category'), required=False) def clean_url(self): url = self.cleaned_data['url'] if (self.cleaned_data.get('subscribe', False) and self.user.feeds.filter(url=url).exists()): raise forms.ValidationError( _("You are already subscribed to this feed.")) return url def clean_name(self): if (self.cleaned_data.get('subscribe', False) and not self.cleaned_data['name']): raise forms.ValidationError(_('This field is required.')) return self.cleaned_data['name']
class SubscribeContactsAdminForm(SearchActionForm): """This form is used for superuser forcing newsletter subscription""" subscription_type = forms.ChoiceField(required=True) subscribe = forms.BooleanField( required=False, label=_('Subscribe'), help_text=_('It will subscribe/unsubscribe all selected contacts') ) def __init__(self, *args, **kwargs): super(SubscribeContactsAdminForm, self).__init__(*args, **kwargs) self.fields['subscription_type'].choices = [ (subscription_type.id, subscription_type.name) for subscription_type in SubscriptionType.objects.all() ] def clean_subscription_type(self): try: return SubscriptionType.objects.get(id=self.cleaned_data['subscription_type']) except SubscriptionType.DoesNotExist: raise ValidationError(_('Unknown subscription type'))
def __init__(self, user=None, list_of_laws=(), default_law=None, hide_law_widgets=True, **kwargs): super(RequestForm, self).__init__(**kwargs) self.user = user self.list_of_laws = list_of_laws self.indexed_laws = dict([(l.pk, l) for l in self.list_of_laws]) self.default_law = default_law self.fields["public_body"].widget.set_initial_jurisdiction( kwargs.get('initial', {}).pop('jurisdiction', None)) self.fields["public_body"].widget.set_initial_search( kwargs.get('initial', {}).pop('public_body_search', None)) self.fields["law"] = forms.ChoiceField( label=_("Information Law"), required=False, widget=forms.Select if not hide_law_widgets else forms.HiddenInput, initial=default_law.pk, choices=((l.pk, l.name) for l in list_of_laws))
class BillingModelFormWithCity(ModelFormWithCity): """ModelForm with city""" billing_city = forms.CharField( required=False, label=_('City'), widget=CityAutoComplete(attrs={ 'placeholder': _('Enter a city'), 'size': '80' })) billing_country = forms.ChoiceField(required=False, label=_('Country')) def __init__(self, *args, **kwargs): super(BillingModelFormWithCity, self).__init__(*args, **kwargs) def _post_init(self, *args, **kwargs): """called at the end of __init__ of the parent class""" super(BillingModelFormWithCity, self)._post_init(*args, **kwargs) self._manage_country_field('billing_', *args, **kwargs) def clean_billing_city(self): """city validation""" return self._clean_city_field('billing_')
class ContactsImportConfirmForm(ContactsImportForm): """confirm contact import""" default_department = forms.ChoiceField( required=False, label=_('Default department'), help_text=_( 'The city in red will be created with this department as parent')) class Meta(ContactsImportForm.Meta): """from model""" fields = ( 'encoding', 'separator', 'entity_type', 'groups', 'entity_name_from_email', ) def __init__(self, *args, **kwargs): super(ContactsImportConfirmForm, self).__init__(*args, **kwargs) zone_tuples = [ (zone.code, zone.name) for zone in models.Zone.objects.filter(type__type='department') ] self.fields['default_department'].choices = [('', '')] + zone_tuples def clean_default_department(self): """validation""" code = self.cleaned_data['default_department'] if code: if not models.Zone.objects.filter( code=self.cleaned_data['default_department']): raise ValidationError(ugettext('Please enter a valid code')) return self.cleaned_data['default_department'] else: return None