def lookups(self, request, model_admin):
      address_model = get_address_model()

      if address_model == GoogleAddress:
        states = AddressComponent.objects.filter(channel__slug=request.channel, types__name="administrative_area_level_2").values_list('long_name', flat=True).distinct()

      if address_model == SimpleAddress:
        states = SimpleAddress.objects.filter(channel__slug=request.channel).values_list('city', flat=True).distinct()

      return [('', 'No city')] + [(x, x) for x in states]
    def queryset(self, request, queryset):
      address_model = get_address_model()
      city = request.GET.get('city', None)

      if city:
        if address_model == GoogleAddress:
          return queryset.filter(address__address_components__long_name=city, address__address_components__types__name="administrative_area_level_2")

        if address_model == SimpleAddress:
          return queryset.filter(address__city = city)
      return queryset
    def queryset(self, request, queryset):
      address_model = get_address_model()
      state = request.GET.get('state', None)

      if state:
        if address_model == GoogleAddress:
          return queryset.filter(address__address_components__short_name=state, address__address_components__types__name="administrative_area_level_1")

        if address_model == SimpleAddress:
          return queryset.filter(address__state = state)
      return queryset
class Organization(ChannelRelationship, RatedModelMixin):
    # Relationships
    owner = models.ForeignKey('users.User',
                              verbose_name=_('owner'),
                              related_name="organizations")
    address = models.OneToOneField(get_address_model(),
                                   blank=True,
                                   null=True,
                                   verbose_name=_('address'),
                                   db_constraint=False)
    image = models.ForeignKey('uploads.UploadedImage',
                              blank=True,
                              null=True,
                              verbose_name=_('image'))
    cover = models.ForeignKey('uploads.UploadedImage',
                              blank=True,
                              null=True,
                              related_name="+",
                              verbose_name=_('cover'))
    causes = models.ManyToManyField('core.Cause',
                                    verbose_name=_('causes'),
                                    blank=True)
    members = models.ManyToManyField('users.User',
                                     verbose_name=_('members'),
                                     related_name="organizations_member",
                                     blank=True)
    galleries = models.ManyToManyField('gallery.Gallery',
                                       verbose_name=_('galleries'),
                                       related_name="galleries",
                                       blank=True)

    # Fields
    categories = models.ManyToManyField('projects.Category',
                                        verbose_name=_('categories'),
                                        blank=True)
    slug = models.SlugField(_('Slug'),
                            max_length=100,
                            unique=True,
                            blank=True,
                            null=True)
    name = models.CharField(_('Name'), max_length=300)
    website = models.URLField(_('Website'),
                              blank=True,
                              null=True,
                              default=None)
    facebook_page = models.CharField(_('Facebook'),
                                     max_length=255,
                                     blank=True,
                                     null=True,
                                     default=None)
    type = models.PositiveSmallIntegerField(_('Type'),
                                            choices=ORGANIZATION_TYPES,
                                            default=0)
    details = models.TextField(_('Details'),
                               max_length=3000,
                               blank=True,
                               null=True,
                               default=None)
    description = models.CharField(_('Short description'),
                                   max_length=320,
                                   blank=True,
                                   null=True)
    hidden_address = models.BooleanField(_('Hidden address'), default=False)
    verified = models.BooleanField(_('Verified'), default=False)
    document = models.CharField(_('CNPJ'),
                                unique=True,
                                max_length=100,
                                validators=[validate_CNPJ],
                                blank=True,
                                null=True)
    benefited_people = models.IntegerField(blank=True, null=True, default=0)

    # Organization contact
    contact_name = models.CharField(_('Responsible name'),
                                    max_length=150,
                                    blank=True,
                                    null=True)
    contact_email = models.EmailField(_('Responsible email'),
                                      max_length=150,
                                      blank=True,
                                      null=True)
    contact_phone = models.CharField(_('Responsible phone'),
                                     max_length=150,
                                     blank=True,
                                     null=True)

    # Meta
    highlighted = models.BooleanField(_('Highlighted'),
                                      default=False,
                                      blank=False)
    published = models.BooleanField(_('Published'), default=False)
    published_date = models.DateTimeField(_('Published date'),
                                          blank=True,
                                          null=True)
    deleted = models.BooleanField(_('Deleted'), default=False)
    deleted_date = models.DateTimeField(_('Deleted date'),
                                        blank=True,
                                        null=True)
    created_date = models.DateTimeField(_('Created date'), auto_now_add=True)
    modified_date = models.DateTimeField(_('Modified date'), auto_now=True)
    is_inactive = models.BooleanField(_('Inactive'),
                                      default=False,
                                      blank=False)
    reminder_sent = models.BooleanField(_('Reminder'),
                                        default=False,
                                        blank=False)
    reminder_sent_date = models.DateTimeField(_('Reminder sent date'),
                                              blank=True,
                                              null=True)

    @staticmethod
    def autocomplete_search_fields():
        return 'name',

    def __init__(self, *args, **kwargs):
        super(Organization, self).__init__(*args, **kwargs)
        self.__orig_deleted = self.deleted
        self.__orig_published = self.published

    def __str__(self):
        return self.name

    def delete(self, *args, **kwargs):
        self.deleted = True
        self.published = False
        self.save()

    def mailing(self):
        return OrganizationMail(self)

    def admin_mailing(self):
        return OrganizationAdminMail(self)

    def save(self, *args, **kwargs):
        creating = False
        force_update = True

        if self.pk is not None:
            if not self.__orig_published and self.published:
                self.published_date = timezone.now()
                self.mailing().sendOrganizationPublished(
                    {"organization": self})

            if not self.__orig_deleted and self.deleted:
                self.deleted_date = timezone.now()
        else:
            # Organization being created
            self.slug = generate_slug(Organization, self.name)
            creating = True

        self.document = format_CNPJ(self.document)

        # If there is no description, take 100 chars from the details
        if not self.description and self.details:
            if len(self.details) > 100:
                self.description = self.details[0:100]
            else:
                self.description = self.details

        obj = super(Organization, self).save(*args, **kwargs)

        if creating:
            self.mailing().sendOrganizationCreated({"organization": self})
            try:
                self.admin_mailing().sendOrganizationCreated(
                    {"organization": self})
            except:
                pass

        return obj

    def is_bookmarked(self, user):
        return self.bookmarks.filter(user=user).count() > 0

    class Meta:
        app_label = 'organizations'
        verbose_name = _('organization')
        verbose_name_plural = _('organizations')
class Project(ChannelRelationship, RatedModelMixin):
  """
  Project model
  """
  image = models.ForeignKey('uploads.UploadedImage', blank=True, null=True, verbose_name=_('image'))
  address = models.ForeignKey(get_address_model(), blank=True, null=True, verbose_name=_('address'), db_constraint=False)
  skills = models.ManyToManyField('core.Skill', verbose_name=_('skills'))
  causes = models.ManyToManyField('core.Cause', verbose_name=_('causes'))
  galleries = models.ManyToManyField('gallery.Gallery', verbose_name=_('galleries'), blank=True)
  posts = models.ManyToManyField('core.Post', verbose_name=_('posts'), blank=True)
  documents = models.ManyToManyField('uploads.UploadedDocument', verbose_name=_('documents'), blank=True)

  # Relationships
  categories = models.ManyToManyField('projects.Category', verbose_name=_('categories'), blank=True)
  owner = models.ForeignKey('users.User', verbose_name=_('owner'))
  organization = models.ForeignKey('organizations.Organization', blank=True, null=True, verbose_name=_('organization'))
  item = models.ForeignKey('items.Item', blank=True, null=True, verbose_name=_('item'))
  rating_requests = GenericRelation(RatingRequest, related_query_name='rated_object_project')


  # Fields
  name = models.CharField(_('Project name'), max_length=100)
  slug = models.SlugField(max_length=100, blank=True, null=True, unique=True)
  published = models.BooleanField(_("Published"), default=False)
  highlighted = models.BooleanField(_("Highlighted"), default=False, blank=False)
  applied_count = models.IntegerField(_('Applied count'), blank=False, null=False, default=0)
  max_applies = models.IntegerField(blank=False, null=False, default=1) #note: This is not a hard limit, or is it?
  max_applies_from_roles = models.IntegerField(blank=False, null=False, default=0) # This is not a hard limit, just an estimate based on roles vacancies
  public_project = models.BooleanField(_("Public"), default=True, blank=False)
  minimum_age = models.IntegerField(_("Minimum Age"), blank=False, null=False, default=0)
  hidden_address = models.BooleanField(_('Hidden address'), default=False)
  crowdfunding = models.BooleanField(_('Crowdfunding'), default=False)
  skip_address_filter = models.BooleanField(_('Skip address filter'), default=False)
  type = models.FloatField(_('Project Type'), choices=types, default=1, max_length=10)

  benefited_people = models.IntegerField(blank=True, null=True, default=0)
  partnership = models.BooleanField(_('Partnership'), default=False)
  chat_enabled = models.BooleanField(_('Chat Enabled'), default=False)
  canceled = models.BooleanField(_("Canceled"), default=False)
  testimony = models.TextField(_('testimony'), max_length=3000, blank=True, null=True)


  # Date fields
  published_date = models.DateTimeField(_("Published date"), blank=True, null=True)
  closed = models.BooleanField(_("Closed"), default=False)
  closed_date = models.DateTimeField(_("Closed date"), blank=True, null=True)
  canceled_date = models.DateTimeField(_("Canceled date"), blank=True, null=True)
  deleted = models.BooleanField(_("Deleted"), default=False)
  deleted_date = models.DateTimeField(_("Deleted date"), blank=True, null=True)
  created_date = models.DateTimeField(_('Created date'), auto_now_add=True)
  modified_date = models.DateTimeField(_('Modified date'), auto_now=True)

  # About
  details = models.TextField(_('Details'), max_length=3000)
  description = models.TextField(_('Short description'), max_length=160, blank=True, null=True)

  """
  Set this property to use in haystack template
  """
  @property
  def roles_title(self):
    return [role.name for role in self.roles.all()]

  def mailing(self, async_mail=None):
    return emails.ProjectMail(self, async_mail)

  def admin_mailing(self, async_mail=None):
    return emails.ProjectAdminMail(self, async_mail)

  '''
  Data methods
  '''
  def get_phone(self):
    return self.owner.phone

  def get_email(self):
    return self.owner.email

  def get_volunteers_numbers(self):
    return Apply.objects.filter(project=self, status__in=["applied", "confirmed-volunteer"]).count()

  def is_bookmarked(self, user):
    return self.bookmarks.filter(user=user).count() > 0

  def bookmark_count(self):
    return self.bookmarks.count()

  '''
  Model operation methods
  '''
  def delete(self, *args, **kwargs):
    self.deleted = True
    self.published = False
    self.save()

  def save(self, *args, **kwargs):
    creating = False

    if self.pk is not None:
      orig = Project.objects.get(pk=self.pk)
      if not orig.published and self.published:
        try:
          self.published_date = timezone.now()
          self.mailing().sendProjectPublished({'project': self})
        except:
          pass

      if not orig.closed and self.closed:
        try:
          self.closed_date = timezone.now()
          self.mailing().sendProjectClosed({'project': self})
        except:
          pass

      if not orig.canceled and self.canceled:
        self.closed_date = timezone.now()

      if not orig.deleted and self.deleted:
        self.deleted_date = timezone.now()
    else:
      # Project being created
      self.slug = generate_slug(Project, self.name)
      creating = True

    # If there is no description, take 100 chars from the details
    if not self.description:
      if len(self.details) > 100:
        self.description = self.details[0:100]
      else:
        self.description = self.details

    self.modified_date = timezone.now()

    obj = super(Project, self).save(*args, **kwargs)

    if creating:
      self.mailing().sendProjectCreated({'project': self})
      try:
        self.admin_mailing().sendProjectCreated({'project': self})
      except:
        pass

    return obj

  def active_apply_set(self):
    return self.apply_set.filter(status__in=["applied", "confirmed-volunteer"])

  def __str__(self):
      return  '%s' % (self.name)

  class Meta:
    app_label = 'projects'
    verbose_name = _('project')
    verbose_name_plural = _('projects')
Example #6
0
 def test_default_model(self):
   """Assert GoogleAddress is the default address model"""
   model = get_address_model()
   self.assertTrue(model == GoogleAddress)
Example #7
0
 def test_setting(self):
   """Assert it's possible to modify the model by changing the setting"""
   model = get_address_model()
   self.assertTrue(model == SimpleAddress)