Beispiel #1
0
 def add_arguments(self, parser):
     """
     The command can be given a list of ISO country codes to update,
     as an argument. A missing argument or the word "ALL" mean that
     all countries in the local database will be refreshed.
     """
     parser.add_argument(
         'update_countries',
         nargs='*',
         choices=tuple(sorted(COUNTRIES.keys())) + ('ALL', ),
         default='ALL',
         metavar='country code',
         help=
         "one or more country codes to update, omit to update all countries."
     )
     parser.add_argument(
         '-s',
         '--start-from',
         default='AA',
         choices='ABCDEFGHIJKLMNOPQRSTUVWXYZ',
         help="when all countries are being updated, begin with the ISO code "
         "starting with this letter.")
     parser.add_argument(
         '-e',
         '--end-before',
         default='ZZ',
         choices='ABCDEFGHIJKLMNOPQRSTUVWXYZ',
         help=
         "when all countries are being updated, stop before the ISO code "
         "starting with this letter.")
 def country_response(self):
     from django_countries.data import COUNTRIES
     countries = sorted(list(COUNTRIES.items()), key=lambda x: x[1].encode('utf-8'))
     if self.search_string:
         search_string = self.search_string.lower()
         return [x for x in countries if x[1].lower().startswith(search_string)]
     return countries
Beispiel #3
0
class ShippingMethodCountry(models.Model):

    ANY_COUNTRY = ''
    COUNTRY_CODE_CHOICES = [(ANY_COUNTRY, _('Any country'))] + list(
        COUNTRIES.items())

    country_code = models.CharField(choices=COUNTRY_CODE_CHOICES,
                                    max_length=2,
                                    blank=True,
                                    default=ANY_COUNTRY)
    price = PriceField(pgettext_lazy('Shipping method region field', 'price'),
                       currency=settings.DEFAULT_CURRENCY,
                       max_digits=12,
                       decimal_places=2)
    shipping_method = models.ForeignKey(ShippingMethod,
                                        related_name='price_per_country')

    objects = ShippingMethodCountryQueryset.as_manager()

    class Meta:
        unique_together = ('country_code', 'shipping_method')

    def __str__(self):
        # https://docs.djangoproject.com/en/dev/ref/models/instances/#django.db.models.Model.get_FOO_display  # noqa
        return "%s %s" % (self.shipping_method,
                          self.get_country_code_display())

    def get_total(self):
        return self.price
Beispiel #4
0
class WhereaboutsFactory(DjangoModelFactory):
    class Meta:
        model = 'hosting.Whereabouts'

    type = Faker('random_element', elements=[ch.value for ch in LocationType])

    @factory.lazy_attribute
    def name(self):
        return Faker._get_faker().city().upper()

    @factory.lazy_attribute
    def state(self):
        if self.country in countries_with_mandatory_region():
            return CountryRegionFactory(country=self.country).iso_code
        else:
            return ""

    country = Faker('random_element', elements=COUNTRIES.keys())

    @factory.lazy_attribute
    def bbox(self):
        minx, miny, maxx, maxy = self.center.buffer(width=uniform_random(
            0.05, 0.45),
                                                    quadsegs=2).extent
        return LineString((minx, miny), (maxx, maxy), srid=SRID)

    @factory.lazy_attribute
    def center(self):
        # Cannot use the 'local_latlng' Faker, they don't have all countries in the database!
        return Point([
            uniform_random(a, b)
            for a, b in zip(*COUNTRIES_GEO[self.country]['bbox'].values())
        ],
                     srid=SRID)
Beispiel #5
0
 def country_response(self):
     from django_countries.data import COUNTRIES
     countries = sorted(list(COUNTRIES.items()), key=lambda x: x[1].encode('utf-8'))
     if self.search_string:
         search_string = self.search_string.lower()
         return [x for x in countries if x[1].lower().startswith(search_string)]
     return countries
Beispiel #6
0
 def lookups(self, request, queryset):
     from apps.accounts.models import Hostingprovider
     qs = Hostingprovider.objects.all().values_list(
         'country', flat=True).distinct().order_by('country')
     countries = [(country, COUNTRIES.get(country, 'Unknown Country'))
                  for country in qs]
     return countries
Beispiel #7
0
class SignupForm(forms.Form):
    first_name = forms.CharField(max_length=30, label=_('First Name'), required=False)
    last_name = forms.CharField(max_length=30, label=_('Last Name'), required=False)
    send_email = forms.BooleanField(label=_('I want to receive newsletters'), required=False)
    birthday_day = forms.IntegerField(label=_('Birthday'), required=False)
    birthday_month = forms.IntegerField(label=_('Birthday'), required=False)
    birthday_year = forms.IntegerField(label=_('Birthday'), required=False)
    country = forms.ChoiceField(label=_('Country'), required=False, choices=sorted(COUNTRIES.items(), key=lambda tup: tup[1]))
    city = forms.ModelChoiceField(Choices.objects.filter(kind=Choices.KINDS.city), required=False, label=_('City'), empty_label=_("City"))
    bike_brand = forms.ModelChoiceField(Choices.objects.filter(kind=Choices.KINDS.bike_brand), required=False, label=_('Bike Brand'), empty_label=_("Bike Brand"))
    phone_number = forms.CharField(required=False, label=_('Phone number'))

    def __init__(self, *args, **kwargs):
        super(SignupForm, self).__init__(*args, **kwargs)
        self.fields['country'].initial = 'LV'

    def signup(self, request, user):
        user.first_name = self.cleaned_data['first_name']
        user.last_name = self.cleaned_data['last_name']
        user.send_email = self.cleaned_data['send_email']
        user.country = self.cleaned_data['country']
        user.city = self.cleaned_data['city']
        user.bike_brand = self.cleaned_data['bike_brand']
        user.phone_number = self.cleaned_data['phone_number']
        try:
            user.birthday = datetime.date(self.cleaned_data['birthday_year'], self.cleaned_data['birthday_month'], self.cleaned_data['birthday_day'])
        except:
            print("WRONG DATE")

        user.save()
Beispiel #8
0
class FilterForm(forms.Form):
    destination = forms.CharField(widget=forms.Select(
        choices=sorted(COUNTRIES.items(), key=operator.itemgetter(1)),
        attrs={
            'class': 'selectpicker form-control bg-white border filterr',
            'multiple': '',
            'data-live-search': 'true',
            'title': 'Selectioner Pays'
        }),
                                  required='false')
    wilaya = forms.CharField(widget=forms.Select(
        choices=WILAYA_CHOICES,
        attrs={
            'class': 'selectpicker form-control bg-white border filterr',
            'multiple': '',
            'data-live-search': 'true',
            'title': 'Wilaya'
        }),
                             required=False)
    minprice = forms.CharField(
        widget=forms.NumberInput(attrs={'class': 'form-control filterr'}),
        required=False)
    maxprice = forms.CharField(
        widget=forms.NumberInput(attrs={'class': 'form-control filterr'}),
        required=False)
    mincommission = forms.CharField(
        widget=forms.NumberInput(attrs={'class': 'form-control filterr'}),
        required=False)
    maxcommission = forms.CharField(
        widget=forms.NumberInput(attrs={'class': 'form-control filterr'}),
        required=False)
    mot_cle = forms.CharField(
        widget=forms.TextInput(attrs={'class': 'form-control filterr'}),
        required=False)
Beispiel #9
0
def scoreboard(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect(reverse('login'))

    categories = QuestionCategory.objects.all()
    countries = COUNTRIES.items()
    country = request.POST['country'] if request.POST.has_key('country') else None
    category = request.POST['cat_id'] if request.POST.has_key('cat_id') else None
    selected_country = country.split('\'')[1] if country else None
    quizs = Quiz.objects.all()
    if category:
        quizs = quizs.filter(category__id=category)
    scores = {}
    for q in quizs:
        if q.competitor1.user.first_name in scores:
            scores[q.competitor1.user.first_name] = scores[q.competitor1.user.first_name]+(q.score1 or 0)
        else:
            if q.competitor1.nationality.code == selected_country or not selected_country:
                scores[q.competitor1.user.first_name] = (q.score1 or 0)

        if q.competitor2.user.first_name in scores:
            scores[q.competitor2.user.first_name] = scores[q.competitor2.user.first_name]+(q.score2 or 0)
        else:
            if q.competitor2.nationality.code == selected_country or not selected_country:
                scores[q.competitor2.user.first_name] = (q.score2 or 0)
    scores = sorted(scores.items(), key=operator.itemgetter(1), reverse=True)[:5]
    return render_to_response('quiz/scoreboard.html', {'cats':categories, 'category':int(category) if category else category, 'countries':countries, 'selected_country':selected_country, 'scores':scores}, context_instance=RequestContext(request))
Beispiel #10
0
    def __init__(self,
                 account,
                 domain,
                 creating_user,
                 data=None,
                 *args,
                 **kwargs):
        super(ConfirmExtraUserChargesForm, self).__init__(account,
                                                          domain,
                                                          creating_user,
                                                          data=data,
                                                          *args,
                                                          **kwargs)

        from corehq.apps.users.views.mobile import MobileWorkerListView
        self.helper.label_class = 'col-sm-3 col-md-2'
        self.helper.field_class = 'col-sm-9 col-md-8 col-lg-6'
        self.helper.layout = crispy.Layout(
            crispy.Fieldset(
                _("Basic Information"),
                'company_name',
                'first_name',
                'last_name',
                crispy.Field(
                    'email_list',
                    css_class='input-xxlarge accounting-email-select2',
                    data_initial=json.dumps(self.initial.get('email_list'))),
                'phone_number',
            ),
            crispy.Fieldset(
                _("Mailing Address"),
                'first_line',
                'second_line',
                'city',
                'state_province_region',
                'postal_code',
                crispy.Field(
                    'country',
                    css_class="input-large accounting-country-select2",
                    data_country_code=self.current_country or '',
                    data_country_name=COUNTRIES.get(self.current_country, '')),
            ),
            hqcrispy.FormActions(
                crispy.HTML(
                    '<a href="%(user_list_url)s" class="btn btn-default">%(text)s</a>'
                    % {
                        'user_list_url':
                        reverse(MobileWorkerListView.urlname,
                                args=[self.domain]),
                        'text':
                        _("Back to Mobile Workers List")
                    }),
                StrictButton(
                    _("Confirm Billing Information"),
                    type="submit",
                    css_class='btn btn-primary disabled',
                ),
            ),
        )
class locationForm(forms.Form):
    zip = forms.IntegerField()
    country = forms.ChoiceField(choices=sorted(COUNTRIES.items()))
    city = forms.CharField(max_length=255)

    class Meta:
        model = Zip
        fields = ('zip', 'country', 'city')
Beispiel #12
0
 def country_response(self):
     from django_countries.data import COUNTRIES
     countries = sorted(COUNTRIES.items(),
                        key=lambda x: x[1].encode('utf-8'))
     if self.search_string:
         return filter(
             lambda x: x[1].lower().startswith(self.search_string.lower()),
             countries)
     return countries
Beispiel #13
0
class TravelAdviceFactory(DjangoModelFactory):
    class Meta:
        model = 'hosting.TravelAdvice'

    class Params:
        in_past, in_present, in_future = None, None, None

    content = Faker('paragraph')
    description = factory.LazyAttribute(
        lambda obj: '<p>{}</p>'.format(obj.content))
    countries = Faker('random_elements',
                      elements=COUNTRIES.keys(),
                      unique=True,
                      length=factory.LazyFunction(lambda: randint(1, 4)))

    @factory.lazy_attribute
    def active_from(self):
        faker = Faker._get_faker()
        if self.in_past:
            faked_date = faker.optional_value('date_between',
                                              start_date='-365d',
                                              end_date='-200d')
        elif self.in_future:
            faked_date = faker.date_between(start_date='+2d', end_date='+199d')
        elif self.in_present:
            faked_date = faker.optional_value('date_between',
                                              start_date='-200d',
                                              end_date='-2d')
        else:
            faked_date = faker.optional_value('date_object',
                                              end_datetime='+5y')
        return faked_date

    @factory.lazy_attribute
    def active_until(self):
        faker = Faker._get_faker()
        if self.in_past:
            faked_date = faker.date_between(start_date='-199d', end_date='-2d')
        elif self.in_future:
            faked_date = faker.optional_value('date_between',
                                              start_date='+200d',
                                              end_date='+365d')
        elif self.in_present:
            faked_date = faker.optional_value('date_between',
                                              start_date='+2d',
                                              end_date='+200d')
        else:
            if self.active_from:
                start, end = self.active_from, self.active_from + timedelta(
                    days=365)
                faked_date = faker.optional_value('date_between_dates',
                                                  date_start=start,
                                                  date_end=end)
            else:
                faked_date = faker.optional_value('date_object',
                                                  end_datetime='+5y')
        return faked_date
Beispiel #14
0
class CreateJob(forms.ModelForm):
    FT = 'Fulltime'
    PT = 'Parttime'
    IN = 'Internship'
    RE = 'Remote'
    workoptions = (('Fulltime', FT), ('Parttime', PT), ('Internship', IN),
                   ('Remote', RE))
    position = forms.CharField(
        label='Position',
        required=True,
        widget=forms.TextInput(attrs={'class': "form-control"}))
    companyName = forms.CharField(
        label='Company Name',
        required=True,
        widget=forms.TextInput(attrs={'class': "form-control"}))
    location = forms.ChoiceField(
        choices=sorted(COUNTRIES.items()),
        widget=forms.Select(attrs={'class': "form-control"}))
    category = forms.ChoiceField(
        choices=workoptions,
        widget=forms.Select(attrs={'class': "form-control"}))
    companyEmail = forms.EmailField(
        label='Company Email',
        required=True,
        widget=forms.TextInput(attrs={'class': "form-control"}))
    companyApplyUrl = forms.URLField(
        label='Apply Url',
        required=True,
        widget=forms.TextInput(attrs={'class': "form-control"}))
    jobResp = forms.CharField(
        label='Job Responsiblities',
        required=True,
        widget=forms.Textarea(attrs={'class': "form-control"}))
    jobReq = forms.CharField(
        label='Job Requirement',
        required=True,
        widget=forms.Textarea(attrs={'class': "form-control"}))
    jobDesc = forms.CharField(
        label='Job Description',
        required=True,
        widget=forms.Textarea(attrs={'class': "form-control"}))
    salary = forms.IntegerField(
        label='Salary',
        required=False,
        widget=forms.TextInput(attrs={'class': "form-control"}))
    tags = forms.CharField(
        label='Tags',
        required=True,
        widget=forms.TextInput(attrs={'class': "form-control"}))

    class Meta:
        model = models.Job
        fields = [
            'position', 'location', 'category', 'companyName', 'companyLogo',
            'companyEmail', 'companyApplyUrl', 'jobResp', 'jobReq', 'jobDesc',
            'salary', 'tags'
        ]
Beispiel #15
0
class RegistrationForm(forms.ModelForm):
    """
    Form for registering a new account.
    """
    username = forms.EmailField(widget=forms.widgets.TextInput(),
                                label="Email")
    password1 = forms.CharField(widget=forms.widgets.PasswordInput(),
                                label="Password")
    password2 = forms.CharField(widget=forms.widgets.PasswordInput(),
                                label="Password (again)")

    nickname = forms.CharField(widget=forms.widgets.TextInput(),
                               label="Annotator pseudonym")
    first_name = forms.CharField(widget=forms.widgets.TextInput(),
                                 label="First name")
    last_name = forms.CharField(widget=forms.widgets.TextInput(),
                                label="Last name")
    job_title = forms.CharField(widget=forms.widgets.TextInput(),
                                label="Job title")
    organization = forms.CharField(widget=forms.widgets.TextInput(),
                                   label="Organization")
    country = forms.ChoiceField(widget=forms.Select(),
                                choices=sorted(COUNTRIES.items()))
    annotator_exp = forms.ChoiceField(widget=forms.Select(),
                                      choices=[('b', 'Beginner'),
                                               ('i', 'Intermediate'),
                                               ('e', 'Expert')],
                                      label="Annotator experience")

    class Meta:
        model = UserCred
        fields = [
            'username', 'password1', 'password2', 'nickname', 'first_name',
            'last_name', 'job_title', 'organization', 'annotator_exp',
            'country'
        ]

    def save(self, commit=True):
        print type(self)
        user = super(RegistrationForm, self).save(commit=False)
        user.set_password("password")
        if commit:
            ap = AnnotatorProfile(
                nickname=self.cleaned_data["nickname"],
                first_name=self.data["auth_firstname"],
                last_name=self.data["auth_lastname"],
                email=self.data["auth_email"],
                country=self.cleaned_data["country"],
                organization=self.cleaned_data["organization"],
                job_title=self.cleaned_data["job_title"],
                annotator_exp=self.cleaned_data["annotator_exp"])
            ap.save(using='users')
            user.annotator_id = ap

            user.save(using='users')
        return user
Beispiel #16
0
def check_ioc_countries():
    """
    Check if all IOC codes map to ISO codes correctly
    """
    from django_countries.data import COUNTRIES

    print("Checking if all IOC codes map correctly")
    for key in ISO_TO_IOC.keys():
        assert COUNTRIES.get(key, '') != '', 'No ISO code for %s' % key
    print("Finished checking IOC codes")
def check_ioc_countries():
    """
    Check if all IOC codes map to ISO codes correctly
    """
    from django_countries.data import COUNTRIES

    print("Checking if all IOC codes map correctly")
    for key in ISO_TO_IOC:
        assert COUNTRIES.get(key), 'No ISO code for %s' % key
    print("Finished checking IOC codes")
Beispiel #18
0
class PlaceFactory(DjangoModelFactory):
    class Meta:
        model = 'hosting.Place'

    owner = factory.SubFactory('tests.factories.ProfileFactory')
    country = Faker('random_element', elements=COUNTRIES.keys())

    @factory.lazy_attribute
    def state_province(self):
        if self.country in countries_with_mandatory_region():
            region = CountryRegionFactory(country=self.country)
            return region.iso_code
        else:
            return ""

    city = Faker('city')
    address = Faker('address')

    @factory.lazy_attribute
    def location(self):
        # Cannot use the 'local_latlng' Faker, they don't have all countries in the database!
        return Point([
            uniform_random(a, b)
            for a, b in zip(*COUNTRIES_GEO[self.country]['bbox'].values())
        ],
                     srid=SRID)

    description = Faker('paragraph', nb_sentences=4)
    short_description = Faker('text', max_nb_chars=140)
    in_book = False

    @staticmethod
    def generate_postcode(country):
        regex = COUNTRIES_DATA[country]['postcode_regex'] or r'\d{5}'
        # The * repetition qualifier makes the generator go wild, strictly limit to 1 copy.
        regex = regex.replace('*', '{1}')
        # Articially limit the length of overly permissive chunks.
        regex = re.sub(r'{0,\d\d}', '{0,2}', regex)
        # Generate a random value according to the constrained regular expression.
        # All whitespaces are condensed to single space and the value is uppercased.
        value = ""
        while value in ("", "GIR0AA", "GIR 0AA"):
            # The generator has a strong preference to this UK postal code...
            value = ' '.join(rstr.xeger(regex).upper().strip().split())
        return value

    @factory.post_generation
    def postcode(instance, create, value, **kwargs):
        if not value:
            return
        if value is True:
            instance.postcode = PlaceFactory.generate_postcode(
                instance.country)
        else:
            instance.postcode = value
Beispiel #19
0
    def __init__(self, account, domain, creating_user, data=None, *args, **kwargs):
        super(ConfirmExtraUserChargesForm, self).__init__(account, domain, creating_user, data=data, *args, **kwargs)
        self.fields['confirm_product_agreement'].label = _(
            'I have read and agree to the <a href="%(pa_url)s" target="_blank">'
            'Software Product Subscription Agreement</a>.'
        ) % {'pa_url': reverse('product_agreement')}

        from corehq.apps.users.views.mobile import MobileWorkerListView
        self.helper.label_class = 'col-sm-3 col-md-2'
        self.helper.field_class = 'col-sm-9 col-md-8 col-lg-6'
        self.helper.layout = crispy.Layout(
            crispy.Fieldset(
                _("Basic Information"),
                'company_name',
                'first_name',
                'last_name',
                crispy.Field('email_list', css_class='input-xxlarge'),
                'phone_number',
            ),
            crispy.Fieldset(
                 _("Mailing Address"),
                'first_line',
                'second_line',
                'city',
                'state_province_region',
                'postal_code',
                crispy.Field('country', css_class="input-large",
                             data_countryname=COUNTRIES.get(self.current_country, '')),
            ),
            hqcrispy.B3MultiField(
                '',
                crispy.Field('confirm_product_agreement'),
            ),
            hqcrispy.FormActions(
                crispy.HTML(
                    '<a href="%(user_list_url)s" class="btn btn-default">%(text)s</a>' % {
                        'user_list_url': reverse(MobileWorkerListView.urlname, args=[self.domain]),
                        'text': _("Back to Mobile Workers List")
                    }
                ),
                StrictButton(
                    _("Confirm Billing Information"),
                    type="submit",
                    css_class='btn btn-primary disabled',
                    disabled="disabled",
                    css_id="submit-button-pa",
                ),
                crispy.HTML(
                    '<p class="help-inline" id="submit-button-help-qa" style="vertical-align: '
                    'top; margin-top: 5px; margin-bottom: 0px;">%s</p>' % _("Please agree to the Product Subscription "
                                                                            "Agreement above before continuing.")
                ),
            ),
        )
Beispiel #20
0
    def __init__(self, account, domain, creating_user, data=None, *args, **kwargs):
        super(ConfirmExtraUserChargesForm, self).__init__(account, domain, creating_user, data=data, *args, **kwargs)
        self.fields['confirm_product_agreement'].label = _(
            'I have read and agree to the <a href="%(pa_url)s" target="_blank">'
            'Software Product Subscription Agreement</a>.'
        ) % {'pa_url': reverse('product_agreement')}

        from corehq.apps.users.views.mobile import MobileWorkerListView
        self.helper.label_class = 'col-sm-3 col-md-2'
        self.helper.field_class = 'col-sm-9 col-md-8 col-lg-6'
        self.helper.layout = crispy.Layout(
            crispy.Fieldset(
                _("Basic Information"),
                'company_name',
                'first_name',
                'last_name',
                crispy.Field('email_list', css_class='input-xxlarge ko-email-select2'),
                'phone_number',
            ),
            crispy.Fieldset(
                 _("Mailing Address"),
                'first_line',
                'second_line',
                'city',
                'state_province_region',
                'postal_code',
                crispy.Field('country', css_class="input-large ko-country-select2",
                             data_countryname=COUNTRIES.get(self.current_country, '')),
            ),
            hqcrispy.B3MultiField(
                '',
                crispy.Field('confirm_product_agreement'),
            ),
            hqcrispy.FormActions(
                crispy.HTML(
                    '<a href="%(user_list_url)s" class="btn btn-default">%(text)s</a>' % {
                        'user_list_url': reverse(MobileWorkerListView.urlname, args=[self.domain]),
                        'text': _("Back to Mobile Workers List")
                    }
                ),
                StrictButton(
                    _("Confirm Billing Information"),
                    type="submit",
                    css_class='btn btn-primary disabled',
                    disabled="disabled",
                    css_id="submit-button-pa",
                ),
                crispy.HTML(
                    '<p class="help-inline" id="submit-button-help-qa" style="vertical-align: '
                    'top; margin-top: 5px; margin-bottom: 0px;">%s</p>' % _("Please agree to the Product Subscription "
                                                                            "Agreement above before continuing.")
                ),
            ),
        )
Beispiel #21
0
def all_members(request):
    try:
        document = Documents.objects.get(user=request.user)
    except:
        pass
    countries = sorted([i[1] for i in COUNTRIES.items()])

    users = User.objects.all()


    return render(request, 'main/all_members.html', locals())
Beispiel #22
0
class PIRForm(forms.Form):
    name = fields.CharField(
        required=True,
        label=_('Name'),
    )
    company = fields.CharField(
        required=True,
        label=_('Company'),
    )

    email = fields.EmailField(
        required=True,
        label=_('Email'),
    )

    phone_number = fields.CharField(
        required=False,
        label=_('Phone number (optional)'),
        widget=TextInput(attrs={'type': 'tel'})
    )

    country = fields.ChoiceField(
        required=True,
        label=_('Country'),
        choices=sorted(
            [(k, v) for k, v in COUNTRIES.items()],
            key=lambda tup: tup[1]
        )
    )

    gdpr_optin = fields.BooleanField(initial=False, required=False)

    def __init__(self, *args, **kwargs):
        super(PIRForm, self).__init__(*args, **kwargs)
        self.client = PIRAPIClient(
            base_url=settings.PIR_API_URL,
            api_key=settings.PIR_API_KEY
        )

        options = self.client.get_options()

        sector_choices = [
            (
                o['value'],
                o['display_name']) for o in options['sector']['choices']
        ]

        self.fields['sector'] = fields.ChoiceField(
            label='Sector',
            choices=sector_choices
        )

        self.fields['captcha'] = NoReCaptchaField()
def check_ioc_countries(verbosity=1):
    """
    Check if all IOC codes map to ISO codes correctly
    """
    from django_countries.data import COUNTRIES

    if verbosity:  # pragma: no cover
        print("Checking if all IOC codes map correctly")
    for key in ISO_TO_IOC:
        assert COUNTRIES.get(key), "No ISO code for %s" % key
    if verbosity:  # pragma: no cover
        print("Finished checking IOC codes")
Beispiel #24
0
class VisaFormUpdate(ModelForm):
    destination = forms.CharField(widget=forms.Select(
        choices=sorted(COUNTRIES.items(), key=operator.itemgetter(1)),
        attrs={
            'class': 'selectpicker form-control bg-white border',
            'data-live-search': 'true',
            'title': 'Destination'
        }), )

    class Meta:
        model = Visa
        exclude = ['user', 'slug']
Beispiel #25
0
def check_ioc_countries(verbosity=1):
    """
    Check if all IOC codes map to ISO codes correctly
    """
    from django_countries.data import COUNTRIES

    if verbosity:  # pragma: no cover
        print("Checking if all IOC codes map correctly")
    for key in ISO_TO_IOC:
        assert COUNTRIES.get(key), 'No ISO code for %s' % key
    if verbosity:  # pragma: no cover
        print("Finished checking IOC codes")
Beispiel #26
0
    def __init__(self, account, domain, creating_user, data=None, *args, **kwargs):
        super(ConfirmExtraUserChargesForm, self).__init__(account, domain, creating_user, data=data, *args, **kwargs)
        self.fields["confirm_product_agreement"].label = _(
            'I have read and agree to the <a href="%(pa_url)s" target="_blank">'
            "Software Product Subscription Agreement</a>."
        ) % {"pa_url": reverse("product_agreement")}

        from corehq.apps.users.views.mobile import MobileWorkerListView

        self.helper.layout = crispy.Layout(
            crispy.Fieldset(
                _("Basic Information"),
                "company_name",
                "first_name",
                "last_name",
                crispy.Field("emails", css_class="input-xxlarge"),
                "phone_number",
            ),
            crispy.Fieldset(
                _("Mailing Address"),
                "first_line",
                "second_line",
                "city",
                "state_province_region",
                "postal_code",
                crispy.Field(
                    "country", css_class="input-large", data_countryname=COUNTRIES.get(self.current_country, "")
                ),
            ),
            crispy.Field("confirm_product_agreement"),
            FormActions(
                crispy.HTML(
                    '<a href="%(user_list_url)s" class="btn">%(text)s</a>'
                    % {
                        "user_list_url": reverse(MobileWorkerListView.urlname, args=[self.domain]),
                        "text": _("Back to Mobile Workers List"),
                    }
                ),
                StrictButton(
                    _("Confirm Billing Information"),
                    type="submit",
                    css_class="btn btn-primary disabled",
                    disabled="disabled",
                    css_id="submit-button-pa",
                ),
                crispy.HTML(
                    '<p class="help-inline" id="submit-button-help-qa" style="vertical-align: '
                    'top; margin-top: 5px; margin-bottom: 0px;">%s</p>'
                    % _("Please agree to the Product Subscription " "Agreement above before continuing.")
                ),
            ),
        )
Beispiel #27
0
def check_ioc_countries(verbosity=1):
    """
    Check if all IOC codes map to ISO codes correctly
    """
    from django_countries.data import COUNTRIES

    if verbosity:  # pragma: no cover
        print("Checking if all IOC codes map correctly")
    for key in ISO_TO_IOC:
        if not COUNTRIES.get(key):  # pragma: no cover
            raise KeyError(f"No ISO code for {key}")
    if verbosity:  # pragma: no cover
        print("Finished checking IOC codes")
Beispiel #28
0
def filter_country(request, country):
    try:
        document = Documents.objects.get(user=request.user)
    except:
        pass
    if country == 'ALL':
        return redirect('main:all_members')
    countries = sorted([i[1] for i in COUNTRIES.items()])
    filter_ = [i[0] for i in COUNTRIES.items() if i[1] == country][0]

    users = User.objects.filter(country=filter_)

    page = request.GET.get('page', 1)

    paginator = Paginator(users, 150)
    try:
        users = paginator.page(page)
    except PageNotAnInteger:
        users = paginator.page(1)
    except EmptyPage:
        users = paginator.page(paginator.num_pages)

    return render(request, 'main/all_members.html', locals())
Beispiel #29
0
class CountryRegionFactory(DjangoModelFactory):
    class Meta:
        model = 'hosting.CountryRegion'

    class Params:
        short_code = factory.LazyFunction(lambda: random() < 0.20)

    country = Faker('random_element', elements=COUNTRIES.keys())
    iso_code = Faker('pystr_format',
                     string_format='???#',
                     letters='ABCDEFGHJKLMNPQRSTUVWXYZ')
    latin_code = factory.Maybe('short_code',
                               yes_declaration=Faker(
                                   'pystr_format',
                                   string_format='??',
                                   letters='ABCDEFGHIJKLMNOPQRSTUVWXYZ'),
                               no_declaration=Faker('sentence', nb_words=3))
    latin_name = factory.Maybe('short_code',
                               yes_declaration=Faker('sentence', nb_words=3),
                               no_declaration="")

    @factory.lazy_attribute
    def esperanto_name(self):
        latin_region = self.latin_name or self.latin_code
        replacements = [
            ('Q', 'Kv'),
            ('q', 'kv'),
            ('W', 'V'),
            ('w', 'v'),
            ('X', 'Ks'),
            ('x', 'ks'),
            ('Y', 'J'),
            ('y ', 'i '),
            ('y.', 'i.'),
            ('y', 'j'),
            ('Ph', 'F'),
            ('ph', 'f'),
            ('Th', 'Z'),
            ('th', 'z'),
            ('cc', 'k'),
            ('ee', 'i'),
            ('ll', 'l'),
            ('tt', 't'),
            (' ', '-'),
            ('.', 'o'),
        ]
        for lat_letter, esp_letter in replacements:
            latin_region = latin_region.replace(lat_letter, esp_letter)
        return latin_region
Beispiel #30
0
 def add_arguments(self, parser):
     """
     The command can be given a list of ISO country codes to update,
     as an argument. A missing argument or the word "ALL" mean that
     all countries in the local database will be refreshed.
     """
     parser.add_argument(
         'update_countries',
         nargs='*',
         choices=tuple(COUNTRIES.keys()) + ('ALL', ),
         default='ALL',
         metavar='country code',
         help=
         "one or more country codes to update, omit to update all countries."
     )
Beispiel #31
0
class User(AbstractUser):
    """
    Модель профиль пользователя.
    Расширение стандартной модели юзера.
    """
    GENDER_CHOICES = (('male', 'Male'), ('female', 'Female'))

    username = models.CharField(max_length=30, unique=True)
    name = models.CharField(max_length=30)
    email = models.EmailField(unique=True)

    avatar = models.ImageField(upload_to='uploads/avatar',
                               blank=True,
                               null=True)
    header = models.ImageField(upload_to='uploads/headers',
                               blank=True,
                               null=True)
    description = models.TextField(max_length=160, null=True, blank=True)

    first_name = models.CharField(max_length=30, null=True, blank=True)
    last_name = models.CharField(max_length=30, null=True, blank=True)
    phone_number = models.CharField(max_length=11, blank=True, null=True)
    date_of_birth = models.DateField(blank=True, null=True)
    gender = models.CharField(max_length=6,
                              choices=GENDER_CHOICES,
                              null=True,
                              blank=True)
    country = models.CharField(max_length=30,
                               choices=sorted(COUNTRIES.items()),
                               null=True,
                               blank=True)
    location = models.CharField(max_length=20, blank=True, null=True)
    site = models.URLField(max_length=100, blank=True, null=True)

    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['name']

    def save(self, *args, **kwargs):
        is_creating = not self.pk

        if not self.name and is_creating:
            # При создании пользователя  name = username
            self.name = self.username
        super().save(*args, **kwargs)

    def __str__(self):
        return f'@{self.username}'
Beispiel #32
0
class UserForm(forms.ModelForm):
    # date_of_birth = forms.DateField(required=False)
    # date_of_birth = forms.CharField()
    facebook_profile = forms.URLField(max_length=150, required=False)
    phone = forms.CharField(max_length=11, required=False)
    country = forms.ChoiceField(choices=sorted(COUNTRIES.items()))

    class Meta:
        model = MyUser
        fields = [
            'first_name', 'last_name', 'phone', 'date_of_birth', 'country',
            'facebook_profile'
        ]
        widgets = {
            'country': CountrySelectWidget(),
            'date_of_birth': DateInput(attrs={'type': 'date'})
        }
Beispiel #33
0
    def countries(self):
        """
        Return the countries list, modified by any overriding settings.
        The result is cached so future lookups are less work intensive.
        """
        # Local import so that countries aren't loaded into memory until first
        # used.
        from django_countries.data import COUNTRIES

        if not hasattr(self, '_countries'):
            self._countries = []
            overrides = settings.COUNTRIES_OVERRIDE
            for code, name in COUNTRIES.items():
                if code in overrides:
                    name = overrides['code']
                if name:
                    self.countries.append((code, name))
        return self._countries
Beispiel #34
0
    def countries(self):
        """
        Return the countries list, modified by any overriding settings.
        The result is cached so future lookups are less work intensive.
        """
        # Local import so that countries aren't loaded into memory until first
        # used.
        from django_countries.data import COUNTRIES

        if not hasattr(self, '_countries'):
            self._countries = []
            overrides = settings.COUNTRIES_OVERRIDE
            for code, name in COUNTRIES.items():
                if code in overrides:
                    name = overrides['code']
                if name:
                    self.countries.append((code, name))
        return self._countries
Beispiel #35
0
class PhoneFactory(DjangoModelFactory):
    class Meta:
        model = 'hosting.Phone'

    profile = factory.SubFactory('tests.factories.ProfileFactory')

    @factory.lazy_attribute
    def number(self):
        # the Faker's phone-number provider is a mess.
        phone = PhoneNumber()
        while not phone.is_valid():
            phone = PhoneNumber(country_code=randint(1, 999),
                                national_number=randint(10000, 99999999990))
        return phone

    country = Faker('random_element', elements=COUNTRIES.keys())
    comments = Faker('text', max_nb_chars=20)
    type = Faker('random_element',
                 elements=[ch[0] for ch in PHONE_TYPE_CHOICES])
Beispiel #36
0
 def __init__(self,
              attrs=None,
              country_attrs=None,
              country_radio_attrs=None,
              area_radio_attrs=None,
              area_attrs=None):
     widgets = (
         forms.CheckboxInput(attrs=attrs if country_radio_attrs is None else
                             country_radio_attrs),
         CountrySelectWidget(
             choices=((k, v) for k, v in COUNTRIES.items()),
             attrs=attrs if country_attrs is None else country_attrs),
         forms.CheckboxInput(
             attrs=attrs if area_radio_attrs is None else area_radio_attrs),
         forms.Select(attrs=attrs if area_attrs is None else area_attrs,
                      choices=[('', _('Area or continent'))] +
                      [(x.id, x.title_he)
                       for x in OriginArea.objects.all()]))
     super().__init__(widgets)
Beispiel #37
0
def update_mozillian_profiles(queryset=None):
    """Sync MozillianProfile objects with mozillians.org"""

    if not queryset:
        queryset = MozillianProfile.objects.all()

    for mozillian in queryset:
        data = get_mozillian_by_email(mozillian.email)

        if not data:
            # Try to fetch by username
            data = get_mozillian_by_username(mozillian.mozillian_username)

            if not data:
                continue

        if 'country' in data:
            mozillian.country = COUNTRIES.get(data['country'].upper(), '').capitalize()
        if 'full_name' in data:
            mozillian.full_name = data['full_name']
        else:
            mozillian.full_name = 'Private Mozillian'
        mozillian.email = data['email']
        if 'city' in data:
            mozillian.city = data['city']
        if 'ircname' in data:
            mozillian.ircname = data['ircname']
        if 'photo' in data:
            mozillian.avatar_url = data['photo']
        if 'bio' in data:
            mozillian.bio = data['bio']
        mozillian.save()

        mozillian.tracking_groups.clear()
        groups = []
        if 'groups' in data:
            for group in data['groups']:
                obj, created = MozillianGroup.objects.get_or_create(name=group)
                groups.append(obj)

        mozillian.tracking_groups = groups
        logger.debug('Mozillian succesfully updated.')
class PerfectFitProspectusForm(forms.Form):
    name = forms.CharField(
        required=True,
        label=_('Name'),
    )
    company = forms.CharField(
        required=True,
        label=_('Company'),
    )

    email = forms.EmailField(
        required=True,
        label=_('Email'),
    )

    phone_number = forms.CharField(required=False,
                                   label=_('Phone number (optional)'),
                                   widget=TextInput(attrs={'type': 'tel'}))

    country = forms.ChoiceField(required=True,
                                label=_('Country'),
                                choices=sorted([(k, v)
                                                for k, v in COUNTRIES.items()],
                                               key=lambda tup: tup[1]))

    gdpr_optin = forms.BooleanField(
        label=_('I would like to receive further information.'),
        initial=False,
        required=False)

    captcha = ReCaptchaField(
        label='',
        label_suffix='',
    )

    def __init__(self, sector_choices, country_choices, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['sector'] = forms.ChoiceField(label='Sector',
                                                  choices=sector_choices)
        self.fields['country'] = forms.ChoiceField(label='Country',
                                                   choices=country_choices)
Beispiel #39
0
    def __init__(self, account, domain, creating_user, data=None, *args, **kwargs):
        super(ConfirmExtraUserChargesForm, self).__init__(account, domain, creating_user, data=data, *args, **kwargs)

        from corehq.apps.users.views.mobile import MobileWorkerListView
        self.helper.label_class = 'col-sm-3 col-md-2'
        self.helper.field_class = 'col-sm-9 col-md-8 col-lg-6'
        self.helper.layout = crispy.Layout(
            crispy.Fieldset(
                _("Basic Information"),
                'company_name',
                'first_name',
                'last_name',
                crispy.Field('email_list', css_class='input-xxlarge accounting-email-select2',
                             data_initial=json.dumps(self.initial.get('email_list'))),
                'phone_number',
            ),
            crispy.Fieldset(
                 _("Mailing Address"),
                'first_line',
                'second_line',
                'city',
                'state_province_region',
                'postal_code',
                crispy.Field('country', css_class="input-large accounting-country-select2",
                             data_country_code=self.current_country or '',
                             data_country_name=COUNTRIES.get(self.current_country, '')),
            ),
            hqcrispy.FormActions(
                crispy.HTML(
                    '<a href="%(user_list_url)s" class="btn btn-default">%(text)s</a>' % {
                        'user_list_url': reverse(MobileWorkerListView.urlname, args=[self.domain]),
                        'text': _("Back to Mobile Workers List")
                    }
                ),
                StrictButton(
                    _("Confirm Billing Information"),
                    type="submit",
                    css_class='btn btn-primary disabled',
                ),
            ),
        )
Beispiel #40
0
    def __init__(self, *args, **kwargs):
        super(PublicSMSRateCalculatorForm, self).__init__(*args, **kwargs)

        isd_codes = []
        countries = sorted(COUNTRIES.items(), key=lambda x: x[1].encode('utf-8'))
        for country_shortcode, country_name in countries:
            country_isd_code = country_code_for_region(country_shortcode)
            isd_codes.append((country_isd_code, country_name))

        self.fields['country_code'].choices = isd_codes

        self.helper = FormHelper()
        self.helper.form_class = "form-horizontal"
        self.helper.layout = crispy.Layout(
            crispy.Field(
                'country_code',
                css_class="input-xxlarge",
                data_bind="value: country_code",
                placeholder=_("Please Select a Country Code"),
            ),
        )
Beispiel #41
0
 def get_gir_dict_for_domain_and_monthspan(domain, monthspan):
     user_tuple = GIRTableGenerator.classify_users(domain, monthspan)
     max_device = GIRTableGenerator.get_max_device(domain, monthspan)
     possible_experience = get_possibly_experienced(domain, monthspan)
     recently_active = GIRTableGenerator.get_active_recent(domain, monthspan)
     gir_dict = {
         'month': monthspan.startdate,
         'domain_name': domain.name,
         'country':
             ', '.join([unicode(COUNTRIES.get(abbr, abbr)) for abbr in domain.deployment.countries]),
         'sector': domain.internal.area,
         'subsector': domain.internal.sub_area,
         'bu': GIRTableGenerator.get_bu(domain),
         'self_service': domain.internal.self_started,
         'test_domain': TEST_COUCH_TO_SQL_MAP.get(domain.is_test, NOT_SET),
         'start_date': domain.date_created,
         'device_id': max_device,
         'wam': AMPLIFY_COUCH_TO_SQL_MAP.get(domain.internal.amplifies_workers, NOT_SET),
         'pam': AMPLIFY_COUCH_TO_SQL_MAP.get(domain.internal.amplifies_project, NOT_SET),
         'wams_current': len(user_tuple.performing & user_tuple.experienced),
         'active_users': len(user_tuple.active | user_tuple.sms),
         'using_and_performing': len(user_tuple.performing),
         'not_performing': len(user_tuple.active - user_tuple.performing),
         'inactive_experienced':
             len((user_tuple.total - user_tuple.active) & user_tuple.experienced),
         'inactive_not_experienced':
             len((user_tuple.total - user_tuple.active) - user_tuple.experienced),
         'not_experienced': len(user_tuple.performing - user_tuple.experienced),
         'not_performing_not_experienced':
             len(user_tuple.active - user_tuple.performing - user_tuple.experienced),
         'active_ever': len(possible_experience | recently_active),
         'possibly_exp': len(possible_experience),
         'ever_exp': len(user_tuple.experienced),
         'exp_and_active_ever': len(user_tuple.active & user_tuple.experienced),
         'active_in_span': len(recently_active),
         'eligible_forms': user_tuple.eligible,
         'experienced_threshold': domain.internal.experienced_threshold or DEFAULT_EXPERIENCED_THRESHOLD,
         'performance_threshold': domain.internal.performance_threshold or DEFAULT_PERFORMANCE_THRESHOLD,
     }
     return gir_dict
    def handle(self, *args, **options):
        print "Migrating Domain countries"

        country_lookup = {v.lower(): k for k, v in COUNTRIES.iteritems()}
        #Special cases
        country_lookup["USA"] = country_lookup["united states"]
        country_lookup["California"] = country_lookup["united states"]
        country_lookup["Wales"] = country_lookup["united kingdom"]

        for domain in Domain.get_all():
            if domain.deployment._doc.get('countries', None):
                continue
            try:
                country = None
                if domain.deployment._doc.get('country', None):
                    country = domain.deployment._doc['country']
                elif domain._doc.get('country', None):
                    country = domain._doc['country']

                if country:
                    if ',' in country:
                        countries = country.split(',')
                    elif ' and ' in country:
                        countries = country.split(' and ')
                    else:
                        countries = [country]

                    abbr = []
                    for country in countries:
                        country = country.strip().lower()
                        if country in country_lookup.keys():
                            abbr.append(country_lookup[country])

                    domain.deployment.countries = abbr
                    domain.save()
            except Exception as e:
                print "There was an error migrating the domain named %s." % domain.name
                print "Error: %s" % e
    def forwards(self, orm):
        reverse_map = dict((v.upper(), k) for k, v in COUNTRIES.items())
        # add a few special cases to the list that we know might exist
        reverse_map['GREAT BRITAIN'] = 'GB'
        reverse_map['KOREA'] = 'KR'
        reverse_map['MACEDONIA'] = 'MK'
        reverse_map['RUSSIA'] = 'RU'
        reverse_map['SOUTH KOREA'] = 'KR'
        reverse_map['TAIWAN'] = 'TW'
        reverse_map['VIETNAM'] = 'VN'

        for country_name in orm.Mirror.objects.values_list(
                'country_old', flat=True).order_by().distinct():
            code = reverse_map.get(country_name.upper(), '')
            orm.Mirror.objects.filter(
                    country_old=country_name).update(country=code)

        for country_name in orm.MirrorUrl.objects.filter(
				country_old__isnull=False).values_list(
                'country_old', flat=True).order_by().distinct():
            code = reverse_map.get(country_name.upper(), '')
            orm.MirrorUrl.objects.filter(
                    country_old=country_name).update(country=code)
 def country_response(self):
     from django_countries.data import COUNTRIES
     countries = sorted(COUNTRIES.items(), key=lambda x: x[1].encode('utf-8'))
     if self.search_string:
         return filter(lambda x: x[1].lower().startswith(self.search_string.lower()), countries)
     return countries
def _get_country(domain):
    project = Domain.get_by_name(domain)
    if project and project.deployment.countries:
        return unicode(COUNTRIES.get(project.deployment.countries[0], ''))
Beispiel #46
0
from .image_generator import generate_image

DEFAULT_IDENTIFIER = "default"
DEFAULT_NAME = "Default"

DEFAULT_ADDRESS_DATA = dict(
    prefix="Sir",
    name=u"Dog Hello",
    suffix=", Esq.",
    postal_code="K9N",
    street="Woof Ave.",
    city="Dog Fort",
    country="GB"
)

COUNTRY_CODES = sorted(COUNTRIES.keys())


class FuzzyBoolean(fuzzy.BaseFuzzyAttribute):
    def __init__(self, probability, **kwargs):
        self.probability = probability
        super(FuzzyBoolean, self).__init__()

    def fuzz(self):
        return (random.random() < self.probability)


class UserFactory(DjangoModelFactory):
    class Meta:
        model = settings.AUTH_USER_MODEL
Beispiel #47
0
def country_name_from_isd_code_or_empty(isd_code):
    cc = COUNTRY_CODE_TO_REGION_CODE.get(isd_code)
    return force_unicode(COUNTRIES.get(cc[0])) if cc else ''
Beispiel #48
0

def construct_address_form(country_code, i18n_rules):
    class_name = 'AddressForm%s' % country_code
    base_class = CountryAwareAddressForm
    form_kwargs = {
        'Meta': type(str('Meta'), (base_class.Meta, object), {}),
        'formfield_callback': None}
    class_ = type(base_class)(str(class_name), (base_class, ), form_kwargs)
    update_base_fields(class_, i18n_rules)
    class_.i18n_country_code = country_code
    class_.i18n_fields_order = property(get_form_i18n_lines)
    return class_


for country in COUNTRIES.keys():
    try:
        country_rules = i18naddress.get_validation_rules(
            {'country_code': country})
    except ValueError:
        country_rules = i18naddress.get_validation_rules({})
        UNKNOWN_COUNTRIES.add(country)

COUNTRY_CHOICES = [(code, label) for code, label in COUNTRIES.items()
                   if code not in UNKNOWN_COUNTRIES]
# Sort choices list by country name
COUNTRY_CHOICES = sorted(COUNTRY_CHOICES, key=lambda choice: choice[1])

for country, label in COUNTRY_CHOICES:
    country_rules = i18naddress.get_validation_rules({'country_code': country})
    COUNTRY_FORMS[country] = construct_address_form(country, country_rules)