def register(request): """Registers Users. Pulls out an invite code if it exists and auto validates the user if so. Single-purpose view. """ COUNTRIES = zip( product_details.get_regions('en-US').values(), product_details.get_regions(request.locale).values()) COUNTRIES = sorted(COUNTRIES, key=lambda country: country[1]) COUNTRIES.insert(0, ('', '----')) if 'code' in request.GET: request.session['invite-code'] = request.GET['code'] return redirect('home') if request.user.is_authenticated(): return redirect(reverse('profile', args=[request.user.username])) authenticated_email = request.session.get('authenticated_email') if not authenticated_email: log.error('Browserid registration, but no verified email in session') return redirect('home') user = auth.authenticate(authenticated_email=authenticated_email) if not user: return redirect('home') form = forms.RegistrationForm(request.POST or None, instance=user.get_profile()) form.fields['country'].choices = COUNTRIES if request.method == 'POST': if form.is_valid(): form.save(user) userProfile = user.get_profile() for group in request.POST.getlist('groups'): userProfile.groups.add(group) userProfile.save() auth.login(request, user) _update_invites(request) messages.info(request, _(u'Your account has been created.')) return redirect(reverse('profile', args=[request.user.username])) # 'user' object must be passed in because we are not logged in return render( request, 'registration/register.html', dict( form=form, edit_form_action=reverse('register'), mode='new', profile=user.get_profile(), user=user, ))
def register(request): """Registers Users. Pulls out an invite code if it exists and auto validates the user if so. Single-purpose view. """ COUNTRIES = zip(product_details.get_regions('en-US').values(), product_details.get_regions(request.locale).values()) COUNTRIES = sorted(COUNTRIES, key=lambda country: country[1]) COUNTRIES.insert(0, ('', '----')) if 'code' in request.GET: request.session['invite-code'] = request.GET['code'] return redirect('home') if request.user.is_authenticated(): return redirect(reverse('profile', args=[request.user.username])) authenticated_email = request.session.get('authenticated_email') if not authenticated_email: log.error('Browserid registration, but no verified email in session') return redirect('home') user = auth.authenticate(authenticated_email=authenticated_email) if not user: return redirect('home') form = forms.RegistrationForm(request.POST or None, instance=user.get_profile()) form.fields['country'].choices = COUNTRIES if request.method == 'POST': if form.is_valid(): form.save(user) userProfile = user.get_profile() for group in request.POST.getlist('groups'): userProfile.groups.add(group) userProfile.save() auth.login(request, user) _update_invites(request) messages.info(request, _(u'Your account has been created.')) return redirect(reverse('profile', args=[request.user.username])) # 'user' object must be passed in because we are not logged in return render(request, 'registration/register.html', dict(form=form, edit_form_action=reverse('register'), mode='new', profile=user.get_profile(), user=user, ))
def __init__(self, locale, *args, **kwargs): regions = product_details.get_regions(locale) regions = sorted(regions.iteritems(), key=itemgetter(1)) regions.insert(0, self.empty_choice) super(ContributeSignupForm, self).__init__(*args, **kwargs) self.locale = locale self.fields['country'] = forms.ChoiceField(choices=regions, widget=L10nSelect)
def __init__(self, locale, *args, **kwargs): regions = product_details.get_regions(locale) regions = sorted(regions.iteritems(), key=lambda x: x[1]) lang = country = locale.lower() if '-' in lang: lang, country = lang.split('-', 1) lang_choices = self.LANG_CHOICES[:] if lang not in LANGS: # 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, (lang, lang)) super(NewsletterFooterForm, self).__init__(*args, **kwargs) self.fields['country'] = forms.ChoiceField(choices=regions, initial=country, required=False) # TypedChoiceField knows that '' is an empty choice, and with # required=True, will not accept '' as valid input. select_widget = widgets.Select(attrs={'required': 'required'}) self.fields['lang'] = forms.TypedChoiceField(widget=select_widget, choices=lang_choices, initial=lang, required=True, empty_value='')
def result_to_country(result): """ Given one result from mapbox, converted to a dictionary keyed on 'type', return a Country object or None """ if 'country' in result: mapbox_country = result['country'] codes = dict((v, k) for k, v in product_details.get_regions('en-US').iteritems()) code = codes.get(mapbox_country['name'], '') lookup_args = { 'name': mapbox_country['name'] } args = { 'mapbox_id': mapbox_country['id'], 'code': code } args.update(lookup_args) query = Q(**lookup_args) | Q(mapbox_id=mapbox_country['id']) country_qs = Country.objects.filter(query).distinct() if country_qs.exists(): # Check if deduplication is required if country_qs.count() == 2: deduplicate_countries(country_qs[0], country_qs[1]) country_qs.update(**args) country = country_qs[0] else: country = Country.objects.create(**args) return country
def __init__(self, locale, *args, **kwargs): regions = product_details.get_regions(locale) regions = sorted(regions.iteritems(), key=itemgetter(1)) regions.insert(0, self.empty_choice) super(ContributeSignupForm, self).__init__(*args, **kwargs) self.locale = locale self.fields["country"] = forms.ChoiceField(choices=regions, widget=L10nSelect)
def __init__(self, locale, *args, **kwargs): regions = product_details.get_regions(locale) regions = sorted(regions.iteritems(), key=lambda x: x[1]) lang = country = locale.lower() if '-' in lang: lang, country = lang.split('-', 1) lang_choices = get_lang_choices() 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, (lang, lang)) super(NewsletterFooterForm, self).__init__(*args, **kwargs) self.fields['country'] = forms.ChoiceField(choices=regions, initial=country, required=False) # TypedChoiceField knows that '' is an empty choice, and with # required=True, will not accept '' as valid input. select_widget = widgets.Select(attrs={'required': 'required'}) self.fields['lang'] = forms.TypedChoiceField(widget=select_widget, choices=lang_choices, initial=lang, required=True, empty_value='')
def lazy_countries(): from product_details import product_details try: return product_details.get_regions('en-US') except IOError: return {u'us': 'United States'}
def lazy_countries(): from product_details import product_details try: return product_details.get_regions("en-US") except IOError: return {u"us": "United States"}
def result_to_country(result): """ Given one result from mapbox, converted to a dictionary keyed on 'type', return a Country object or None """ if 'country' in result: mapbox_country = result['country'] codes = dict( (v, k) for k, v in product_details.get_regions('en-US').iteritems()) code = codes.get(mapbox_country['name'], '') lookup_args = {'name': mapbox_country['name']} args = {'mapbox_id': mapbox_country['id'], 'code': code} args.update(lookup_args) query = Q(**lookup_args) | Q(mapbox_id=mapbox_country['id']) country_qs = Country.objects.filter(query).distinct() if country_qs.exists(): # Check if deduplication is required if country_qs.count() == 2: deduplicate_countries(country_qs[0], country_qs[1]) country_qs.update(**args) country = country_qs[0] else: country = Country.objects.create(**args) return country
def __init__(self, *args, **kwargs): locale = kwargs.get('locale', 'en-US') super(ContributeUniversityAmbassadorForm, self).__init__(*args, **kwargs) country_list = product_details.get_regions(locale).items() country_list = sorted(country_list, key=lambda country: country[1]) country_list.insert(0, ('', _('Country'))) self.fields['country'].choices = country_list
def __init__(self, *args, **kwargs): locale = kwargs.get("locale", "en-US") super(ContributeStudentAmbassadorForm, self).__init__(*args, **kwargs) country_list = product_details.get_regions(locale).items() country_list = sorted(country_list, key=lambda country: country[1]) country_list.insert(0, ("", "")) self.fields["country"].choices = country_list
def kpi(request): reps = User.objects.filter(groups__name='Rep', userprofile__registration_complete=True) q_active = Q( ng_reports__report_date__range=[get_date(weeks=-4), get_date(weeks=4)]) q_inactive = Q( ng_reports__report_date__range=[get_date(weeks=-8), get_date(weeks=8)]) q_active_month1 = Q( ng_reports__report_date__range=[get_date(weeks=-4), get_date(weeks=0)]) q_active_month2 = Q( ng_reports__report_date__range=[get_date(weeks=-8), get_date(weeks=0)]) q_active_month6 = Q( ng_reports__report_date__range=[get_date(weeks=-26), get_date(weeks=0)]) q_active_month12 = Q( ng_reports__report_date__range=[get_date(weeks=-52), get_date(weeks=0)]) top_countries = (reps .values('userprofile__country') .annotate(country_count=Count('userprofile__country')) .order_by('-country_count')[:15]) active = reps.filter(q_active) active_month1 = reps.filter(q_active_month1) active_month2 = reps.filter(q_active_month2) active_month6 = reps.filter(q_active_month6) active_month12 = reps.filter(q_active_month12) inactive_low = reps.filter(~q_active & q_inactive) inactive_high = reps.filter(~q_inactive) args = {} args['active_users'] = active.distinct().count() args['inactive_low_users'] = inactive_low.distinct().count() args['inactive_high_users'] = inactive_high.distinct().count() args['reps_count'] = reps.count() args['past_events'] = Event.objects.filter(start__lt=now()).count() args['future_events'] = Event.objects.filter(start__gte=now()).count() args['activities'] = NGReport.objects.all().count() args['active_month1'] = active_month1.distinct().count() args['active_month2'] = active_month2.distinct().count() args['active_month6'] = active_month6.distinct().count() args['active_month12'] = active_month12.distinct().count() args['top_countries'] = top_countries countries = product_details.get_regions('en').values() countries.sort() categories = FunctionalArea.active_objects.all() initiatives = Campaign.active_objects.all() ordered_reps = reps.order_by('userprofile__country', 'last_name', 'first_name') args['reps'] = ordered_reps args['countries'] = countries args['categories'] = categories args['initiatives'] = initiatives return render(request, 'kpi.jinja', args)
def __init__(self, *args, **kwargs): locale = kwargs.get('locale', 'en-US') super(ContributeStudentAmbassadorForm, self).__init__(*args, **kwargs) country_list = product_details.get_regions(locale).items() country_list = sorted(country_list, key=lambda country: country[1]) country_list.insert(0, ('', '')) self.fields['country'].choices = country_list
def __init__(self, *args, **kwargs): """Initialize form. Dynamically set choices for country field. """ if 'editable_owner' in kwargs: self.editable_owner = kwargs['editable_owner'] del(kwargs['editable_owner']) super(EventForm, self).__init__(*args, **kwargs) # Dynamic countries field. countries = product_details.get_regions('en').values() countries.sort() country_choices = ([('', "Country")] + [(country, country) for country in countries]) self.fields['country'].choices = country_choices # Dynamic owner field. if self.editable_owner: self.fields['owner_form'] = forms.ModelChoiceField( queryset=User.objects.filter( userprofile__registration_complete=True, groups__name='Rep'), empty_label='Owner', initial=self.instance.owner.pk) else: self.fields['owner_form'] = forms.CharField( required=False, initial=get_full_name(self.instance.owner), widget=forms.TextInput(attrs={'readonly': 'readonly', 'class': 'input-text big'})) instance = self.instance # Dynamically set the year portion of the datetime widget now = datetime.now() start_year = getattr(self.instance.start, 'year', now.year) end_year = getattr(self.instance.end, 'year', now.year) self.fields['start_form'] = forms.DateTimeField( widget=SplitSelectDateTimeWidget( years=range(start_year, now.year + 10), minute_step=5), validators=[validate_datetime]) self.fields['end_form'] = forms.DateTimeField( widget=SplitSelectDateTimeWidget( years=range(end_year, now.year + 10), minute_step=5), validators=[validate_datetime]) # Make times local to venue if self.instance.start: start = make_naive(instance.local_start, timezone(instance.timezone)) self.fields['start_form'].initial = start if self.instance.end: end = make_naive(instance.local_end, timezone(instance.timezone)) self.fields['end_form'].initial = end # Use of intermediate fields to translate between bug.id and # bug.bug_id if instance.budget_bug: self.fields['budget_bug_form'].initial = instance.budget_bug.bug_id if instance.swag_bug: self.fields['swag_bug_form'].initial = instance.swag_bug.bug_id
def __init__(self, locale, *args, **kwargs): regions = product_details.get_regions(locale) regions = sorted(regions.iteritems(), key=lambda x: x[1]) self.locale = locale lang = country = locale.lower() if '-' in lang: lang, country = lang.split('-', 1) super(UserProfileEditForm, self).__init__(*args, **kwargs) # Dynamically add URLFields for all sites defined in the model. sites = kwargs.get('sites', UserProfile.website_choices) for name, meta in sites: self.fields['websites_%s' % name] = forms.RegexField( regex=meta['regex'], required=False) self.fields['websites_%s' % name].widget.attrs['placeholder'] = meta['prefix'] # Newsletter field copied from SubscriptionForm # FIXME: this is extra dupe nasty here because we already have a locale # field on the profile self.fields['country'] = forms.ChoiceField( label=_(u'Your country'), choices=regions, initial=country, required=False )
def __init__(self, locale, *args, **kwargs): regions = product_details.get_regions(locale) regions = sorted(regions.iteritems(), key=lambda x: x[1]) self.locale = locale lang = country = locale.lower() if '-' in lang: lang, country = lang.split('-', 1) super(UserProfileEditForm, self).__init__(*args, **kwargs) # Dynamically add URLFields for all sites defined in the model. sites = kwargs.get('sites', UserProfile.website_choices) for name, meta in sites: self.fields['websites_%s' % name] = forms.RegexField( regex=meta['regex'], required=False) self.fields['websites_%s' % name].widget.attrs['placeholder'] = meta['prefix'] # Newsletter field copied from SubscriptionForm # FIXME: this is extra dupe nasty here because we already have a locale # field on the profile self.fields['country'] = forms.ChoiceField(label=_(u'Your country'), choices=regions, initial=country, required=False)
def __init__(self, *args, **kwargs): locale = kwargs.pop('locale', 'en-US') super(BaseProfileForm, self).__init__(*args, **kwargs) country_list = product_details.get_regions(locale).items() country_list = sorted(country_list, key=lambda country: country[1]) country_list.insert(0, ('', '----')) self.fields['country'].choices = country_list
def fetch_countries(): mozillians_client = MozilliansClient(settings.MOZILLIANS_API_URL, settings.MOZILLIANS_API_KEY) countries = sorted(product_details.get_regions("en-US").values()) for country in countries: vouched = mozillians_client.get_users(params={"is_vouched": True, "country": country})["count"] total = mozillians_client.get_users(params={"country": country})["count"] Country.objects.create(name=country, vouched=vouched, total=total)
def __init__(self, locale, *args, **kw): regions = product_details.get_regions(locale) regions = sorted(regions.iteritems(), key=lambda x: x[1]) super(DevNewsletterForm, self).__init__(*args, **kw) self.fields['country'].choices = regions self.fields['country'].initial = 'us'
def __init__(self, *args, **kwargs): kwargs.pop('lead_source', None) super(ContentServicesForm, self).__init__(*args, **kwargs) locale = kwargs.get('locale', 'en-US') country_list = product_details.get_regions(locale).items() country_list = sorted(country_list, key=lambda country: country[1]) country_list.insert(0, ('', '')) self.fields['country'].choices = country_list
def create_countries(): from snippets.base.models import TargetedCountry for code, name in product_details.get_regions('en-US').items(): country = TargetedCountry.objects.get_or_create(code=code)[0] if country.name != name: country.name = name country.save()
def __init__(self, *args, **kwargs): locale = kwargs.pop("locale", "en-US") super(BaseProfileForm, self).__init__(*args, **kwargs) country_list = product_details.get_regions(locale).items() country_list = sorted(country_list, key=lambda country: country[1]) country_list.insert(0, ("", "----")) self.fields["country"].choices = country_list
def list_profiles(request): """List users in Rep Group.""" countries = product_details.get_regions('en').values() countries.sort() return render(request, 'profiles_people.html', {'countries': countries, 'areas': FunctionalArea.objects.all()})
def __init__(self, *args, **kwargs): locale = kwargs.pop('locale', 'en-US') super(ProfileForm, self).__init__(*args, **kwargs) country_list = product_details.get_regions(locale).items() country_list = sorted(country_list, key=lambda country: country[1]) country_list.insert(0, ('', '----')) self.fields['country'].choices = country_list
def __init__(self, newsletters, locale, data=None, *args, **kwargs): regions = product_details.get_regions(locale) regions = sorted(iter(regions.items()), key=itemgetter(1)) try: if isinstance(newsletters, str): newsletters = newsletters.split(",") 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, ("", ftl_lazy("newsletter-form-select-country-or-region", fallback="newsletter-form-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, ("", ftl_lazy("newsletter-form-available-languages"))) super().__init__(data, *args, **kwargs) required_args = { "required": "required", "aria-required": "true", } country_widget = widgets.Select(attrs=required_args) country_label = ftl_lazy("newsletter-form-select-country-or-region", fallback="newsletter-form-select-country") self.fields["country"] = forms.ChoiceField(widget=country_widget, choices=regions, initial=country, required=False, label=country_label) lang_widget = widgets.Select(attrs=required_args) lang_label = ftl_lazy("newsletter-form-select-language", fallback="newsletter-form-available-languages") self.fields["lang"] = forms.TypedChoiceField(widget=lang_widget, choices=lang_choices, initial=lang, required=False, label=lang_label) self.fields["newsletters"].choices = [(n, self.choice_labels.get(n, n)) for n in newsletters] self.fields["newsletters"].initial = newsletters
def backwards(self, orm): # Translate country code to full country names from product_details import product_details COUNTRIES = product_details.get_regions('en-US') for up in orm.UserProfile.objects.all(): if up.country: up.country = COUNTRIES.get(up.country, '') up.save()
def define_country_field(self): lang = get_language() choices = sorted(product_details.get_regions(lang).items(), key=lambda n: n[1]) # L10n: Used in a dropdown that lets users filter the Leaderboard by # L10n: country. Refers to the default filter, which shows all countries choices.insert(0, ('', _('All'))) self.fields['country'].choices = choices
def forwards(self, orm): # Translate country code to full country names from product_details import product_details COUNTRIES = product_details.get_regions('en-US') for up in orm.UserProfile.objects.all(): if up.country: up.country = COUNTRIES.get(up.country, '') up.save()
def country_name(country_code): """Return a localized version of a country's name.""" locale = get_language() # product_details has no `es` regional information, so we us es-ES instead. if locale == 'es': locale = 'es-ES' return product_details.get_regions(locale)[country_code]
def forwards(self, orm): from product_details import product_details COUNTRIES = product_details.get_regions('en-US') # Reverse dictionary mapping COUNTRIES = dict((v,k) for k, v in COUNTRIES.items()) for up in orm.UserProfile.objects.all(): if up.country: up.country = COUNTRIES.get(up.country, '') up.save()
def __init__(self, locale, *args, **kwargs): regions = product_details.get_regions(locale) regions = sorted(regions.iteritems(), key=lambda x: x[1]) locale = locale.lower() if locale.find('-') != -1: locale = locale.split('-')[1] super(NewsletterCountryForm, self).__init__(*args, **kwargs) self.fields['country'] = forms.ChoiceField(choices=regions, initial=locale)
def get_sorted_countries_list(locale): """Return a localized list of all countries sorted by name.""" countries = product_details.get_regions(locale) countries.update(settings.EXTRA_COUNTRIES) for c_new, c_old in settings.COUNTRY_CODE_MAP.items(): c_old = c_old.lower() if c_old in countries: countries[c_new] = countries[c_old] countries_list = ((code.upper(), name) for code, name in countries.iteritems()) key_function = itemgetter(1) if locale.startswith('en') else uca_sort_key return sorted(countries_list, key=key_function)
def backwards(self, orm): from product_details import product_details COUNTRIES = product_details.get_regions('en-US') # Reverse dictionary mapping COUNTRIES = dict((v,k) for k, v in COUNTRIES.items()) for up in orm.UserProfile.objects.all(): if up.country: up.country = COUNTRIES.get(up.country, '') up.save()
def __init__(self, locale, *args, **kwargs): regions_dict = product_details.get_regions(locale) regions = sorted(iter(regions_dict.items()), 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 "country" in initial and initial["country"] not in regions_dict: # clear the initial country if it's not in the list del initial["country"] 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().__init__(*args, **kwargs) self.fields["country"].choices = regions self.fields["lang"].choices = lang_choices self.already_subscribed = initial.get("newsletters", [])
def __init__(self, *args, **kwargs): super(LeaderboardFilterForm, self).__init__(*args, **kwargs) # Update choices to use the current locale. lang = get_language() choices = sorted(product_details.get_regions(lang).items(), key=lambda n: n[1]) # L10n: Used in a dropdown that lets users filter the Leaderboard by # L10n: country. Refers to the default filter, which shows all countries choices.insert(0, ('', _('All'))) self.fields['country'].choices = choices
def __init__(self, locale, *args, **kwargs): regions = product_details.get_regions(locale) regions = sorted(regions.iteritems(), key=lambda x: x[1]) lang = country = locale.lower() if "-" in lang: lang, country = lang.split("-", 1) lang = lang if lang in LANGS else "en" super(NewsletterForm, self).__init__(*args, **kwargs) self.fields["country"] = forms.ChoiceField(choices=regions, initial=country, required=False) self.fields["lang"] = forms.ChoiceField(choices=self.LANG_CHOICES, initial=lang, required=False)
def __init__(self, locale, *args, **kwargs): super(NewsletterForm, self).__init__(*args, **kwargs) regions = product_details.get_regions(locale) regions = sorted(regions.iteritems(), key=operator.itemgetter(1)) lang = country = locale.lower() if '-' in lang: lang, country = lang.split('-', 1) self.fields['country'].choices = regions self.fields['country'].initial = country
def list_profiles(request): """List users in Rep Group.""" countries = product_details.get_regions("en").values() countries.sort() reps = User.objects.filter(userprofile__registration_complete=True, groups__name="Rep").order_by( "userprofile__country", "last_name", "first_name" ) return render( request, "profiles_people.html", {"countries": countries, "reps": reps, "areas": FunctionalArea.objects.all()} )
def list_profiles(request): """List users in Rep Group.""" countries = product_details.get_regions('en').values() countries.sort() reps = (User.objects .filter(userprofile__registration_complete=True, groups__name='Rep') .order_by('userprofile__country', 'last_name', 'first_name')) return render(request, 'profiles_people.html', {'countries': countries, 'reps': reps, 'areas': FunctionalArea.objects.all()})
def __init__(self, locale, already_subscribed, *args, **kwargs): super(NewsletterForm, self).__init__(*args, **kwargs) self.already_subscribed = already_subscribed regions = product_details.get_regions(locale) regions = sorted(regions.iteritems(), key=operator.itemgetter(1)) lang = country = locale.lower() if "-" in lang: lang, country = lang.split("-", 1) self.fields["country"].choices = regions self.fields["country"].initial = country
def get_sorted_countries_list(locale): """Return a localized list of all countries sorted by name.""" locale = fix_locale(locale) countries = product_details.get_regions(locale) countries.update(settings.EXTRA_COUNTRIES) for c_new, c_old in settings.COUNTRY_CODE_MAP.items(): c_old = c_old.lower() if c_old in countries: countries[c_new] = countries[c_old] countries_list = ((code.upper(), name) for code, name in countries.iteritems()) key_function = itemgetter(1) if locale.startswith('en') else uca_sort_key return sorted(countries_list, key=key_function)
def __init__(self, locale, *args, **kwargs): regions = product_details.get_regions(locale) regions = sorted(regions.iteritems(), key=lambda x: x[1]) lang = country = locale.lower() if "-" in lang: lang, country = lang.split("-", 1) super(SubscriptionForm, self).__init__(*args, **kwargs) self.fields["country"] = forms.ChoiceField( label=_(u"Your country"), choices=regions, initial=country, required=False )
def fetch_countries(): mozillians_client = MozilliansClient(settings.MOZILLIANS_API_URL, settings.MOZILLIANS_API_KEY) countries = sorted(product_details.get_regions('en-US').values()) for country in countries: vouched = mozillians_client.get_users(params={ 'is_vouched': True, 'country': country })['count'] total = mozillians_client.get_users( params={'country': country})['count'] Country.objects.create(name=country, vouched=vouched, total=total)
def __init__(self, locale, *args, **kwargs): regions = product_details.get_regions(locale) regions = sorted(regions.iteritems(), key=lambda x: x[1]) lang = country = locale.lower() if '-' in lang: lang, country = lang.split('-', 1) super(SubscriptionForm, self).__init__(*args, **kwargs) self.fields['country'] = forms.ChoiceField(label=_(u'Your country'), choices=regions, initial=country, required=False)
def kpi(request): countries = product_details.get_regions('en').values() countries.sort() categories = FunctionalArea.active_objects.all() initiatives = Campaign.active_objects.all() reps = (User.objects.filter(userprofile__registration_complete=True, groups__name='Rep') .order_by('userprofile__country', 'last_name', 'first_name')) return render(request, 'kpi.jinja', {'reps': reps, 'countries': countries, 'categories': categories, 'initiatives': initiatives})
def __init__(self, user, *args, **kwargs): super(NewsletterSubscriptionForm, self).__init__(*args, **kwargs) # TODO: Figure out how to not duplciate code from the # LeaderboardFilterForm. The main issue right now is that ChoiceFields # have nothing that runs when a form using it is initiated. # Update choices to use the current locale. lang = get_language() choices = sorted(product_details.get_regions(lang).items(), key=lambda n: n[1]) self.fields['country'].choices = choices self.fields['country'].initial = user.country
def __init__(self, locale, *args, **kwargs): regions = product_details.get_regions(locale) regions = sorted(regions.iteritems(), key=lambda x: x[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 __init__(self, locale, request=None, *args, **kwargs): regions = product_details.get_regions(locale) regions = sorted(regions.iteritems(), key=lambda x: x[1]) self.locale = locale lang = country = locale.lower() if '-' in lang: lang, country = lang.split('-', 1) super(BrowserIDRegisterForm, self).__init__(request, *args, **kwargs) # Newsletter field copied from SubscriptionForm self.fields['country'] = forms.ChoiceField(label=_(u'Your country'), choices=regions, initial=country, required=False)
def __init__(self, newsletters, locale, data=None, *args, **kwargs): regions = product_details.get_regions(locale) regions = sorted(iter(regions.items()), 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, ('', ftl_lazy('newsletter-form-select-country-or-region', fallback='newsletter-form-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, ('', ftl_lazy('newsletter-form-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 __init__(self, *args, **kwargs): """Initialize form. Dynamically set choices for country fields. """ self.request = kwargs.pop('request', None) super(ChangeProfileForm, self).__init__(*args, **kwargs) countries = product_details.get_regions('en').values() countries.sort() country_choices = ([('', "Country")] + [(country, country) for country in countries]) self.fields['country'].choices = country_choices timezone_choices = ([('', 'Timezone')] + zip(common_timezones, common_timezones)) self.fields['timezone'].choices = timezone_choices