class MemberSerializer(serializers.ModelSerializer): country = SerializableCountryField(allow_blank=True, choices=Countries(), required=False) nationality = SerializableCountryField(allow_blank=True, choices=Countries(), required=False) class Meta: model = Member fields = '__all__'
def field(self): choices = self._get_countries() overrides = extend_country_choices(choices, settings.COUNTRIES_OVERRIDE) countries = Countries() countries.only = overrides self.extra["choices"] = list(countries) return super().field
def field(self): qs = self.model._default_manager.distinct() qs = qs.order_by(self.name).values_list(self.name, flat=True) choices = [o for o in qs if o] countries = Countries() countries.only = choices self.extra["choices"] = list(countries) self.extra["choices"].insert(0, (None, "---------")) return super().field
def field(self): qs = self.model._default_manager.distinct() qs = qs.order_by(self.field_name).values_list(self.field_name, flat=True) choices = [o for o in qs if o] countries = Countries() countries.only = choices self.extra['choices'] = list(countries) return super().field
def field(self): qs = self.model._default_manager.distinct() qs = qs.order_by(self.name).values_list(self.name, flat=True) choices = [o for o in qs if o] countries = Countries() countries.only = choices self.extra['choices'] = list(countries) self.extra['choices'].insert(0, EMPTY_SELECTION) return super().field
def __init__(self, *args, **kwargs): '''Build form layout dynamically.''' super(InstructorsForm, self).__init__(*args, **kwargs) # dynamically build choices for country field only = Airport.objects.distinct().values_list('country', flat=True) only = [c for c in only if c] countries = Countries() countries.only = only choices = list(countries) self.fields['country'] = forms.MultipleChoiceField(choices=choices, required=False) self.helper = FormHelper(self) self.helper.form_class = 'form-inline' self.helper.form_method = 'get' self.helper.layout = Layout( Div( Div( 'latitude', 'longitude', css_class='panel-body' ), css_class='panel panel-default ', ), HTML('<p>OR</p>'), Div( Div( 'airport', css_class='panel-body' ), css_class='panel panel-default ', ), HTML('<p>OR</p>'), Div( Div( 'country', css_class='panel-body' ), css_class='panel panel-default ', ), 'gender', 'lessons', 'instructor_badges', FormActions( Submit('submit', 'Submit'), ), )
def test_applicable_countries(self): # An advice applicable for any country is expected to return the "ALL" label. advice = TravelAdviceFactory(countries=[]) self.assertEqual(advice.applicable_countries(all_label=None), advice._meta.get_field('countries').blank_label) self.assertEqual(advice.applicable_countries(all_label="EVERYONE"), "EVERYONE") # An advice for specific countries is expected to return the names or codes of these countries. all_world = Countries() countries = random.sample(all_world.countries.keys(), 4) advice = TravelAdviceFactory(countries=countries) self.assertEqual(advice.applicable_countries(code=True), ', '.join(countries)) self.assertEqual(advice.applicable_countries(code=False), ', '.join(all_world.name(k) for k in countries))
def clean(self): self.cleaned_data = super(AddressForm, self).clean() country = self.cleaned_data.get('country') postal_code = self.cleaned_data.get('postal_code') region = self.cleaned_data.get('region') self.country_name = Countries().name(country) # Require a Region (State/Province/County) in countries where required. if country and country != 'GB' and not region: error_message = ( 'The %s field is required for addresses within the selected ' 'country (%s).' % (self.fields['region'].label, self.country_name)) self.add_error('region', error_message) # Require a Postal Code in countries where required. if country and country != 'IE' and not postal_code: error_message = ( 'The %s field is required for addresses within the selected ' 'country (%s).' % (self.fields['postal_code'].label, self.country_name)) self.add_error('postal_code', error_message) elif country == 'IE' and postal_code: self.cleaned_data.update({ 'postal_code': None, }) else: self.validate_postal_code(country, postal_code) return self.cleaned_data
def geo_result_country(result): """ Return the country from django_countries corresponding to the one in the geocoding result. """ try: return Countries().name(result.country_code.upper()) or result.country except (AttributeError, KeyError): return result.country
class UserSerializer(serializers.ModelSerializer): country = SerializableCountryField(allow_blank=True, choices=Countries()) class Meta: model = CustomUser fields = [ 'id', 'email', 'first_name', 'last_name', 'phone_number', 'country', 'date_of_birth' ]
def get_countries_list(): countries = Countries() country_list = {} for code, name in list(countries): code_name = "[{0}] {1}".format(code, name) print("[APP] adding: {0}".format(code_name)) country_list[code] = code_name return country_list
class EventFilterSet(filters.FilterSet): # Filtering by country and importance level importance = filters.MultipleChoiceFilter(field_name="importance", label="filter by importance", choices=[(i, i) for i in range(1, 4)]) country = filters.MultipleChoiceFilter(field_name="country", label="filter by country", choices=Countries()) class Meta: model = Event fields = ["importance", "country"]
def __init__(self, *args, **kwargs): '''Build form layout dynamically.''' super().__init__(*args, **kwargs) # dynamically build choices for country field only = Airport.objects.distinct().exclude(country='') \ .exclude(country=None) \ .values_list('country', flat=True) countries = Countries() countries.only = only choices = list(countries) self.fields['country'] = forms.MultipleChoiceField(choices=choices, required=False) self.helper = FormHelper(self) self.helper.form_class = 'form-inline' self.helper.form_method = 'get' self.helper.layout = Layout( Div( Div(HTML('Location close to'), css_class='panel-heading'), Div('airport', css_class='panel-body'), Div(HTML('<b>OR</b>'), css_class='panel-footer'), Div('country', css_class='panel-body'), Div(HTML('<b>OR</b>'), css_class='panel-footer'), Div('latitude', 'longitude', css_class='panel-body'), css_class='panel panel-default ', ), 'instructor_badges', 'was_helper', 'was_organizer', 'is_in_progress_trainee', 'languages', 'gender', 'lessons', FormActions( Submit('submit', 'Submit'), ), )
class LocationSerializer(serializers.ModelSerializer): """ Location serializer class """ country = SerializableCountryField(allow_blank=True, required=False, choices=Countries()) shapefile = ShapeFileField(required=False) geopoint = GeopointField(required=False) def validate(self, attrs): """ Custom Validation for Location Serializer """ if self.instance: geopoint = attrs.get('geopoint', self.instance.geopoint) radius = attrs.get('radius', self.instance.radius) shapefile = attrs.get('shapefile', self.instance.shapefile) else: geopoint = attrs.get('geopoint') radius = attrs.get('radius') shapefile = attrs.get('shapefile') if geopoint is not None: if shapefile is not None: raise serializers.ValidationError( {'shapefile': GEODETAILS_ONLY}) if radius is None: raise serializers.ValidationError({'radius': RADIUS_MISSING}) if radius is not None: if shapefile is not None: raise serializers.ValidationError( {'shapefile': GEODETAILS_ONLY}) if geopoint is None: raise serializers.ValidationError( {'geopoint': GEOPOINT_MISSING}) return super(LocationSerializer, self).validate(attrs) # pylint: disable=too-few-public-methods class Meta: """ Meta options for LocationSerializer """ model = Location fields = [ 'id', 'name', 'country', 'description', 'geopoint', 'radius', 'location_type', 'shapefile', 'parent', 'created', 'modified' ]
def __init__(self, *args, **kwargs): '''Build form layout dynamically.''' super(InstructorsForm, self).__init__(*args, **kwargs) # dynamically build choices for country field only = Airport.objects.distinct().values_list('country', flat=True) only = [c for c in only if c] countries = Countries() countries.only = only choices = list(countries) self.fields['country'] = forms.MultipleChoiceField(choices=choices, required=False) self.helper = FormHelper(self) self.helper.form_class = 'form-inline' self.helper.form_method = 'get' self.helper.layout = Layout( Div( Div('latitude', 'longitude', css_class='panel-body'), css_class='panel panel-default ', ), HTML('<p>OR</p>'), Div( Div('airport', css_class='panel-body'), css_class='panel panel-default ', ), HTML('<p>OR</p>'), Div( Div('country', css_class='panel-body'), css_class='panel panel-default ', ), 'gender', 'lessons', 'instructor_badges', FormActions(Submit('submit', 'Submit'), ), )
def format_geo_result(result): """ Replace given country (-ujo) by the one from django_countries """ if not result.country: return result.address or '' try: country = Countries().name(result.country_code.upper()) except Exception: return result.address else: if not country: return result.address # The name of the country is not necessarily the last-most component of # the address. For example, in some countries the postal code would be # located at the very end of the address string. components = [ part for part in result.address.split(", ") if part != result.country ] return ", ".join(components + [country])
class InstructorsOverTimeFilter(AMYFilterSet): badges = filters.ModelMultipleChoiceFilter( queryset=Badge.objects.instructor_badges(), label='Badges', ) country = filters.MultipleChoiceFilter( choices=list(Countries()), widget=Select2MultipleWidget, help_text="Instructor's country", ) date = filters.DateFromToRangeFilter( label='Date range (from - to)', help_text="Filters on award's date", widget=filter_widgets.RangeWidget(attrs={"class": "dateinput"}), ) class Meta: model = Person fields = [ 'badges', 'country', ]
def test_form_requires_postal_code_for_all_countries_except_ireleand( self, clean_mock): ''' Test that all countries other than Ireland must specify a postal code. ''' form = AddressForm() cleaned_data = { 'country': 'US', 'postal_code': None, } clean_mock.return_value = cleaned_data form.clean() label = form.fields['postal_code'].label country_name = Countries().name(cleaned_data['country']) error_message = ( ('The %s field is required for addresses within the selected ' 'country (%s).') % (label, country_name)) form_errors = form.errors.get('postal_code') self.assertIn(error_message, form_errors)
class WorkshopsOverTimeFilter(AMYFilterSet): tags = filters.ModelMultipleChoiceFilter( queryset=Tag.objects.all(), label='Events with at least one of the following tags:', widget=widgets.SelectMultiple(attrs=dict(size=13)), ) country = filters.MultipleChoiceFilter( choices=list(Countries()), widget=Select2MultipleWidget, ) start = filters.DateFromToRangeFilter( label='Date range (from - to)', help_text="Filters only on the 'Event.start' field", widget=filter_widgets.RangeWidget(attrs={"class": "dateinput"}), ) class Meta: model = Event fields = [ 'tags', 'country', 'start', ]
def setUpTestData(cls): cls.config = SiteConfiguration.get_solo() cls.faker = Faker._get_faker() cls.all_countries = Countries().countries.keys() cls.expected_fields = [ 'country', 'type', 'number', 'comments', ] cls.profile_one = ProfileFactory() cls.phone1_valid = PhoneFactory(profile=cls.profile_one) cls.phone2_valid = PhoneFactory(profile=cls.profile_one) cls.phone3_deleted = PhoneFactory( profile=cls.profile_one, deleted_on=make_aware(cls.faker.date_time_this_decade())) cls.profile_two = ProfileFactory() cls.phone4_valid = PhoneFactory(profile=cls.profile_two) cls.phone5_deleted = PhoneFactory( profile=cls.profile_two, deleted_on=make_aware(cls.faker.date_time_this_decade()))
from django import forms from django.core.validators import MaxValueValidator from django.core.validators import MinValueValidator from django.forms.models import ModelForm from django.forms.models import inlineformset_factory from django_countries import Countries COUNTRIES = list(Countries()) from gpaconvert.models import ContinuousRule from gpaconvert.models import DiscreteRule from gpaconvert.models import GradeSource class GradeSourceListForm(forms.Form): country_choices = [ ('', 'All Countries'), ] + COUNTRIES country = forms.ChoiceField(choices=country_choices, required=False) def __init__(self, *args, **kwargs): f = super(GradeSourceListForm, self).__init__(*args, **kwargs) # limit country choices to those with some data used_countries = set( GradeSource.objects.active().order_by().values_list( 'country', flat=True).distinct()) used_countries.add('') # the all-countries option choices = self.fields['country'].choices choices = [(k, v) for k, v in choices if k in used_countries] self.fields['country'].choices = choices
class WorkshopStaffFilter(AMYFilterSet): """Form for this filter is never showed up, instead a custom form (.forms.WorkshopStaffForm) is used. So there's no need to specify widgets here. """ country = django_filters.MultipleChoiceFilter( choices=list(Countries()), method="filter_country", ) continent = ContinentFilter(label="Continent") lessons = django_filters.ModelMultipleChoiceFilter( label='Lessons', queryset=Lesson.objects.all(), conjoined=True, # `AND` ) badges = django_filters.ModelMultipleChoiceFilter( label='Badges', queryset=Badge.objects.instructor_badges(), conjoined=False, # `OR` ) is_trainer = django_filters.BooleanFilter( widget=widgets.CheckboxInput, method='filter_trainer', ) languages = django_filters.ModelMultipleChoiceFilter( label='Languages', queryset=Language.objects.all(), conjoined=True, # `AND` ) gender = django_filters.ChoiceFilter( label='Gender', choices=Person.GENDER_CHOICES, ) was_helper = django_filters.BooleanFilter( widget=widgets.CheckboxInput, method='filter_helper', ) was_organizer = django_filters.BooleanFilter( widget=widgets.CheckboxInput, method='filter_organizer', ) is_in_progress_trainee = django_filters.BooleanFilter( widget=widgets.CheckboxInput, method='filter_in_progress_trainee', ) def filter_country(self, qs, n, v): if v: return qs.filter(Q(airport__country__in=v) | Q(country__in=v)) return qs def filter_trainer(self, qs, n, v): if v: return qs.filter(is_trainer__gte=1) return qs def filter_helper(self, qs, n, v): if v: return qs.filter(num_helper__gte=1) return qs def filter_organizer(self, qs, n, v): if v: return qs.filter(num_organizer__gte=1) return qs def filter_in_progress_trainee(self, qs, n, v): if v: return qs.filter(is_trainee__gte=1) return qs
def test_initial_iter(self): # Use a new instance so nothing is cached dict(Countries())
class LocationSerializer(serializers.ModelSerializer): """ Location serializer class """ country = SerializableCountryField(allow_blank=True, required=False, choices=Countries()) shapefile = ShapeFileField(required=False) geopoint = GeopointField(required=False) def validate(self, attrs): """ Custom Validation for Location Serializer """ if self.instance: geopoint = attrs.get("geopoint", self.instance.geopoint) radius = attrs.get("radius", self.instance.radius) shapefile = attrs.get("shapefile", self.instance.shapefile) else: geopoint = attrs.get("geopoint") radius = attrs.get("radius") shapefile = attrs.get("shapefile") if geopoint is not None: if shapefile is not None: raise serializers.ValidationError( {"shapefile": GEODETAILS_ONLY}) if radius is None: raise serializers.ValidationError({"radius": RADIUS_MISSING}) if radius is not None: if shapefile is not None: raise serializers.ValidationError( {"shapefile": GEODETAILS_ONLY}) if geopoint is None: raise serializers.ValidationError( {"geopoint": GEOPOINT_MISSING}) return super(LocationSerializer, self).validate(attrs) # pylint: disable=too-few-public-methods class Meta: """ Meta options for LocationSerializer """ model = Location fields = [ "id", "name", "country", "description", "geopoint", "radius", "location_type", "shapefile", "parent", "created", "modified", ]
class WorkshopStaffFilter(AMYFilterSet): country = django_filters.MultipleChoiceFilter( choices=list(Countries()), widget=Select2Multiple(), method="filter_country", ) lessons = django_filters.ModelMultipleChoiceFilter( label='Lessons', queryset=Lesson.objects.all(), widget=ModelSelect2Multiple(attrs=SIDEBAR_DAL_WIDTH), conjoined=True, # `AND` ) badges = django_filters.ModelMultipleChoiceFilter( label='Badges', queryset=Badge.objects.instructor_badges(), widget=ModelSelect2Multiple(attrs=SIDEBAR_DAL_WIDTH), conjoined=False, # `OR` ) languages = django_filters.ModelMultipleChoiceFilter( label='Languages', queryset=Language.objects.all(), widget=ModelSelect2Multiple( url='language-lookup', attrs=SIDEBAR_DAL_WIDTH, ), conjoined=True, # `AND` ) gender = django_filters.ChoiceFilter( label='Gender', choices=Person.GENDER_CHOICES, ) was_helper = django_filters.BooleanFilter( widget=widgets.CheckboxInput, method='filter_helper', ) was_organizer = django_filters.BooleanFilter( widget=widgets.CheckboxInput, method='filter_organizer', ) is_in_progress_trainee = django_filters.BooleanFilter( widget=widgets.CheckboxInput, method='filter_in_progress_trainee', ) def filter_country(self, qs, n, v): if v: return qs.filter( Q(airport__country__in=v) | Q(country__in=v) ) return qs def filter_helper(self, qs, n, v): if v: return qs.filter(num_helper__gte=1) return qs def filter_organizer(self, qs, n, v): if v: return qs.filter(num_organizer__gte=1) return qs def filter_in_progress_trainee(self, qs, n, v): if v: return qs.filter(is_trainee__gte=1) return qs
class TicketRequestBaseForm(forms.ModelForm): required_css_class = 'required' name = forms.CharField( label=_("Full name"), required=True, ) public_name = forms.CharField( label=_("Public display name"), required=True, ) email = forms.EmailField( label=_("Email"), required=True, widget=forms.TextInput( attrs={ 'type': 'email', 'placeholder': _('*****@*****.**') })) years_attended_iff = forms.MultipleChoiceField( label='Have you attended the IFF before?', required=True, choices=( ("Not yet!", _("Not yet!")), ("2019", _("2019")), ("2018", _("2018")), ("2017", _("2017")), ("2016", _("2016")), ("2015", _("2015 (CTF)")), ), widget=forms.CheckboxSelectMultiple(), ) pgp_key = forms.CharField( label=_("PGP Key"), required=False, widget=forms.Textarea(), ) gender = forms.ChoiceField( label=_("Gender"), choices=( ("Female", _("Female")), ("Gender-nonconforming", _("Gender-nonconforming")), ("Male", _("Male")), ("Other", _("Other")), ("Prefer not to say", _("Prefer not to say")), ), ) country = forms.ChoiceField(label=_("Country of Origin"), choices=Countries()) is_refugee = forms.TypedChoiceField(label=_( "Do you identify as being part of an ethnic, racial or cultural minority group?" ), choices=(((True, 'Yes'), (False, 'No'))), widget=forms.RadioSelect) belongs_to_minority_group = forms.TypedChoiceField( label=_( "Do you identify as being part of a refugee diaspora community?"), choices=(((True, 'Yes'), (False, 'No'))), widget=forms.RadioSelect) professional_areas = forms.MultipleChoiceField( label='Check the boxes that most closely describe the work you do.', choices=( ("Digital Security Training", _("Digital Security Training")), ("Software/Web Development", _("Software/Web Development")), ("Cryptography", _("Cryptography")), ("Information Security", _("Information Security")), ("Student", _("Student")), ("Frontline Activism", _("Frontline Activism")), ("Research/Academia", _("Research/Academia")), ("Social Sciences", _("Social Sciences")), ("Policy/Internet Governance", _("Policy/Internet Governance")), ("Data Science", _("Data Science")), ("Advocacy", _("Advocacy")), ("Communications", _("Communications")), ("Journalism and Media", _("Journalism and Media")), ("Arts & Culture", _("Arts & Culture")), ("Design", _("Design")), ("Program Management", _("Program Management")), ("Philanthropic/Grantmaking Organization", _("Philanthropic/Grantmaking Organization")), ("Other", _("Other")), ), widget=forms.CheckboxSelectMultiple(), ) professional_title = forms.CharField( label=_("Professional Title"), required=False, ) organization = forms.CharField( label=_("Organization"), required=False, ) project = forms.CharField( label=_("Project"), required=False, ) follow_coc = forms.TypedChoiceField( label=_("Do you agree to respect and follow IFF’s Code of Conduct?"), required=True, choices=(((True, 'Yes'), (False, 'No'))), widget=forms.RadioSelect) subscribe_mailing_list = forms.TypedChoiceField( label=_("Would you like to subscribe to the IFF Mailing List?"), required=False, choices=(((True, 'Yes'), (False, 'No'))), widget=forms.RadioSelect) receive_mattermost_invite = forms.TypedChoiceField( label=_("Would you like to receive a Mattermost invite?"), required=False, choices=(((True, 'Yes'), (False, 'No'))), widget=forms.RadioSelect) def clean_follow_coc(self): follow_coc = self.cleaned_data.get('follow_coc') if not follow_coc == 'True': raise forms.ValidationError( "You have to agree to respect and follow IFF’s Code of Conduct" ) return follow_coc class Meta: model = TicketRequest fields = ( 'name', 'email', ) json_fields = ( 'public_name', 'years_attended_iff', 'pgp_key', 'gender', 'country', 'is_refugee', 'belongs_to_minority_group', 'professional_areas', 'professional_title', 'organization', 'project', 'follow_coc', 'subscribe_mailing_list', 'receive_mattermost_invite', )
from django import forms from django.core.validators import MaxValueValidator from django.core.validators import MinValueValidator from django.forms.models import ModelForm from django.forms.models import inlineformset_factory from django_countries import Countries COUNTRIES = Countries().countries from gpaconvert.models import ContinuousRule from gpaconvert.models import DiscreteRule from gpaconvert.models import GradeSource class GradeSourceListForm(forms.Form): country_choices = [('', 'All Countries'),] + COUNTRIES country = forms.ChoiceField(choices=country_choices, required=False) def __init__(self, *args, **kwargs): f = super(GradeSourceListForm, self).__init__(*args, **kwargs) # limit country choices to those with some data used_countries = set(GradeSource.objects.active().order_by().values_list('country', flat=True).distinct()) used_countries.add('') # the all-countries option choices = self.fields['country'].choices choices = [(k,v) for k,v in choices if k in used_countries] self.fields['country'].choices = choices return f
class WorkshopStaffForm(forms.Form): '''Represent instructor matching form.''' latitude = forms.FloatField(label='Latitude', min_value=-90.0, max_value=90.0, required=False) longitude = forms.FloatField(label='Longitude', min_value=-180.0, max_value=180.0, required=False) airport = forms.ModelChoiceField(label='Airport', required=False, queryset=Airport.objects.all(), widget=ModelSelect2( url='airport-lookup', attrs=SIDEBAR_DAL_WIDTH, )) languages = forms.ModelMultipleChoiceField(label='Languages', required=False, queryset=Language.objects.all(), widget=ModelSelect2Multiple( url='language-lookup', attrs=SIDEBAR_DAL_WIDTH, )) country = forms.MultipleChoiceField( choices=list(Countries()), required=False, widget=Select2Multiple, ) continent = forms.ChoiceField( choices=continent_list, required=False, widget=Select2, ) lessons = forms.ModelMultipleChoiceField( queryset=Lesson.objects.all(), widget=SelectMultiple(), required=False, ) badges = forms.ModelMultipleChoiceField( queryset=Badge.objects.instructor_badges(), widget=CheckboxSelectMultiple(), required=False, ) is_trainer = forms.BooleanField(required=False, label='Has Trainer badge') GENDER_CHOICES = ((None, '---------'), ) + Person.GENDER_CHOICES gender = forms.ChoiceField(choices=GENDER_CHOICES, required=False) was_helper = forms.BooleanField(required=False, label='Was helper at least once before') was_organizer = forms.BooleanField( required=False, label='Was organizer at least once before') is_in_progress_trainee = forms.BooleanField( required=False, label='Is an in-progress instructor trainee') def __init__(self, *args, **kwargs): '''Build form layout dynamically.''' super().__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_method = 'get' self.helper.layout = Layout( Div( Div(HTML('<h5 class="card-title">Location</h5>'), 'airport', HTML('<hr>'), 'country', HTML('<hr>'), 'continent', HTML('<hr>'), 'latitude', 'longitude', css_class='card-body'), css_class='card', ), 'badges', 'is_trainer', HTML('<hr>'), 'was_helper', 'was_organizer', 'is_in_progress_trainee', 'languages', 'gender', 'lessons', Submit('', 'Submit'), ) def clean(self): cleaned_data = super().clean() lat = bool(cleaned_data.get('latitude')) lng = bool(cleaned_data.get('longitude')) airport = bool(cleaned_data.get('airport')) country = bool(cleaned_data.get('country')) latlng = lat and lng # if searching by coordinates, then there must be both lat & lng # present if lat ^ lng: raise forms.ValidationError( 'Must specify both latitude and longitude if searching by ' 'coordinates') # User must search by airport, or country, or coordinates, or none # of them. Sum of boolean elements must be equal 0 (if general search) # or 1 (if searching by airport OR country OR lat/lng). if sum([airport, country, latlng]) not in [0, 1]: raise forms.ValidationError( 'Must specify an airport OR a country, OR use coordinates, OR ' 'none of them.') return cleaned_data
class CityStateCountryShippingSimulatorForm(forms.Form): country = forms.ChoiceField(choices=lambda: Countries(), required=True) region = forms.CharField(required=True) city = forms.CharField(required=True)
from django.contrib.auth.hashers import make_password import requests as rq from ..models.users import User from django.core.mail import EmailMessage from rest_framework import serializers from django_countries.serializer_fields import CountryField from django_countries import Countries from django.template.loader import render_to_string from django.urls import reverse from ..utils import EmailVerificationTokenGenerator options = Countries() class UserSerializer(serializers.HyperlinkedModelSerializer): country = CountryField(country_dict=True) def validate_country(self, code_or_name): if options.name(code_or_name): # given string is code return code_or_name code = options.by_name(code_or_name) if code: return code else: raise serializers.ValidationError(f'{code_or_name} is not a valid country name or code') @staticmethod def validate_password(password):
def __init__(self, **kwargs): super(SerializeableCountryField, self).__init__(choices=Countries(), **kwargs)
class WorkshopStaffForm(forms.Form): """Represent instructor matching form.""" latitude = forms.FloatField(label="Latitude", min_value=-90.0, max_value=90.0, required=False) longitude = forms.FloatField(label="Longitude", min_value=-180.0, max_value=180.0, required=False) airport = forms.ModelChoiceField( label="Airport", required=False, queryset=Airport.objects.all(), widget=ModelSelect2Widget(data_view="airport-lookup", attrs=SELECT2_SIDEBAR), ) languages = forms.ModelMultipleChoiceField( label="Languages", required=False, queryset=Language.objects.all(), widget=ModelSelect2MultipleWidget( data_view="language-lookup", attrs=SELECT2_SIDEBAR, ), ) country = forms.MultipleChoiceField( choices=list(Countries()), required=False, widget=Select2MultipleWidget, ) continent = forms.ChoiceField( choices=continent_list, required=False, widget=Select2Widget, ) lessons = forms.ModelMultipleChoiceField( queryset=Lesson.objects.all(), widget=SelectMultiple(), required=False, ) badges = forms.ModelMultipleChoiceField( queryset=Badge.objects.instructor_badges(), widget=CheckboxSelectMultiple(), required=False, ) is_trainer = forms.BooleanField(required=False, label="Has Trainer badge") GENDER_CHOICES = ((None, "---------"), ) + Person.GENDER_CHOICES gender = forms.ChoiceField(choices=GENDER_CHOICES, required=False) was_helper = forms.BooleanField(required=False, label="Was helper at least once before") was_organizer = forms.BooleanField( required=False, label="Was organizer at least once before") is_in_progress_trainee = forms.BooleanField( required=False, label="Is an in-progress instructor trainee") def __init__(self, *args, **kwargs): """Build form layout dynamically.""" super().__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_method = "get" self.helper.layout = Layout( Div( Div( HTML('<h5 class="card-title">Location</h5>'), "airport", HTML("<hr>"), "country", HTML("<hr>"), "continent", HTML("<hr>"), "latitude", "longitude", css_class="card-body", ), css_class="card", ), "badges", "is_trainer", HTML("<hr>"), "was_helper", "was_organizer", "is_in_progress_trainee", "languages", "gender", "lessons", Submit("", "Submit"), ) def clean(self): cleaned_data = super().clean() lat = bool(cleaned_data.get("latitude")) lng = bool(cleaned_data.get("longitude")) airport = bool(cleaned_data.get("airport")) country = bool(cleaned_data.get("country")) latlng = lat and lng # if searching by coordinates, then there must be both lat & lng # present if lat ^ lng: raise ValidationError( "Must specify both latitude and longitude if searching by " "coordinates") # User must search by airport, or country, or coordinates, or none # of them. Sum of boolean elements must be equal 0 (if general search) # or 1 (if searching by airport OR country OR lat/lng). if sum([airport, country, latlng]) not in [0, 1]: raise ValidationError( "Must specify an airport OR a country, OR use coordinates, OR " "none of them.") return cleaned_data
def settings_form_fields(self) -> dict: """ When the event's administrator visits the event configuration page, this method is called to return the configuration fields available. It should therefore return a dictionary where the keys should be (unprefixed) settings keys and the values should be corresponding Django form fields. The default implementation returns the appropriate fields for the ``_enabled``, ``_fee_abs``, ``_fee_percent`` and ``_availability_date`` settings mentioned above. We suggest that you return an ``OrderedDict`` object instead of a dictionary and make use of the default implementation. Your implementation could look like this:: @property def settings_form_fields(self): return OrderedDict( list(super().settings_form_fields.items()) + [ ('bank_details', forms.CharField( widget=forms.Textarea, label=_('Bank account details'), required=False )) ] ) .. WARNING:: It is highly discouraged to alter the ``_enabled`` field of the default implementation. """ places = settings.CURRENCY_PLACES.get(self.event.currency, 2) d = OrderedDict([ ('_enabled', forms.BooleanField( label=_('Enable payment method'), required=False, )), ('_availability_date', RelativeDateField( label=_('Available until'), help_text= _('Users will not be able to choose this payment provider after the given date.' ), required=False, )), ('_invoice_text', I18nFormField( label=_('Text on invoices'), help_text= _('Will be printed just below the payment figures and above the closing text on invoices. ' 'This will only be used if the invoice is generated before the order is paid. If the ' 'invoice is generated later, it will show a text stating that it has already been paid.' ), required=False, widget=I18nTextarea, widget_kwargs={'attrs': { 'rows': '2' }})), ('_total_min', forms.DecimalField( label=_('Minimum order total'), help_text= _('This payment will be available only if the order total is equal to or exceeds the given ' 'value. The order total for this purpose may be computed without taking the fees imposed ' 'by this payment method into account.'), localize=True, required=False, decimal_places=places, widget=DecimalTextInput(places=places))), ('_total_max', forms.DecimalField( label=_('Maximum order total'), help_text= _('This payment will be available only if the order total is equal to or below the given ' 'value. The order total for this purpose may be computed without taking the fees imposed ' 'by this payment method into account.'), localize=True, required=False, decimal_places=places, widget=DecimalTextInput(places=places))), ('_fee_abs', forms.DecimalField(label=_('Additional fee'), help_text=_('Absolute value'), localize=True, required=False, decimal_places=places, widget=DecimalTextInput(places=places))), ('_fee_percent', forms.DecimalField( label=_('Additional fee'), help_text=_('Percentage of the order total.'), localize=True, required=False, )), ('_fee_reverse_calc', forms.BooleanField( label=_( 'Calculate the fee from the total value including the fee.' ), help_text= _('We recommend to enable this if you want your users to pay the payment fees of your ' 'payment provider. <a href="{docs_url}" target="_blank" rel="noopener">Click here ' 'for detailed information on what this does.</a> Don\'t forget to set the correct fees ' 'above!'). format( docs_url= 'https://docs.pretix.eu/en/latest/user/payments/fees.html' ), required=False)), ('_restricted_countries', forms.MultipleChoiceField( label=_('Restrict to countries'), choices=Countries(), help_text= _('Only allow choosing this payment provider for invoice addresses in the selected ' 'countries. If you don\'t select any country, all countries are allowed. This is only ' 'enabled if the invoice address is required.'), widget=forms.CheckboxSelectMultiple( attrs={'class': 'scrolling-multiple-choice'}), required=False, disabled=not self.event.settings.invoice_address_required)), ]) d['_restricted_countries']._as_type = list return d
class KaznetLocationSerializer(serializers.ModelSerializer): """ KaznetLocationSerializer serializer class """ country = SerializableCountryField( allow_blank=True, required=False, choices=Countries()) shapefile = ShapeFileField(required=False) geopoint = GeopointField(required=False) # pylint: disable=too-few-public-methods class Meta: """ Meta options for KaznetLocationSerializer """ model = Location fields = [ 'id', 'name', 'country', 'parent_name', 'location_type', 'location_type_name', 'description', 'geopoint', 'radius', 'shapefile', 'parent', 'created', 'modified', 'has_submissions', ] def validate_parent(self, value): """ Validate location parent field """ if self.instance is not None and not validate_parent_field( self.instance, value): # locations cannot be their own parents raise serializers.ValidationError(SAME_PARENT) return value def validate(self, attrs): """ Custom Validation for KaznetLocationSerializer """ geopoint = attrs.get('geopoint') radius = attrs.get('radius') shapefile = attrs.get('shapefile') if geopoint is not None: if shapefile is not None: raise serializers.ValidationError( {'shapefile': GEODETAILS_ONLY} ) if radius is None: raise serializers.ValidationError( {'radius': RADIUS_MISSING} ) if radius is not None: if shapefile is not None: raise serializers.ValidationError( {'shapefile': GEODETAILS_ONLY} ) if geopoint is None: raise serializers.ValidationError( {'geopoint': GEOPOINT_MISSING} ) if shapefile is not None: if radius is not None: raise serializers.ValidationError( {'radius': GEODETAILS_ONLY} ) if geopoint is not None: raise serializers.ValidationError( {'geopoint': GEODETAILS_ONLY} ) return super().validate(attrs) def update(self, instance, validated_data): """ Custom method to perform Location Update """ geopoint = validated_data.get('geopoint') radius = validated_data.get('radius') shapefile = validated_data.get('shapefile') # remove shapefile if post data has geopoint and radius if geopoint is not None and radius is not None: instance.radius = radius instance.geopoint = geopoint if instance.shapefile: instance.shapefile = None # remove geopoint and radius if post data has shapefile elif shapefile is not None: instance.shapefile = shapefile if instance.geopoint or instance.radius: instance.radius = None instance.geopoint = None instance.name = validated_data.get('name', instance.name) instance.description = validated_data.get('description', instance.description) instance.save() return super().update(instance, validated_data)