Exemplo n.º 1
0
class RegistrationForm(BaseModel):
    user = models.OneToOneField(User, models.CASCADE)
    address = models.CharField(max_length=300)
    address_2 = models.CharField(max_length=300, blank=True)
    city = models.CharField(max_length=100)
    state = us_model.USStateField()
    zip_code = us_model.USZipCodeField()
    phone_1 = PhoneNumberField()
    phone_2 = PhoneNumberField(blank=True)
    date_of_birth = models.DateField()
    gender = models.CharField(max_length=1, choices=GENDER_CHOICES)
    pronouns = models.CharField(max_length=30, blank=True)
    emergency_contact_name = models.CharField(max_length=200)
    emergency_contact_relationship_to_you = models.CharField(max_length=200)
    emergency_contact_phone_number = PhoneNumberField()
    physical_fitness = models.TextField()
    medical_condition_description = models.TextField(blank=True)
    allergy_condition_description = models.TextField(blank=True)
    medications_descriptions = models.TextField(blank=True)
    medical_insurance = models.BooleanField()
    name_of_policy_holder = models.CharField(max_length=200)
    relation_of_policy_holder = models.CharField(max_length=100)
    signature = models.CharField(max_length=3)
    todays_date = models.DateField()

    def __str__(self):
        return f"{self.user.first_name} {self.user.last_name} " f"registration form"
Exemplo n.º 2
0
class User(User):
    class Meta:
        app_label = 'toolshare'

    REMAINDER_FREQ_TYPE = (
        ('D', 'Every day'),
        ('W', 'Once a week'),
        ('M', 'Once a month'),
        ('N', 'Never')
    )
    address_line = models.CharField(max_length=100, null=False)
    city = models.CharField(max_length=20, null=False)
    state = us_models.USStateField(null=False)
    zipcode = models.IntegerField(max_length=5, null=False)
    phone = us_models.PhoneNumberField(null=True, blank=True)
    email_remainder_freq = models.CharField(max_length=1, choices=REMAINDER_FREQ_TYPE, default='D')
    pickup_location = models.CharField(max_length=100, null=False)
    share_zone = models.ForeignKey(ShareZone)

    def __str__(self):
        return '{first} {last}'.format(first=self.first_name,
                                       last=self.last_name)

    def _pending_requests(self):
        reservation = Reservation.objects.filter(lender_id=self.id, status__in=['RP','P'])
        return reservation.count()

    pending_requests = property(_pending_requests)
Exemplo n.º 3
0
class BarMembership(models.Model):
    barMembership = local_models.USStateField(
        "the two letter state abbreviation of a bar membership")

    def __unicode__(self):
        return self.get_barMembership_display()

    class Meta:
        verbose_name = "bar membership"
        ordering = ["barMembership"]
Exemplo n.º 4
0
class Shed(BaseModel):
    address = models.CharField(max_length=50, null=False, blank=False)
    zipcode = models.CharField(max_length=5, null=False)
    city = models.CharField(max_length=20, null=False)
    state = us_models.USStateField(null=False)
    coordinator = models.ForeignKey(User)

    def __str__(self):
        return '-'.join([self.address, self.city, self.state, self.zipcode])

    def to_string(self):
        return "%s %s, %s %s" % (self.address, self.city, self.state,
                                 self.zipcode)
Exemplo n.º 5
0
class Childcare(models.Model):
    name = models.CharField(max_length=100)
    slug = models.SlugField(verbose_name='URL: kindy.at/',
                            unique=True,
                            max_length=100)
    logo = models.ImageField(upload_to='images/logos/', blank=True)
    slogan = models.CharField(max_length=100, blank=True)
    description = models.TextField(blank=True)
    street_address = models.CharField(max_length=100)
    city = models.CharField(max_length=100)
    state = usmodels.USStateField(blank=True)
    country = countries.CountryField()
    manager = models.ForeignKey(User, related_name='childcare_manager')
    employees = models.ManyToManyField(User,
                                       related_name='childcare_employees',
                                       blank=True)
    theme = themes.ThemeField(default='default')
    theme_image = models.CharField(max_length=100,
                                   blank=True,
                                   default='default')
    email = models.CharField(max_length=100, blank=True)
    phone_number = models.CharField(max_length=100, blank=True)
    subscription = subscriptions.SubscriptionField(default='trial')
    subscription_expires = models.DateTimeField(default=one_month_trial())
    disabled = models.BooleanField(default=False)

    def __unicode__(self):
        return self.name

    class Meta:
        permissions = (
            ('childcare_view', 'View childcare dashboard'),
            ('childcare_update', 'Updating childcare settings'),
            ('classroom_view', 'View classroom dashboard'),
        )

    def save(self, *args, **kwargs):
        is_create = False
        if not self.id:
            is_create = True

        if not self.slug:
            self.slug = unique_slugify(self, self.name)

        super(Childcare, self).save(*args, **kwargs)

        if is_create:
            roles_childcare_init_new(self)

    def get_absolute_url(self):
        return '/childcare/%s' % self.id
Exemplo n.º 6
0
class Location(models.Model):
    city = models.CharField(max_length=100)
    # locality is for certain places (such as queens) where the google
    # locality and neighborhood are different
    locality = models.CharField(max_length=100, default="")
    state = us_models.USStateField()
    address = models.CharField(max_length=255)
    zipcode = us_models.USZipCodeField()
    latitude = models.DecimalField(
        max_digits=9, decimal_places=6, blank=True, null=True
    )
    longitude = models.DecimalField(
        max_digits=9, decimal_places=6, blank=True, null=True
    )
    last_fetched_zillow = models.DateTimeField(blank=True, null=True)

    @property
    def full_address(self):
        addr_components = map(str, [self.address, self.city, self.state, self.zipcode])
        return ", ".join(addr_components)

    @property
    def url_encoded_full_address(self):
        return quote(self.full_address)

    @property
    def google_map_url(self):
        return f"https://www.google.com/maps/search/?api=1&query={self.url_encoded_full_address}"

    def avg_rate(self):
        review_sum = 0
        for review in self.review_set.all():
            review_sum += review.rating
        if self.review_set.count() != 0:
            avg = review_sum / self.review_set.count()
            return float("%.2f" % round(avg, 2))
        else:
            return 0

    def check_tenant(self, user):
        return self.apartment_set.filter(tenant=user).exists()

    def check_landlord(self, user):
        return self.apartment_set.filter(landlord=user).exists()
Exemplo n.º 7
0
class Contact(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
    firstName = models.CharField(max_length=30, default='')
    lastName = models.CharField(max_length=30, default='')
    phone = usmodels.PhoneNumberField(default='')
    email = models.EmailField(default='')
    street = models.CharField(max_length=255, default='')
    city = models.CharField(max_length=90, default='Fairview')
    state = usmodels.USStateField(default='TX')
    zipCode = usmodels.USZipCodeField(default='75069')
    '''
    This model will then not be used to create any database table.
    Instead, when it is used as a base class for other models, its
    fields will be added to those of the child class.
    '''
    class Meta:
        abstract = True

    def __unicode__(self):
        return '%s, %s' % (self.lastName, self.firstName)
Exemplo n.º 8
0
class Person(models.Model):
    RELIGIONS = (
        ('ca', 'Catholic'),
        ('pr', 'Protestant'),
        ('je', 'Jewish'),
        ('mu', 'Muslim'),
        ('at', 'Atheist'),
        ('ag', 'Agnostic'),
        ('mo', 'Mormon'),
        ('bu', 'Buddhist'),
        ('hi', 'Hindu')
    )
    race = models.ManyToManyField(
        'Race',
        help_text="A person's race or races if they are multi-racial.",
        blank=True,
    )
    is_alias_of = models.ForeignKey(
        'self',
        help_text="Any nicknames or other aliases that a person has. For "
                  "example, William Jefferson Clinton has an alias to Bill",
        related_name="aliases",
        blank=True,
        null=True,
    )
    date_created = models.DateTimeField(
        help_text="The original creation date for the item",
        auto_now_add=True,
        db_index=True
    )
    date_modified = models.DateTimeField(
        help_text="The last moment when the item was modified.",
        auto_now=True,
        db_index=True,
    )
    fjc_id = models.IntegerField(
        help_text="The ID of a judge as assigned by the Federal Judicial "
                  "Center.",
        null=True,
        blank=True,
        unique=True,
        db_index=True,
    )
    cl_id = models.CharField(
        max_length=30,
        help_text="A unique identifier for judge, also indicating source of "
                  "data.",
        unique=True,
        db_index=True
    )
    slug = models.SlugField(
        help_text="A generated path for this item as used in CourtListener "
                  "URLs",
        max_length=158  # len(self.name_full)
    )
    name_first = models.CharField(
        help_text="The first name of this person.",
        max_length=50,
    )
    name_middle = models.CharField(
        help_text="The middle name or names of this person",
        max_length=50,
        blank=True,
    )
    name_last = models.CharField(
        help_text="The last name of this person",
        max_length=50,
        db_index=True,
    )
    name_suffix = models.CharField(
        help_text="Any suffixes that this person's name may have",
        choices=SUFFIXES,
        max_length=5,
        blank=True,
    )
    date_dob = models.DateField(
        help_text="The date of birth for the person",
        null=True,
        blank=True,
    )
    date_granularity_dob = models.CharField(
        choices=DATE_GRANULARITIES,
        max_length=15,
        blank=True,
    )
    date_dod = models.DateField(
        help_text="The date of death for the person",
        null=True,
        blank=True,
    )
    date_granularity_dod = models.CharField(
        choices=DATE_GRANULARITIES,
        max_length=15,
        blank=True,
    )
    dob_city = models.CharField(
        help_text="The city where the person was born.",
        max_length=50,
        blank=True,
    )
    dob_state = local_models.USStateField(
        help_text="The state where the person was born.",
        blank=True,
    )
    dod_city = models.CharField(
        help_text="The city where the person died.",
        max_length=50,
        blank=True,
    )
    dod_state = local_models.USStateField(
        help_text="The state where the person died.",
        blank=True,
    )
    gender = models.CharField(
        help_text="The person's gender",
        choices=GENDERS,
        max_length=2,
        blank=True,
    )
    religion = models.CharField(
        help_text="The religion of a person",
        max_length=30,
        blank=True
    )
    ftm_total_received = models.FloatField(
        help_text="The amount of money received by this person and logged by "
                  "Follow the Money.",
        blank=True,
        null=True,
        db_index=True,
    )
    ftm_eid = models.CharField(
        max_length=30,
        help_text="The ID of a judge as assigned by the Follow the Money "
                  "database.",
        null=True,
        blank=True,
    )
    has_photo = models.BooleanField(
        help_text="Whether there is a photo corresponding to this person in "
                  "the judge pics project.",
        default=False,
    )

    def __unicode__(self):
        return u'%s: %s' % (self.pk, self.name_full)

    class Meta:
        verbose_name_plural = "people"

    def get_absolute_url(self):
        return reverse('view_person', args=[self.pk, self.slug])

    def save(self, *args, **kwargs):
        self.slug = slugify(trunc(self.name_full, 158))
        self.full_clean()
        super(Person, self).save(*args, **kwargs)

    def clean_fields(self, *args, **kwargs):
        validate_partial_date(self, ['dob', 'dod'])
        validate_is_not_alias(self, ['is_alias_of'])
        validate_has_full_name(self)
        super(Person, self).clean_fields(*args, **kwargs)

    @property
    def name_full(self):
        return u' '.join([v for v in [
            self.name_first,
            self.name_middle,
            self.name_last,
            self.get_name_suffix_display(),
        ] if v]).strip()

    @property
    def name_full_reverse(self):
        return u'{name_last}, {name_first} {name_middle}, {suffix}'.format(
            suffix=self.get_name_suffix_display(),
            **self.__dict__
        ).strip(', ')

    @property
    def is_alias(self):
        return True if self.is_alias_of is not None else False

    @property
    def is_judge(self):
        """Examine the positions a person has had and identify if they were ever
        a judge.
        """
        for position in self.positions.all():
            if position.is_judicial_position:
                return True
        return False

    def as_search_dict(self):
        """Create a dict that can be ingested by Solr"""
        out = {
            'id': self.pk,
            'fjc_id': self.fjc_id,
            'cl_id': self.cl_id,
            'alias_ids': [alias.pk for alias in self.aliases.all()],
            'races': [r.get_race_display() for r in self.race.all()],
            'gender': self.get_gender_display(),
            'religion': self.religion,
            'name': self.name_full,
            'name_reverse': self.name_full_reverse,
            'date_granularity_dob': self.date_granularity_dob,
            'date_granularity_dod': self.date_granularity_dod,
            'dob_city': self.dob_city,
            'dob_state': self.get_dob_state_display(),
            'dob_state_id': self.dob_state,
            'absolute_url': self.get_absolute_url(),
            'school': [e.school.name for e in self.educations.all()],
            'political_affiliation': [
                pa.get_political_party_display() for pa in
                self.political_affiliations.all() if pa
            ],
            'political_affiliation_id': [
                pa.political_party for pa in
                self.political_affiliations.all() if pa
            ],
            'aba_rating': [
                r.get_rating_display() for r in
                self.aba_ratings.all() if r
            ],
        }

        # Dates
        if self.date_dob is not None:
            out['dob'] = datetime.combine(self.date_dob, time())
        if self.date_dod is not None:
            out['dod'] = datetime.combine(self.date_dod, time())

        # Joined Values. Brace yourself.
        positions = self.positions.all()
        if positions.count() > 0:
            p_out = {
                'court': [p.court.short_name for p in positions if p.court],
                'court_exact': [p.court.pk for p in positions if p.court],
                'position_type': [p.get_position_type_display() for p in
                                  positions],
                'appointer': [p.appointer.person.name_full_reverse for p in
                              positions if p.appointer],
                'supervisor': [p.supervisor.name_full_reverse for p in
                               positions if p.supervisor],
                'predecessor': [p.predecessor.name_full_reverse for p in
                                positions if p.predecessor],
                'date_nominated': solr_list(positions, 'date_nominated'),
                'date_elected': solr_list(positions, 'date_elected'),
                'date_recess_appointment': solr_list(
                    positions, 'date_recess_appointment',
                ),
                'date_referred_to_judicial_committee': solr_list(
                    positions, 'date_referred_to_judicial_committee',
                ),
                'date_judicial_committee_action': solr_list(
                    positions, 'date_judicial_committee_action',
                ),
                'date_hearing': solr_list(positions, 'date_hearing'),
                'date_confirmation': solr_list(positions, 'date_confirmation'),
                'date_start': solr_list(positions, 'date_start'),
                'date_granularity_start': solr_list(
                    positions, 'date_granularity_start',
                ),
                'date_retirement': solr_list(
                    positions, 'date_retirement',
                ),
                'date_termination': solr_list(
                    positions, 'date_termination',
                ),
                'date_granularity_termination': solr_list(
                    positions, 'date_granularity_termination',
                ),
                'judicial_committee_action': [
                    p.get_judicial_committee_action_display() for p in
                    positions if p.judicial_committee_action
                ],
                'nomination_process': [
                    p.get_nomination_process_display() for p in
                    positions if p.nomination_process
                ],
                'selection_method': [
                    p.get_how_selected_display() for p in
                    positions if p.how_selected
                ],
                'selection_method_id': [
                    p.how_selected for p in
                    positions if p.how_selected
                ],
                'termination_reason': [
                    p.get_termination_reason_display() for p in
                    positions if p.termination_reason
                ],
            }
            out.update(p_out)

        text_template = loader.get_template('indexes/person_text.txt')
        out['text'] = text_template.render({'item': self}).translate(null_map)

        return normalize_search_dicts(out)
Exemplo n.º 9
0
class Event(models.Model):
    """
    EVENT CLASS - abstraction for a unique spatial-temporal occurrence that
    necessitates the services of one or more interpreters
    """
    #Keyed fields
    company_tag = models.CharField(max_length=16,
                                   verbose_name='Creator\'s Company Tag')
    creator_tag = models.CharField(max_length=16,
                                   verbose_name='Creator\'s Tag')
    languages = models.CharField(max_length=64,
                                 blank=True,
                                 verbose_name='Languages')
    #Natural fields
    title = models.CharField(max_length=128, blank=True, verbose_name='Title')
    date_created = models.DateTimeField(
        default=datetime.now().replace(tzinfo=utc),
        verbose_name='Date Created')
    date_time_start = models.DateTimeField(null=True,
                                           verbose_name='Date and Time Start')
    date_time_end = models.DateTimeField(null=True,
                                         verbose_name='Date and Time End')
    timezone = models.CharField(max_length=64, default='America/Chicago')
    date = models.DateField(verbose_name='Date')
    sessionStart = models.TimeField(verbose_name='Session Start')
    sessionEnd = models.TimeField(verbose_name='Session End')
    addressLineOne = models.CharField(max_length=128,
                                      verbose_name='Address Line 1')
    addressLineTwo = models.CharField(max_length=128,
                                      verbose_name='Address Line 2',
                                      blank=True)
    addressLineThree = models.CharField(max_length=128,
                                        verbose_name='Address Line 3',
                                        blank=True)
    city = models.CharField(max_length=32, verbose_name='City')
    state = us_models.USStateField(verbose_name='State')
    zipCode = models.CharField(
        max_length=10,
        verbose_name='Zip Code',
        validators=[RegexValidator(r'^\d{5}(-\d{4})?$')])

    class Meta:
        verbose_name = "Event"
        verbose_name_plural = "Events"

    def save(self, *args, **kwargs):
        """
        Save override. Been in place a while. Normalizes date field
        """
        self.sessionStart = _clean_time(self.sessionStart)
        self.sessionEnd = _clean_time(self.sessionEnd)
        self.date = _clean_date(self.date)

        # temporary solution to duplicative date fields until they can be paired off

        self.date_time_start = datetime(self.date.year, self.date.month,
                                        self.date.day, self.sessionStart.hour,
                                        self.sessionStart.minute,
                                        self.sessionEnd.second)

        self.date_time_end = datetime(self.date.year, self.date.month,
                                      self.date.day, self.sessionEnd.hour,
                                      self.sessionEnd.minute,
                                      self.sessionEnd.second)

        zone = timezone(self.timezone)

        self.date_time_end = zone.localize(self.date_time_end)
        self.date_time_start = zone.localize(self.date_time_start)

        self.date_time_end = pack_time_utc(self.date_time_end)
        self.date_time_start = pack_time_utc(self.date_time_start)

        super(Event, self).save(*args, **kwargs)
Exemplo n.º 10
0
class Position(models.Model):
    """A role held by a person, and the details about it."""
    POSITION_TYPES = (
        ('Judge', (
            # Acting
            ('act-jud',      'Acting Judge'),
            ('act-pres-jud', 'Acting Presiding Judge'),

            # Associate
            ('ass-jud',      'Associate Judge'),
            ('ass-c-jud',    'Associate Chief Judge'),
            ('ass-pres-jud', 'Associate Presiding Judge'),
            ('jud',          'Judge'),
            ('jus',          'Justice'),

            # Chief
            ('c-jud',     'Chief Judge'),
            ('c-jus',     'Chief Justice'),
            ('c-mag',     'Chief Magistrate'),
            ('c-spec-m',  'Chief Special Master'),
            ('pres-jud',  'Presiding Judge'),
            ('pres-jus',  'Presiding Justice'),
            ('pres-mag',  'Presiding Magistrate'),
            # Commissioner
            ('com',     'Commissioner'),
            ('com-dep', 'Deputy Commissioner'),

            # Pro Tem
            ('jud-pt', 'Judge Pro Tem'),
            ('jus-pt', 'Justice Pro Tem'),
            ('mag-pt', 'Magistrate Pro Tem'),

            # Referee
            ('ref-jud-tr',      'Judge Trial Referee'),
            ('ref-off',         'Official Referee'),
            ('ref-state-trial', 'State Trial Referee'),

            # Retired
            ('ret-act-jus',    'Active Retired Justice'),
            ('ret-ass-jud',    'Retired Associate Judge'),
            ('ret-c-jud',      'Retired Chief Judge'),
            ('ret-jus',        'Retired Justice'),
            ('ret-senior-jud', 'Senior Judge'),

            # Special
            ('spec-chair',  'Special Chairman'),
            ('spec-jud',    'Special Judge'),
            ('spec-m',      'Special Master'),
            ('spec-scjcbc', 'Special Superior Court Judge for Complex Business '
                            'Cases'),
            # Other
            ('chair',     'Chairman'),
            ('chan',      'Chancellor'),
            ('mag',       'Magistrate'),
            ('presi-jud', 'President'),
            ('res-jud',   'Reserve Judge'),
            ('trial-jud', 'Trial Judge'),
            ('vice-chan', 'Vice Chancellor'),
            ('vice-cj',   'Vice Chief Judge'),
        )),
        # Sometimes attorney generals write opinions too
        ('Attorney General', (
            ('att-gen',          'Attorney General'),
            ('att-gen-ass',      'Assistant Attorney General'),
            ('att-gen-ass-spec', 'Special Assistant Attorney General'),
            ('sen-counsel',      'Senior Counsel'),
            ('dep-sol-gen',      'Deputy Solicitor General'),
        )),
        ('Appointing Authority', (
            ('pres',          'President of the United States'),
            ('gov',           'Governor'),
        )),
        ('Clerkships', (
            ('clerk',      'Clerk'),
            ('staff-atty', 'Staff Attorney'),
        )),

        ('prof',    'Professor'),
        ('prac',    'Practitioner'),
        ('pros',    'Prosecutor'),
        ('pub_def', 'Public Defender'),
        ('legis',   'Legislator'),
    )
    POSITION_TYPE_GROUPS = make_choices_group_lookup(POSITION_TYPES)
    NOMINATION_PROCESSES = (
        ('fed_senate', 'U.S. Senate'),
        ('state_senate', 'State Senate'),
        ('election', 'Primary Election'),
        ('merit_comm', 'Merit Commission'),
    )
    VOTE_TYPES = (
        ('s', 'Senate'),
        ('p', 'Partisan Election'),
        ('np', 'Non-Partisan Election'),
    )
    JUDICIAL_COMMITTEE_ACTIONS = (
        ('no_rep', 'Not Reported'),
        ('rep_w_rec', 'Reported with Recommendation'),
        ('rep_wo_rec', 'Reported without Recommendation'),
        ('rec_postpone', 'Recommendation Postponed'),
        ('rec_bad', 'Recommended Unfavorably'),
    )
    SELECTION_METHODS = (
        ('Election', (
            ('e_part', 'Partisan Election'),
            ('e_non_part', 'Non-Partisan Election'),

        )),
        ('Appointment', (
            ('a_pres', 'Appointment (President)'),
            ('a_gov', 'Appointment (Governor)'),
            ('a_legis', 'Appointment (Legislature)'),
            # FISC appointments are made by the chief justice of SCOTUS
            ('a_judge', 'Appointment (Judge)'),
        )),
    )
    SELECTION_METHOD_GROUPS = make_choices_group_lookup(SELECTION_METHODS)
    TERMINATION_REASONS = (
        ('ded', 'Death'),
        ('retire_vol', 'Voluntary Retirement'),
        ('retire_mand', 'Mandatory Retirement'),
        ('resign', 'Resigned'),
        ('other_pos', 'Appointed to Other Judgeship'),
        ('lost', 'Lost Election'),
        ('abolished', 'Court Abolished'),
        ('bad_judge', 'Impeached and Convicted'),
        ('recess_not_confirmed', 'Recess Appointment Not Confirmed'),
        ('termed_out', 'Term Limit Reached'),
    )
    position_type = models.CharField(
        help_text="If this is a judicial position, this indicates the role the "
                  "person had. This field may be blank if job_title is "
                  "complete instead.",
        choices=POSITION_TYPES,
        max_length=20,
        blank=True,
        null=True,
    )
    job_title = models.CharField(
        help_text="If title isn't in position_type, a free-text position may "
                  "be entered here.",
        max_length=100,
        blank=True,
    )
    person = models.ForeignKey(
        Person,
        help_text="The person that held the position.",
        related_name='positions',
        blank=True,
        null=True,
    )
    court = models.ForeignKey(
        Court,
        help_text="If this was a judicial position, this is the jurisdiction "
                  "where it was held.",
        related_name='court_positions',
        blank=True,
        null=True,
    )
    school = models.ForeignKey(
        School,
        help_text="If this was an academic job, this is the school where the "
                  "person worked.",
        blank=True,
        null=True,
    )
    organization_name = models.CharField(
        help_text="If the organization where this position was held is not a "
                  "school or court, this is the place it was held.",
        max_length=120,
        blank=True,
        null=True,
    )
    location_city = models.CharField(
        help_text="If not a court or school, the city where person worked.",
        max_length=50,
        blank=True,
    )
    location_state = local_models.USStateField(
        help_text="If not a court or school, the state where person worked.",
        blank=True,
    )
    appointer = models.ForeignKey(
        'self',
        help_text="If this is an appointed position, the person-position "
                  "responsible for the appointment. This field references "
                  "other positions instead of referencing people because that "
                  "allows you to know the position a person held when an "
                  "appointment was made.",
        related_name='appointed_positions',
        blank=True,
        null=True,
    )
    supervisor = models.ForeignKey(
        Person,
        help_text="If this is a clerkship, the supervising judge.",
        related_name='supervised_positions',
        blank=True,
        null=True,
    )
    predecessor = models.ForeignKey(
        Person,
        help_text="The person that previously held this position",
        blank=True,
        null=True,
    )
    date_created = models.DateTimeField(
        help_text="The time when this item was created",
        auto_now_add=True,
        db_index=True,
    )
    date_modified = models.DateTimeField(
        help_text="The last moment when the item was modified.",
        auto_now=True,
        db_index=True,
    )
    date_nominated = models.DateField(
        help_text="The date recorded in the Senate Executive Journal when a "
                  "federal judge was nominated for their position or the date "
                  "a state judge nominated by the legislature. When a "
                  "nomination is by primary election, this is the date of the "
                  "election. When a nomination is from a merit commission, "
                  "this is the date the nomination was announced.",
        null=True,
        blank=True,
        db_index=True,
    )
    date_elected = models.DateField(
        help_text="Judges are elected in most states. This is the date of their"
                  "first election. This field will be null if the judge was "
                  "initially selected by nomination.",
        null=True,
        blank=True,
        db_index=True,
    )
    date_recess_appointment = models.DateField(
        help_text="If a judge was appointed while congress was in recess, this "
                  "is the date of that appointment.",
        null=True,
        blank=True,
        db_index=True,
    )
    date_referred_to_judicial_committee = models.DateField(
        help_text="Federal judges are usually referred to the Judicial "
                  "Committee before being nominated. This is the date of that "
                  "referral.",
        null=True,
        blank=True,
        db_index=True,
    )
    date_judicial_committee_action = models.DateField(
        help_text="The date that the Judicial Committee took action on the "
                  "referral.",
        null=True,
        blank=True,
        db_index=True,
    )
    judicial_committee_action = models.CharField(
        help_text="The action that the judicial committee took in response to "
                  "a nomination",
        choices=JUDICIAL_COMMITTEE_ACTIONS,
        max_length=20,
        blank=True,
    )
    date_hearing = models.DateField(
        help_text="After being nominated, a judge is usually subject to a "
                  "hearing. This is the date of that hearing.",
        null=True,
        blank=True,
        db_index=True,
    )
    date_confirmation = models.DateField(
        help_text="After the hearing the senate will vote on judges. This is "
                  "the date of that vote.",
        null=True,
        blank=True,
        db_index=True,
    )
    date_start = models.DateField(
        help_text="The date the position starts active duty.",
        db_index=True,
    )
    date_granularity_start = models.CharField(
        choices=DATE_GRANULARITIES,
        max_length=15,
    )
    date_termination = models.DateField(
        help_text="The last date of their employment. The compliment to "
                  "date_start",
        null=True,
        blank=True,
        db_index=True,
    )
    termination_reason = models.CharField(
        help_text="The reason for a termination",
        choices=TERMINATION_REASONS,
        max_length=25,
        blank=True,
    )
    date_granularity_termination = models.CharField(
        choices=DATE_GRANULARITIES,
        max_length=15,
        blank=True,
    )
    date_retirement = models.DateField(
        help_text="The date when they become a senior judge by going into "
                  "active retirement",
        null=True,
        blank=True,
        db_index=True,
    )
    nomination_process = models.CharField(
        help_text="The process by which a person was nominated into this "
                  "position.",
        choices=NOMINATION_PROCESSES,
        max_length=20,
        blank=True,
    )
    vote_type = models.CharField(
        help_text="The type of vote that resulted in this position.",
        choices=VOTE_TYPES,
        max_length=2,
        blank=True,
    )
    voice_vote = models.NullBooleanField(
        help_text="Whether the Senate voted by voice vote for this position.",
        blank=True,
    )
    votes_yes = models.PositiveIntegerField(
        help_text="If votes are an integer, this is the number of votes in "
                  "favor of a position.",
        null=True,
        blank=True,
    )
    votes_no = models.PositiveIntegerField(
        help_text="If votes are an integer, this is the number of votes "
                  "opposed to a position.",
        null=True,
        blank=True,
    )
    votes_yes_percent = models.FloatField(
        help_text="If votes are a percentage, this is the percentage of votes "
                  "in favor of a position.",
        null=True,
        blank=True,
    )
    votes_no_percent = models.FloatField(
        help_text="If votes are a percentage, this is the percentage of votes "
                  "opposed to a position.",
        null=True,
        blank=True,
    )
    how_selected = models.CharField(
        help_text="The method that was used for selecting this judge for this "
                  "position (generally an election or appointment).",
        choices=SELECTION_METHODS,
        max_length=20,
        blank=True,
    )
    has_inferred_values = models.BooleanField(
        help_text="Some or all of the values for this position were inferred "
                  "from a data source instead of manually added. See sources "
                  "field for more details.",
        default=False,
    )

    def __unicode__(self):
        return u'%s: %s at %s' % (self.pk, self.person.name_full, self.court_id)

    @property
    def is_judicial_position(self):
        """Return True if the position is judicial."""
        if self.POSITION_TYPE_GROUPS.get(self.position_type) == 'Judge':
            return True
        return False

    @property
    def is_clerkship(self):
        """Return True if the position is a clerkship."""
        if self.POSITION_TYPE_GROUPS.get(self.position_type) == 'Clerkships':
            return True
        return False

    @property
    def vote_string(self):
        """Make a human-friendly string from the vote information"""
        s = ''

        # Do vote type first
        if self.vote_type == 's':
            s += "Senate voted"
            if self.voice_vote:
                s += ' <span class="alt">by</span> voice vote'
        elif self.vote_type in ['p', 'np']:
            s += self.get_vote_type_display()

        # Then do vote counts/percentages, if we have that info.
        if self.votes_yes or self.votes_yes_percent:
            s += ', '
        if self.votes_yes:
            s += '%s in favor <span class="alt">and</span> %s ' \
                           'opposed' % (self.votes_yes, self.votes_no)
        elif self.votes_yes_percent:
            s += '%g%% in favor <span class="alt">and</span> ' \
                           '%g%% opposed' % (self.votes_yes_percent,
                                             self.votes_no_percent)
        return s

    @property
    def html_title(self):
        """Display the position as a title."""
        s = ''

        # Title
        if self.get_position_type_display():
            s += self.get_position_type_display()
        else:
            s += self.job_title

        # Where
        if self.school or self.organization_name or self.court:
            s += ' <span class="alt text-lowercase">at</span> '
            if self.court:
                s += self.court.full_name
            elif self.school:
                s += self.school
            elif self.organization_name:
                s += self.organization_name

        # When
        if self.date_start or self.date_termination:
            if self.date_termination:
                end_date = granular_date(self, 'date_termination')
            else:
                # If we don't know when the position ended, we use a ? if the
                # person has died, or say Present if they're alive.
                if self.person.date_dod:
                    end_date = "?"
                else:
                    end_date = "Present"

            s += ' <span class="text-capitalize">(%s &ndash; %s)' % (
                granular_date(self, 'date_start', default="Unknown Date"),
                end_date,
            )
        return s

    @property
    def sorted_appointed_positions(self):
        """Appointed positions, except sorted by date instead of name."""
        return self.appointed_positions.all().order_by('-date_start')

    def save(self, *args, **kwargs):
        self.full_clean()
        super(Position, self).save(*args, **kwargs)

    def clean_fields(self, *args, **kwargs):
        validate_partial_date(self, ['start', 'termination'])
        validate_is_not_alias(self, ['person', 'supervisor', 'predecessor',
                                     'school'])
        validate_at_most_n(self, 1, ['school', 'organization_name', 'court'])
        validate_exactly_n(self, 1, ['position_type', 'job_title'])
        validate_all_or_none(self, ['votes_yes', 'votes_no'])
        validate_all_or_none(self, ['votes_yes_percent', 'votes_no_percent'])
        validate_not_all(self, ['votes_yes', 'votes_no', 'votes_yes_percent',
                                'votes_no_percent'])
        validate_nomination_fields_ok(self)
        validate_supervisor(self)

        super(Position, self).clean_fields(*args, **kwargs)
Exemplo n.º 11
0
class User(AbstractBaseUser, PermissionsMixin):
    """
    An email based user model
    """
    first_name = models.CharField(_('first name'), max_length=30, blank=True)
    last_name = models.CharField(_('last name'), max_length=30, blank=True)
    email = models.EmailField(_('email address'), unique=True)
    title = models.CharField(max_length=100, blank=True, null=True)
    is_staff = models.BooleanField(
        _('staff status'),
        default=False,
        help_text=_('Designates whether the user can log into this admin '
                    'site.'))
    is_active = models.BooleanField(
        _('active'),
        default=True,
        help_text=_('Designates whether this user should be treated as '
                    'active. Unselect this instead of deleting accounts.'))
    date_joined = models.DateTimeField(_('date joined'), default=timezone.now)

    # Profile data
    primary_phone = localflavor_models.PhoneNumberField(_('Primary Phone'),
                                                        max_length=160,
                                                        blank=True)
    other_phone = localflavor_models.PhoneNumberField(_('Other Phone'),
                                                      max_length=160,
                                                      blank=True)
    fax = localflavor_models.PhoneNumberField(_('Fax'),
                                              max_length=160,
                                              blank=True)
    company_name = models.CharField(_('Company Name'),
                                    max_length=160,
                                    blank=True)
    address = models.CharField(_('Address'), max_length=160, blank=True)
    address2 = models.CharField(_('Address 2'), max_length=160, blank=True)
    city = models.CharField(_('City'), max_length=160, blank=True)
    state = localflavor_models.USStateField(_('State/Province'),
                                            max_length=160,
                                            blank=True)
    code = localflavor_models.USZipCodeField(_('Zip Code'),
                                             max_length=160,
                                             blank=True)

    objects = UserManager()

    USERNAME_FIELD = 'email'

    class Meta:
        verbose_name = _('user')
        verbose_name_plural = _('users')

    def __unicode__(self):
        full_name = self.get_full_name()
        return full_name if full_name else self.email

    def save(self, *args, **kwargs):
        """
        Always save the email as lowercase. Helps identifying unique email
        addresses.
        The de jure standard is that the local component of email addresses is
        case sensitive however the de facto standard is that they are not. In
        practice what happens is user confusion over why an email address
        entered with camel casing one day does not match an email address
        entered in different casing another day.
        """
        self.email = self.email.lower()
        return super(User, self).save(*args, **kwargs)

    def get_username(self):
        """
        Returns the email address
        Satisifies API needs of other libraries.
        """
        return self.email

    def get_full_name(self):
        """
        Returns the first_name plus the last_name, with a space in between.
        """
        full_name = '%s %s' % (self.first_name, self.last_name)
        return full_name.strip()

    def get_short_name(self):
        """Returns the short name for the user."""
        return self.first_name

    def email_user(self, subject, message, from_email=None, **kwargs):
        """Sends an email to this User."""
        send_mail(subject, message, from_email, [self.email], **kwargs)
Exemplo n.º 12
0
class Location(models.Model):
    city = models.CharField(max_length=100)
    # locality is for certain places (such as queens) where the google
    # locality and neighborhood are different
    locality = models.CharField(max_length=100, default="")
    state = us_models.USStateField()
    address = models.CharField(max_length=255)
    zipcode = us_models.USZipCodeField()
    latitude = models.DecimalField(
        max_digits=9, decimal_places=6, blank=True, null=True
    )
    longitude = models.DecimalField(
        max_digits=9, decimal_places=6, blank=True, null=True
    )
    last_fetched_zillow = models.DateTimeField(blank=True, null=True)

    @property
    def full_address(self):
        addr_components = map(str, [self.address, self.city, self.state, self.zipcode])
        return ", ".join(addr_components)

    @property
    def url_encoded_full_address(self):
        return quote(self.full_address)

    @property
    def google_map_url(self):
        return f"https://www.google.com/maps/search/?api=1&query={self.url_encoded_full_address}"

    @property
    def representative_image(self):
        return self.apartment_set.exclude(image=None).first().picture_url

    @property
    def representative_image_or_placeholder(self):
        image = self.representative_image
        return image if image is not None else "/static/img/no_img.png"

    @property
    def rent_price_for_display(self):
        count = self.apartment_set.count()
        if count == 0:
            return None
        elif count == 1:
            return self.apartment_set.first().rent_price_for_display
        else:
            minimum = f"{self.apartment_set.order_by('rent_price')[0].rent_price:.0f}"
            maximum = f"{self.apartment_set.order_by('-rent_price')[0].rent_price:.0f}"
            return f"${minimum} - {maximum}"

    def avg_rate(self):
        review_sum = 0
        for review in self.review_set.all():
            review_sum += review.rating
        if self.review_set.count() != 0:
            avg = review_sum / self.review_set.count()
            return float("%.2f" % round(avg, 2))
        else:
            return 0

    def check_tenant(self, user):
        return self.apartment_set.filter(tenant=user).exists()

    def check_landlord(self, user):
        return self.apartment_set.filter(landlord=user).exists()
Exemplo n.º 13
0
class UserMessageInfo(EmailCongressModel):

    user = models.ForeignKey(User, db_index=True)
    default = models.NullBooleanField(default=False)

    PREFIX_CHOICES = (('Mr.', 'Mr.'), ('Mrs.', 'Mrs.'), ('Ms.', "Ms."))

    # input by user
    prefix = models.CharField(max_length=32,
                              blank=False,
                              choices=PREFIX_CHOICES)
    first_name = models.CharField(max_length=256, blank=False)
    last_name = models.CharField(max_length=256, blank=False)
    street_address = models.CharField(max_length=1000, blank=False)
    street_address2 = models.CharField(max_length=1000, blank=True, null=True)
    city = models.CharField(max_length=256, blank=False)
    state = us_models.USStateField(blank=False)
    zip5 = models.CharField(max_length=5, blank=False)
    zip4 = models.CharField(max_length=4, blank=False)
    phone_number = models.CharField(max_length=20, blank=False)
    accept_tos = models.DateTimeField(null=True)

    # set by methods based on input address information above
    latitude = models.CharField(max_length=256, blank=True, null=True)
    longitude = models.CharField(max_length=256, blank=True, null=True)
    district = models.IntegerField(blank=True, null=True)

    def __str__(self):
        return "{0} {1}".format(self.first_name, self.last_name)

    @property
    def members_of_congress(self):
        if self.district is None:
            self.determine_district()
        return Legislator.members_for_state_and_district(
            self.state, self.district).order_by('title')

    @property
    def humanized_district(self):
        return Legislator.humanized_district(self.state, self.district)

    @property
    def humanized_district_no_state(self):
        return Legislator.humanized_district(None, self.district)

    @property
    def humanized_state(self):
        return Legislator.humanized_state(self.state)

    def confirm_accept_tos(self):
        self.accept_tos = timezone.now()
        self.save()

    def mailing_address(self):
        return "{0} {1}, {2}, {3} {4}-{5}".format(self.street_address,
                                                  self.street_address2,
                                                  self.city, self.state,
                                                  self.zip5, self.zip4)

    def must_update_address_info(self):
        return self.accept_tos is None or (
            timezone.now() - self.accept_tos).days >= settings.DAYS_TOS_VALID

    def complete_information(self):
        if self.district is None:
            self.determine_district()
        if not self.zip4:
            self.zip4_lookup(force=True)

    def geolocate_address(self, force=False, save=False):

        if force or (self.latitude is None or self.longitude is None):
            try:
                self.latitude, self.longitude = geolocation_service.geolocate(
                    street_address=self.street_address,
                    city=self.city,
                    state=self.state,
                    zip5=self.zip5)
                if save:
                    self.save()
                return self.latitude, self.longitude
            except:
                raise

    def determine_district(self, force=False, save=False):
        data = determine_district_service.determine_district(zip5=self.zip5)
        if data is None or len(data) > 1:
            lat, lng = self.geolocate_address(force, save)
            data = determine_district_service.determine_district(latitude=lat,
                                                                 longitude=lng)
        try:
            self.district = data[0].get('district')
            self.state = data[0].get('state')
            if save:
                self.save()
            return self.district
        except:
            return None  # TODO robust error handling

    def zip4_lookup(self, force=False):
        if force or not self.zip4:
            try:
                zip4 = address_inferrence_service.zip4_lookup(
                    self.street_address, self.city, self.state, self.zip5)
                self.update(zip4=zip4)
            except:
                pass

    def get_district_geojson_url(self):
        return Legislator.get_district_geojson_url(self.state, self.district)

    def clone_instance_for_address_update(self):
        """
        By setting pk to None then saving will create a new record.

        @return: None
        @rtype: None
        """
        self.pk = None
        self.updating = True
        self.accept_tos = None
Exemplo n.º 14
0
class Person(models.Model):
    RELIGIONS = (
        ('ca', 'Catholic'),
        ('pr', 'Protestant'),
        ('je', 'Jewish'),
        ('mu', 'Muslim'),
        ('at', 'Atheist'),
        ('ag', 'Agnostic'),
        ('mo', 'Mormon'),
        ('bu', 'Buddhist'),
        ('hi', 'Hindu')
    )
    race = models.ManyToManyField(
        'Race',
        blank=True,
    )
    is_alias_of = models.ForeignKey(
        'self',
        related_name="aliases",
        blank=True,
        null=True,
    )
    date_created = models.DateTimeField(
        help_text="The original creation date for the item",
        auto_now_add=True,
        db_index=True
    )
    date_modified = models.DateTimeField(
        help_text="The last moment when the item was modified.",
        auto_now=True,
        db_index=True,
    )
    fjc_id = models.IntegerField(
        help_text="The ID of a judge as assigned by the Federal Judicial "
                  "Center.",
        null=True,
        blank=True,
        unique=True,
        db_index=True,
    )
    cl_id = models.CharField(
        max_length=30,
        help_text="A unique identifier for judge, also indicating source of "
                  "data.",
        unique=True,
        db_index=True
    )
    slug = models.SlugField(
        max_length=158  # len(self.name_full)
    )
    name_first = models.CharField(
        max_length=50,
    )
    name_middle = models.CharField(
        max_length=50,
        blank=True,
    )
    name_last = models.CharField(
        max_length=50,
        db_index=True,
    )
    name_suffix = models.CharField(
        choices=SUFFIXES,
        max_length=5,
        blank=True,
    )
    date_dob = models.DateField(
        null=True,
        blank=True,
    )
    date_granularity_dob = models.CharField(
        choices=DATE_GRANULARITIES,
        max_length=15,
        blank=True,
    )
    date_dod = models.DateField(
        null=True,
        blank=True,
    )
    date_granularity_dod = models.CharField(
        choices=DATE_GRANULARITIES,
        max_length=15,
        blank=True,
    )
    dob_city = models.CharField(
        max_length=50,
        blank=True,
    )
    dob_state = local_models.USStateField(
        blank=True,
    )
    dod_city = models.CharField(
        max_length=50,
        blank=True,
    )
    dod_state = local_models.USStateField(
        blank=True,
    )
    gender = models.CharField(
        choices=GENDERS,
        max_length=2,
        blank=True,
    )
    religion = models.CharField(
        max_length=30,
        blank=True
    )
    has_photo = models.BooleanField(
        help_text="Whether there is a photo corresponding to this person in "
                  "the judge pics project.",
        default=False,
    )

    def __unicode__(self):
        return u'%s: %s' % (self.pk, self.name_full)

    def get_absolute_url(self):
        return reverse('view_person', args=[self.pk, self.slug])

    def save(self, *args, **kwargs):
        self.slug = slugify(trunc(self.name_full, 158))
        self.full_clean()
        super(Person, self).save(*args, **kwargs)

    def clean_fields(self, *args, **kwargs):
        validate_partial_date(self, ['dob', 'dod'])
        validate_is_not_alias(self, ['is_alias_of'])
        validate_has_full_name(self)
        super(Person, self).clean_fields(*args, **kwargs)

    @property
    def name_full(self):
        return u' '.join([v for v in [
            self.name_first,
            self.name_middle,
            self.name_last,
            self.get_name_suffix_display(),
        ] if v]).strip()

    @property
    def name_full_reverse(self):
        return u'{name_last}, {name_first} {name_middle}, {suffix}'.format(
            suffix=self.get_name_suffix_display(),
            **self.__dict__
        ).strip(', ')

    @property
    def is_alias(self):
        return True if self.is_alias_of is not None else False

    @property
    def is_judge(self):
        """Examine the positions a person has had and identify if they were ever
        a judge.
        """
        for position in self.positions.all():
            if position.is_judicial_position:
                return True
        return False

    class Meta:
        verbose_name_plural = "people"
Exemplo n.º 15
0
class Legislator(EmailCongressModel):

    bioguide_id = models.CharField(max_length=7,
                                   unique=True,
                                   null=False,
                                   db_index=True)
    chamber = models.CharField(max_length=20, db_index=True)
    state = us_models.USStateField(db_index=True)
    district = models.IntegerField(null=True, db_index=True)
    title = models.CharField(max_length=3, db_index=True)
    first_name = models.CharField(max_length=256, db_index=True)
    last_name = models.CharField(max_length=256, db_index=True)
    contact_form = models.CharField(max_length=1024, null=True, db_index=True)
    email = models.CharField(max_length=256, db_index=True)
    contactable = models.BooleanField(default=True, db_index=True)

    FIPS_CODES = {
        "AK": "02",
        "AL": "01",
        "AR": "05",
        "AS": "60",
        "AZ": "04",
        "CA": "06",
        "CO": "08",
        "CT": "09",
        "DC": "11",
        "DE": "10",
        "FL": "12",
        "GA": "13",
        "GU": "66",
        "HI": "15",
        "IA": "19",
        "ID": "16",
        "IL": "17",
        "IN": "18",
        "KS": "20",
        "KY": "21",
        "LA": "22",
        "MA": "25",
        "MD": "24",
        "ME": "23",
        "MI": "26",
        "MN": "27",
        "MO": "29",
        "MS": "28",
        "MT": "30",
        "NC": "37",
        "ND": "38",
        "NE": "31",
        "NH": "33",
        "NJ": "34",
        "NM": "35",
        "NV": "32",
        "NY": "36",
        "OH": "39",
        "OK": "40",
        "OR": "41",
        "PA": "42",
        "PR": "72",
        "RI": "44",
        "SC": "45",
        "SD": "46",
        "TN": "47",
        "TX": "48",
        "UT": "49",
        "VA": "51",
        "VI": "78",
        "VT": "50",
        "WA": "53",
        "WI": "55",
        "WV": "54",
        "WY": "56"
    }

    CONGRESS_API_COLUMNS = [
        'bioguide_id', 'chamber', 'state', 'district', 'title', 'first_name',
        'last_name', 'contact_form'
    ]

    def __str__(self):
        return "{0} {1} {2}".format(self.title, self.first_name,
                                    self.last_name)

    @property
    def full_title(self):
        return {
            'Com': 'Commissioner',
            'Del': 'Delegate',
            'Rep': 'Representative',
            'Sen': 'Senator'
        }.get(self.title, 'Representative')

    @property
    def full_name(self):
        return "{0} {1}".format(self.first_name, self.last_name)

    @property
    def title_and_last_name(self):
        return "{0} {1}".format(self.title, self.last_name)

    @property
    def title_and_full_name(self):
        return "{0} {1}".format(self.title, self.full_name)

    @property
    def full_title_and_full_name(self):
        return "{0} {1}".format(self.full_title, self.full_name)

    @property
    def image_url(self, size='small'):
        dimensions = {'small': '225x275', 'large': '450x550'}
        return "https://raw.githubusercontent.com/unitedstates/images/gh-pages/congress/{0}/{1}.jpg".format(
            dimensions.get(size, dimensions['small']), self.bioguide_id)

    def create_email_address(self):
        raise NotImplementedError  # TODO

    @staticmethod
    def humanized_district(state, district):
        d = '{0} Congressional district'.format(
            utils.ordinal(district) if int(district) > 0 else 'At-Large')
        if state:
            d += ' of {0}'.format(usps.CODE_TO_STATE.get(state))
        return d

    @property
    def humanized_constituency(self):
        return Legislator.humanized_district(self.state, self.district)

    @staticmethod
    def humanized_state(state):
        return usps.CODE_TO_STATE.get(state)

    @staticmethod
    def get_district_geojson_url(state, district):
        try:
            fips = Legislator.FIPS_CODES.get(state, "")
            return "http://realtime.influenceexplorer.com/geojson/cd113_geojson/%s%0*d.geojson" % (
                fips, 2, int(district))
        except:
            return ""

    @staticmethod
    def doctor_email(email):
        """
        Converts an email string to an opencongress.org address by string replacement.

        @param email: the email to convert to an opencongress.org address
        @type email: str
        @return: converted email
        @rtype: str
        """
        return email.replace("opencongress.org",
                             settings.CONFIG_DICT['email']['domain'])

    @staticmethod
    def find_by_email(recip_email):
        return Legislator.objects.filter(
            email__iexact=Legislator.doctor_email(recip_email)).first()

    @staticmethod
    def get_leg_buckets_from_emails(permitted_legs, emails):
        """
        Retrieves

        @param permitted_legs:
        @type permitted_legs:
        @param emails:
        @type emails:
        @return: dictionary containing the various states of legislators to a user
        @rtype: dict[str, list]
        """
        legs = {
            label: []
            for label in [
                'contactable', 'non_existent', 'uncontactable',
                'does_not_represent'
            ]
        }
        inbound_emails = [email_addr for email_addr in emails]

        catch_all = [
            x for x in inbound_emails
            if settings.CONFIG_DICT['email']['catch_all'] in x
        ]
        if catch_all:
            legs['contactable'] = permitted_legs
            for email in catch_all:
                inbound_emails.remove(email)

        # maximize error messages for users for individual addresses
        for recip_email in inbound_emails:
            # IMPORTANT! OC_EMAIL is legacy from @opencongress.org. The new addresses are @emailcongress.us.
            leg = Legislator.find_by_email(recip_email)
            if leg is None:
                legs['non_existent'].append(
                    recip_email)  # TODO refer user to index page?
            elif not leg.contactable:
                legs['uncontactable'].append(leg)
            elif leg not in permitted_legs:
                legs['does_not_represent'].append(leg)
            elif leg not in legs['contactable']:
                legs['contactable'].append(leg)
            else:
                continue

        return legs

    @staticmethod
    def members_for_state_and_district(state, district, contactable=True):
        query = Q(state=state) & (Q(district=None) | Q(district=district))
        if contactable:
            query = query & Q(contactable=True)
        return Legislator.objects.filter(query).all()
Exemplo n.º 16
0
class Location(models.Model):
    city = models.CharField(max_length=64)
    state = us_models.USStateField()
    
    def __unicode__(self):
        return "%s, %s" % (self.city, self.state)
Exemplo n.º 17
0
class Person(models.Model):
    RELIGIONS = (
        ('ca', 'Catholic'),
        ('pr', 'Protestant'),
        ('je', 'Jewish'),
        ('mu', 'Muslim'),
        ('at', 'Atheist'),
        ('ag', 'Agnostic'),
        ('mo', 'Mormon'),
        ('bu', 'Buddhist'),
        ('hi', 'Hindu')
    )
    race = models.ManyToManyField(
        'Race',
        blank=True,
    )
    is_alias_of = models.ForeignKey(
        'self',
        blank=True,
        null=True,
    )
    date_created = models.DateTimeField(
        help_text="The original creation date for the item",
        auto_now_add=True,
        db_index=True
    )
    date_modified = models.DateTimeField(
        help_text="The last moment when the item was modified.",
        auto_now=True,
        db_index=True,
    )
    fjc_id = models.IntegerField(
        help_text="The ID of a judge as assigned by the Federal Judicial "
                  "Center.",
        null=True,
        blank=True,
        unique=True,
        db_index=True,
    )
    cl_id = models.CharField(
        max_length=30,
        help_text="A unique identifier for judge, also indicating source of "
                  "data.",
        unique=True,
        db_index=True,
        null=True,
    )
    slug = models.SlugField(
        max_length=158  # len(self.name_full)
    )
    name_first = models.CharField(
        max_length=50,
    )
    name_middle = models.CharField(
        max_length=50,
        blank=True,
    )
    name_last = models.CharField(
        max_length=50,
        db_index=True,
    )
    name_suffix = models.CharField(
        choices=SUFFIXES,
        max_length=5,
        blank=True,
    )
    date_dob = models.DateField(
        null=True,
        blank=True,
    )
    date_granularity_dob = models.CharField(
        choices=DATE_GRANULARITIES,
        max_length=15,
        blank=True,
    )
    date_dod = models.DateField(
        null=True,
        blank=True,
    )
    date_granularity_dod = models.CharField(
        choices=DATE_GRANULARITIES,
        max_length=15,
        blank=True,
    )
    dob_city = models.CharField(
        max_length=50,
        blank=True,
    )
    dob_state = local_models.USStateField(
        blank=True,
    )
    dod_city = models.CharField(
        max_length=50,
        blank=True,
    )
    dod_state = local_models.USStateField(
        blank=True,
    )
    gender = models.CharField(
        choices=GENDERS,
        max_length=2,
        blank = True
    )
    religion = models.CharField(
        choices=RELIGIONS,
        max_length=2,
        blank=True
    )

    def __unicode__(self):
        return u'%s: %s' % (self.pk, self.name_full)

    def get_absolute_url(self):
        return reverse('view_judge', args=[self.pk, self.slug])

    def save(self, *args, **kwargs):
        self.slug = slugify(trunc(self.name_full, 158))
        self.full_clean()
        super(Person, self).save(*args, **kwargs)

    def clean_fields(self, *args, **kwargs):
        for field in ['dob', 'dod']:
            validate_partial_date(self, field)
        super(Person, self).clean_fields(*args, **kwargs)

    @property
    def name_full(self):
        return ' '.join([
            self.name_first,
            self.name_middle,
            self.name_last,
            self.get_name_suffix_display(),
        ]).strip()

    class Meta:
        verbose_name_plural = "people"
Exemplo n.º 18
0
class Account(AbstractBaseUser):
    """Returns a new Account object inherited from AbstractBaseUser.

    AbstractBaseUser: The parent class of users

    Note: email, businessname, zipcode, city, state, phone
          are required
    """

    email = models.EmailField(max_length=255, unique=True)
    businessname = models.CharField(max_length=35,
                                    blank=False,
                                    default='buname')
    spaceId = models.CharField(max_length=10,
                               unique=True,
                               blank=True,
                               null=True)
    zipcode = usmodels.USZipCodeField(blank=False, default='00000')
    city = models.CharField(max_length=50, blank=False, default='--------')
    state = usmodels.USStateField(choices=US_STATES,
                                  blank=False,
                                  default='--------')
    phone = usmodels.PhoneNumberField(blank=False, default='000-000-0000')

    SHIRT_SIZES = (
        ('1', 'Silver'),
        ('2', 'Gold'),
        ('3', 'Platinum'),
    )
    tierlist = models.CharField(blank=True,
                                null=True,
                                max_length=1,
                                choices=SHIRT_SIZES)

    is_admin = models.BooleanField(default=False)
    is_staff = models.BooleanField(default=False)
    is_superuser = models.BooleanField(default=False)
    is_active = models.BooleanField(default=False)

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    objects = AccountManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['businessname', 'zipcode', 'city', 'state', 'phone']

    def __unicode__(self):
        return self.email

    def get_full_name(self):
        return ' '.join([self.email, self.businessname])

    def get_short_name(self):
        return self.email

    def has_module_perms(self, app_label):
        return self.is_admin

    def has_perm(self, perm, obj=None):
        return self.is_admin
Exemplo n.º 19
0
class CandidateProfile(models.Model):
    # Demographic
    GENDER_CHOICE_FEMALE = "F"
    GENDER_CHOICE_MALE = "M"
    GENDER_CHOICE_NON_BINARY = "X"
    ETHNICITY_HISPANIC_LATINO = "HL"
    ETHNICITY_OTHER = "OT"
    RACE_AMERICAN_INDIAN_ALASKA_NATIVE = "NATIVE"
    RACE_ASIAN = "ASIAN"
    RACE_BLACK_AFRICA = "BLACK"
    RACE_NATIVE_HAWAIIAN_PACIFIC_ISLANDER = "PACIFIC"
    RACE_WHITE = "WHITE"
    DISABILITY_HEALTH_CONDITIONS_POSITIVE = "POSITIVE"
    DISABILITY_HEALTH_CONDITIONS_NEGATIVE = "NEGATIVE"
    VETERAN_POSITIVE = "POSITIVE"
    VETERAN_NEGATIVE = "NEGATIVE"
    DEMOGRAPHIC_CHOICES = [
        (
            "Gender",
            (
                (GENDER_CHOICE_FEMALE, "Female"),
                (GENDER_CHOICE_MALE, "Male"),
                (GENDER_CHOICE_NON_BINARY, "Non Binary"),
            ),
        ),
        (
            "Ethnicity",
            (
                (ETHNICITY_HISPANIC_LATINO, "Hispanic or Latino"),
                (ETHNICITY_OTHER, "Not Hispanic or Latino"),
                (None, "Prefer not to specify"),
            ),
        ),
        (
            "Race",
            (
                (
                    RACE_AMERICAN_INDIAN_ALASKA_NATIVE,
                    "American indian or Alaska Native",
                ),
                (RACE_ASIAN, "Asian"),
                (RACE_BLACK_AFRICA, "Black or African American"),
                (
                    RACE_NATIVE_HAWAIIAN_PACIFIC_ISLANDER,
                    "Native Hawaiian or Pacific Islander",
                ),
                (RACE_WHITE, "White"),
                (None, "Prefer not to specify"),
            ),
        ),
        (
            "Disability and Health Conditions",
            (
                (
                    DISABILITY_HEALTH_CONDITIONS_POSITIVE,
                    "One or more health conditions",
                ),
                (DISABILITY_HEALTH_CONDITIONS_NEGATIVE, "None listed apply"),
                (None, "Prefer not to specify"),
            ),
        ),
        (
            "Veteran",
            (
                (VETERAN_POSITIVE, "Veteran"),
                (VETERAN_NEGATIVE, "Not veteran"),
                (None, "Prefer not to specify"),
            ),
        ),
    ]
    first_name = models.CharField(max_length=30, blank=True, null=True)
    last_name = models.CharField(max_length=30, blank=True, null=True)
    gender = models.CharField(max_length=1,
                              choices=DEMOGRAPHIC_CHOICES[0][1],
                              blank=True,
                              null=True)
    ethnicity = models.CharField(max_length=2,
                                 choices=DEMOGRAPHIC_CHOICES[1][1],
                                 blank=True,
                                 null=True)
    race = models.CharField(max_length=7,
                            choices=DEMOGRAPHIC_CHOICES[2][1],
                            blank=True,
                            null=True)
    health_conditions = models.CharField(max_length=8,
                                         choices=DEMOGRAPHIC_CHOICES[3][1],
                                         blank=True,
                                         null=True)
    veteran = models.CharField(max_length=8,
                               choices=DEMOGRAPHIC_CHOICES[4][1],
                               blank=True,
                               null=True)
    address_line = models.CharField(max_length=100, blank=True, null=True)
    zip_code = mailing.USZipCodeField(blank=True, null=True)
    state = mailing.USStateField(blank=True, null=True)
    phone = PhoneNumberField(blank=True, null=True)
    email = models.EmailField(blank=True, null=True)
    portfolio_website = models.URLField(help_text="e.g. http://example.com",
                                        blank=True,
                                        null=True,
                                        max_length=200)
    # Cover Letter
    cover_letter = models.FileField(
        storage=ResumeStorage(),
        upload_to=upload_to,
        null=True,
        blank=True,
        validators=[file_size],
    )
    # Resume chunks
    resume = models.FileField(
        storage=ResumeStorage(),
        upload_to=upload_to,
        null=True,
        blank=True,
        validators=[file_size],
    )
    additional_info = models.TextField(max_length=10000, blank=True, null=True)

    def __eq__(self, other):
        if not other:
            return False
        return self.id == other.id

    def __ne__(self, other):
        if not other:
            return False
        return self.id != other.id