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)
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
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
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))
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()
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')
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
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' ]
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
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())
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()
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']
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())
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}'
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'}) }
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
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)
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)
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"), ), )
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))
def handle(self, **options): print("Migrating Domain countries") country_lookup = {v.lower(): k for k, v in COUNTRIES.items()} #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: 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)
class UserUpdateForm(forms.ModelForm): country = forms.ChoiceField(choices=sorted(COUNTRIES.items())) country.widget.attrs.update({'class': 'form-control'}) first_name = forms.CharField(widget=forms.TextInput( attrs={ 'class': 'form-control', 'placeholder': "Enter Your First Name Here" })) last_name = forms.CharField(widget=forms.TextInput( attrs={ 'class': 'form-control', 'placeholder': "Enter Your Last Name Here" })) username = forms.CharField(widget=forms.TextInput( attrs={ 'class': 'form-control', 'placeholder': "Enter Your Username Here", 'type': 'email' })) phone = PhoneNumberField( widget=PhoneNumberPrefixWidget(initial='AD', attrs={ 'class': 'form-control', 'placeholder': "Phone Number", 'type': 'number' })) class Meta: model = User fields = ['country', 'first_name', 'last_name', "username", "phone"] exclude = [ 'is_client', 'is_modrator', 'is_photographer', 'is_admin', 'password2', 'password1' ]
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)
class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = [ 'avatar', 'first_name', 'last_name', 'email', 'bio', 'is_contributor', 'is_author', 'field', 'country', ] field_choices = [('Engineering', 'Engineering'), ('Medicine', 'Medicine'), ('Psychology', 'Psychology'), ('Art and Culture', 'Art and Culture')] avatar = forms.ImageField(label='avatar', required=False, widget=forms.FileInput(attrs={'class': ''})) first_name = forms.CharField( label='first_name', widget=forms.TextInput(attrs={ 'placeholder': 'First Name', 'class': 'form-control' })) last_name = forms.CharField( label='last_name', required=False, widget=forms.TextInput(attrs={ 'placeholder': 'Last Name', 'class': 'form-control' })) email = forms.EmailField(label='email', widget=forms.EmailInput(attrs={ 'placeholder': 'email', 'class': 'form-control' })) bio = forms.CharField(label='about', widget=forms.TextInput(attrs={ 'placeholder': 'About', 'class': 'form-control' })) field = forms.CharField(label="Select your specialized field", widget=forms.Select(choices=field_choices, attrs={ 'placeholder': 'field', 'class': 'form-control' })) country = forms.CharField(label="country", widget=forms.Select(choices=sorted( COUNTRIES.items()), attrs={ 'placeholder': 'field', 'class': 'form-control' })) is_author = forms.BooleanField(label='is_author', required=False, widget=forms.CheckboxInput()) is_contributor = forms.BooleanField(label='is_contributor', required=False, widget=forms.CheckboxInput())
from django.utils.translation import ugettext_lazy as _ from django_countries.data import COUNTRIES STATUSES_OPTIONS = { 'employed': [ _("A person working in the government administration"), _("A person working in local government administration"), _("other"), _("A person works in MSME"), _("A person working in a non-governmental administration"), _("A self-employed person"), _("A person working in a large enterprise") ], 'registered': [_("Long-term unemployed person"), _("other")], 'unregistered': [_("Long-term unemployed person"), _("other")], 'looking': [ _("Learning"), _("A person not participating in education or training"), _("other") ] } COUNTRIES_ENROLL = [ ('', _('Select...')), ] + list(COUNTRIES.items()) COUNTRIES_ENROLL.append(('ZZ', _('Unknown or unspecified country')))
from .forms import * import requests from .user_notifications import * from django.contrib import messages from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger #QR import qrcode import qrcode.image.svg from io import BytesIO #from twilio.rest import Client # Create your views here. countries = sorted(COUNTRIES.items()) # Home page handeling ( Authenticated or non both) @login_required def home(request): list(messages.get_messages(request)) try: personal = Personal_Info.objects.get(user=request.user) try: document = Documents.objects.get(user=request.user) try: skills = Skills.objects.get(user=request.user) return redirect('main:profile', request.user.id)
class OldRegistrationForm(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") captcha = CaptchaField() class Meta: model = UserCred fields = [ 'username', 'password1', 'password2', 'nickname', 'first_name', 'last_name', 'job_title', 'organization', 'annotator_exp', 'country', 'captcha' ] def clean(self): """ Verifies that the values entered into the password fields match NOTE: Errors here will appear in ``non_field_errors()`` because it applies to more than one field. """ cleaned_data = super(OldRegistrationForm, self).clean() if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data: if self.cleaned_data['password1'] != self.cleaned_data['password2']: raise forms.ValidationError( "Passwords don't match. Please enter both fields again.") return self.cleaned_data def save(self, commit=True): print type(self) user = super(OldRegistrationForm, self).save(commit=False) user.set_password(self.cleaned_data['password1']) if commit: ap = AnnotatorProfile( nickname=self.cleaned_data["nickname"], first_name=self.cleaned_data["first_name"], last_name=self.cleaned_data["last_name"], email=self.cleaned_data["username"], 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
def countries(self): return [value for (key, value) in sorted(COUNTRIES.items())]
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
class UserForm(UserCreationForm): country = forms.ChoiceField(choices=sorted(COUNTRIES.items())) country.widget.attrs.update({'class': 'form-control'}) first_name = forms.CharField(widget=forms.TextInput( attrs={ 'class': 'form-control', 'placeholder': "Enter Your First Name Here" })) last_name = forms.CharField(widget=forms.TextInput( attrs={ 'class': 'form-control', 'placeholder': "Enter Your Last Name Here" })) username = forms.CharField(widget=forms.TextInput( attrs={ 'class': 'form-control', 'placeholder': "Enter Your Email Here", 'type': 'email' }), label='Email') phone = PhoneNumberField( widget=PhoneNumberPrefixWidget(initial='NP', attrs={ 'class': 'form-control', 'placeholder': "Phone Number", 'type': 'number' })) password1 = forms.CharField( widget=forms.PasswordInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter password' }), label='Password', required=True, max_length=50) password2 = forms.CharField( widget=forms.PasswordInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter password' }), label='Confirm Password', required=True, max_length=50) class Meta: model = User fields = [ 'country', 'first_name', 'last_name', "username", "phone", "password1", "password2", ] exclude = ['membership']
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)
class IP(DatetimeModel, CoordinatesModel): """ Adresse IP """ # Constantes HARMFUL_LEVEL = 2 PROTECTED_IPS = [r'^127\.', r'^192\.168\.'] + list( getattr(settings, 'INTERNAL_IPS', [])) # Champs ip = models.DecimalField(null=False, blank=True, max_digits=39, decimal_places=0, primary_key=True, verbose_name=_("Decimal")) string = models.CharField(max_length=45, verbose_name=_("String")) reverse = models.CharField( max_length=80, blank=True, verbose_name=_("Reverse")) # état de résolution du reverse status = models.SmallIntegerField(default=0, choices=STATUS_CHOICES, verbose_name=_("Reverse status")) isp = models.CharField(max_length=64, blank=True, verbose_name=_("ISP")) country = models.CharField(max_length=2, blank=True, choices=COUNTRIES.items(), db_index=False, verbose_name=_("Country")) harm = models.SmallIntegerField( default=0, db_index=True, validators=[MinValueValidator(0), MaxValueValidator(4)], verbose_name=_("Harm")) blocked = models.BooleanField(default=False, db_index=False, verbose_name=_("Blocked")) updated = models.DateTimeField(default=datetime(1970, 1, 1, tzinfo=pytz.utc), verbose_name=pgettext_lazy('ip', "Updated")) dynamic = models.NullBooleanField( default=None, verbose_name=_("Dynamic")) # IP dynamique ? city_name = models.CharField(max_length=96, blank=True, verbose_name=_("City name")) objects = IPManager() # Getter def natural_key(self): """ Renvoyer une IP par sa clé naturelle """ return 'ip', def get_ip_address(self): """ Renvoyer la chaîne d'adresse de l'IP """ return self.string or IPy.IP(int(self.ip)).strNormal() @addattr(short_description=_("Class")) def get_ip_class(self): """ Renvoyer la classe de l'IP, de A à E """ value = int(self.ip) if value & (0b1 << 31) == 0: # 0.0.0.0 à 127.255.255.255 return "A" elif value & (0b10 << 30) == ( 0b10 << 30): # 128.0.0.0 à 191.255.255.255 return "B" elif value & (0b110 << 29) == ( 0b110 << 29): # 192.0.0.0 à 223.255.255.255 return "C" elif value & (0b1110 << 28) == ( 0b1110 << 28): # 224.0.0.0 à 239.255.255.255 return "D" elif value & (0b1111 << 28) == ( 0b1111 << 28): # 240.0.0.0 à 255.255.255.255 return "E" def get_geoip(self): """ Renvoyer les informations de localisation de l'IP """ try: return IP.objects.geoip.record_by_addr(self.string) or {} except Exception as e: logger.warning(e) return {'country_code': '', 'latitude': 0.0, 'longitude': 0.0} @addattr(short_description=_("Country")) def get_country_code(self): """ Renvoyer le code pays de l'IP """ code = self.get_geoip().get('country_code', "").upper() return code @addattr(short_description=_("Country")) def get_country(self): """ Renvoyer l'instance Country pour l'IP """ if not apps.is_installed('scoop.location'): return None from scoop.location.models import Country # Renvoyer le pays correspondant au code, ou aucun si A1, A2 etc. return Country.objects.get_by_code2_or_none(self.country) @addattr(short_description=_("Country")) def get_country_name(self): """ Renvoyer le nom du pays de l'IP """ return self.get_country_display() def get_closest_city(self): """ Renvoyer l'instance de City la plus proche des coordonnées GPS de l'adresse IP '""" if not apps.is_installed('scoop.location'): return None try: from scoop.location.models import City if self.string in settings.INTERNAL_IPS: return IP.objects.get_by_ip( settings.PUBLIC_IP).get_closest_city() # Trouver la ville la plus proche des coordonnées GPS de l'IP, portant idéalement un nom geoip = self.get_geoip() or dict() if geoip.get('latitude', 0) != 0: point, name = [geoip['latitude'], geoip['longitude']], geoip['city'] return City.objects.find_by_name(point, name=name) return None except Exception: return None @addattr(short_description=_("ISP")) def get_isp(self): """ Renvoyer les informations du FAI de l'IP """ org = IP.objects.geoisp.org_by_addr(self.ip_address) or "" return org @addattr(short_description=_("City name")) def get_city_name(self): """ Renvoyer le nom de la ville de l'IP """ return self.city_name or _("N/D") @addattr(short_description=_("Reverse")) def get_reverse(self, force_lookup=False): """ Renvoyer le nom inversé de l'IP """ if force_lookup is True: return reverse_lookup(self.get_ip_address()) return self.reverse or reverse_lookup(self.get_ip_address()) @addattr(short_description=_("Short reverse")) def get_short_reverse(self): """ Renvoyer un nom inversé court pour l'IP """ reverse = self.reverse shorter = re.sub('\d', '', reverse) shorter = re.sub('\W{2,8}', '-', shorter) shorter = re.sub('(\W$|^\W)', '', shorter) return shorter @staticmethod def get_ip_value(ip_string): """ Renvoyer la valeur décimale d'une IP :param ip_string: chaîne de l'IP, de type A.B.C.D ou 128bits) """ try: return IPy.IP(ip_string).ip except ValueError: return 0 @addattr(admin_order_field='ip', short_description=_("Hexadecimal")) def get_hex(self, group=2): """ Renvoyer la représentation hexadécimale de l'IP """ if group is not int(group) or not group > 0: group = 1 result = "{:X}".format(int(self.ip)) output = "".join([ digit + ':' if idx % group == group - 1 and idx < len(result) - 1 else digit for idx, digit in enumerate(result) ]) return output @addattr(short_description=_("Users")) def get_users(self): """ Renvoyer les utilisateurs ayant navigué avec cette IP """ users = get_user_model().objects.filter( userips__ip=self).order_by('-pk') return users @addattr(short_description=_("Number of users")) def get_user_count(self): """ Renvoyer le nombre d'utilisateurs ayant navigué avec cette IP """ return self.get_users().count() def get_subnet_range(self, bits=24): """ Renvoyer la plage d'IP (long) du sous réseau de l'IP :param bits: taille du masque, en bits """ keep = 32 - bits mask_subnet = (1 << keep) - 1 mask_network = ~mask_subnet network = int(self.ip) & mask_network network_end = network | mask_subnet return [network, network_end] def get_subnet_ips(self, bits=24): """ Renvoyer les IP du sous-réseau de l'IP, avec un masque de n bits """ iprange = self.get_subnet_range(bits) # Renvoyer les résultats entre network et network_end ips = IP.objects.filter(ip__range=(iprange[0], iprange[1])) return ips def get_subnet_users(self, bits=24): """ Renvoyer les utilisateurs ayant une IP du sous-réseau """ iprange = self.get_subnet_range(bits) users = get_user_model().objects.filter( userip__ip__ip__range=(iprange[0], iprange[1])).distinct() return users def has_reverse(self): """ Renvoyer si l'IP possède un nom inversé """ if ('in-addr.arpa' in self.reverse) or '.' not in self.reverse: return False return True def has_isp(self): """ Renvoyer si l'IP possède un FAI """ return self.isp.strip() != "" def has_country(self): """ Renvoyer si l'IP possède un pays """ return self.country.strip() != "" def get_blocked_status(self, check=False): """ Renvoyer les informations de blocage de l'IP :param check: Recalculer l'état de blocage de l'IP """ if check is True: from scoop.rogue.models import IPBlock # Vérifier complètement si l'IP est dangereuse et bloquée return IPBlock.objects.get_ip_status(self) return {'blocked': self.blocked, 'level': self.harm, 'type': 0} def is_blocked(self, check=False): """ Renvoyer si l'IP est bloquée :param check: Recalculer l'état de blocage de l'IP """ result = self.get_blocked_status(check) return result['blocked'] def is_harmful(self): """ Renvoyer si l'adresse IP est dangereuse """ return self.harm >= IP.HARMFUL_LEVEL def is_protected(self): """ Renvoyer si l'IP est spéciale et protégée """ for regex in self.PROTECTED_IPS: if re.search(regex, self.string): return True return False @staticmethod def is_country_harmful(code): """ Renvoyer si un code pays est dangereux """ if not code or code.lower() in getattr( settings, 'LOCATION_SAFE_COUNTRIES', code.lower()): return False return True @addattr(allow_tags=True, short_description=_("Icon")) def get_country_icon(self): """ Renvoyer le HTML du drapeau du pays de l'IP """ if self.has_country(): return get_country_icon_html(self.country, self.get_country_name()) @staticmethod def get_ip_information(ip): """ Renvoyer un dictionnaire d'informations sur l'adresse IP (A.B.C.D) passée """ geoip_info, data = dict(), {'ip': IP.get_ip_value(ip), 'string': ip} reverse = reverse_lookup(ip) data['reverse'] = str(reverse['name']) if isinstance(reverse, dict) else reverse data['status'] = reverse['status'] if isinstance(reverse, dict) else '' data['isp'] = IP.objects.get_isp_by_ip(ip)[0:64] data['updated'] = timezone.now() try: geoip_info = IP.objects.geoip.record_by_addr(ip) or dict() except Exception: pass data['country'] = geoip_info.get('country_code', "").upper() data['harm'] = 3 * IP.is_country_harmful( data['country']) # 3 si True, 0 sinon data['latitude'] = geoip_info.get('latitude', 0.0) or 0.0 data['longitude'] = geoip_info.get('longitude', 0.0) or 0.0 data['city_name'] = geoip_info.get('city', "") or "" return data # Setter def set_ip_information(self, data, save=True): """ Mettre à jour l'IP avec un dictionnaire d'informations """ self.update(save=save, **data) def set_ip_address(self, ip_string, save=False): """ Définir l'adresse IP de l'objet :param ip_string: chaîne du type A.B.C.D :param force_lookup: forcer le lookup DNS même si l'instance IP possède déjà des informations :param save: Enregistrer l'IP directement après """ data = IP.get_ip_information(ip_string) self.set_ip_information(data, save=save) return self def block(self, blocked=True, harm=3, save=False): """ Bloquer l'IP """ self.harm = harm self.blocked = blocked if save is True: self.save() def check_blocked(self, force=False): """ Vérifier et renvoyer si l'IP est potentiellement dangereuse """ from scoop.rogue.models import IPBlock from scoop.rogue.util.signals import ip_blocked # Vérifier via IPBlock si l'IP doit être bloquée if not self.blocked or force: status = IPBlock.objects.get_ip_status(self) if status['blocked'] is True: self.block(status['blocked'], status['level'], save=False) ip_blocked.send(sender=self, harm=status['level']) return True return False # Propriétés ip_address = property(get_ip_address, set_ip_address) geoip = property(get_geoip) # Overrides def __str__(self): """ Renvoyer la représentation unicode de l'objet """ return "{}".format(self.ip_address) def __repr__(self): """ Renvoyer la représentation ASCII de l'objet """ return "@{}".format(self.ip_address) def get_absolute_url(self): """ Renvoyer l'URL de la page de l'objet """ return reverse_lazy('access:ip-view', args=[self.id]) def save(self, *args, **kwargs): """ Enregistrer l'objet dans la base de données """ super(IP, self).save(*args, **kwargs) # Métadonnées class Meta: verbose_name = "IP" verbose_name_plural = "IP" app_label = 'access'