Beispiel #1
0
class IdeaImage(models.Model):
    def get_image_path(instance, filename):
        fsplit = filename.split('.')
        extra = 1
        test_path = os.path.join(
            settings.MEDIA_ROOT, 'idea_images', str(instance.idea_id),
            fsplit[0] + '_' + str(extra) + '.' + fsplit[1])
        while os.path.exists(test_path):
            extra += 1
            test_path = os.path.join(
                settings.MEDIA_ROOT, 'idea_images', str(instance.idea_id),
                fsplit[0] + '_' + str(extra) + '.' + fsplit[1])
        path = os.path.join('idea_images', str(instance.idea_id),
                            fsplit[0] + '_' + str(extra) + '.' + fsplit[-1])
        return path

    idea = models.ForeignKey(Idea)
    image = ImageWithThumbnailsField(
        upload_to=get_image_path,
        thumbnail={'size': (300, 300)},
        help_text=
        "The site will resize this master image as necessary for page display")
    title = models.CharField(max_length=255, help_text="For image alt tags")
    source = models.CharField(
        max_length=255,
        help_text="Source location or person who created the image")
    source_url = models.CharField(max_length=255, blank=True)
    home_page = models.BooleanField(
        default=False, help_text="Select this image for use on the home page.")

    def __unicode__(self):
        return '%s' % (self.image)
Beispiel #2
0
class Interview(WithPublished, WithSite):
    """ Intreview class inherited from WithPusblished """

    title = models.CharField(_('title'), max_length=250)
    image = ImageWithThumbnailsField(upload_to=gen_file_name,
                                     thumbnail={
                                         'size': (272, 128),
                                         'options': {
                                             'crop': ',10'
                                         },
                                         'quality': (100),
                                         'subdir': '_thumb'
                                     },
                                     verbose_name=_('image'),
                                     blank=True,
                                     null=True)
    full_text = tinymce_models.HTMLField(_('full text'))

    objects = InterviewManager()

    class Meta:
        verbose_name = _('Interview')
        verbose_name_plural = _('Interviews')

    def __unicode__(self):
        return self.title

    @models.permalink
    def get_absolute_url(self):
        """Returns absolute url
        for interview by id
        """
        return 'interview_detail', {}, {"interview_id": self.pk}
Beispiel #3
0
class NotebookProcessorLineFamily(models.Model):
    name = models.CharField(max_length = 255)
    brand = models.ForeignKey(NotebookProcessorBrand)
    text = models.TextField()
    
    picture = ImageWithThumbnailsField(
        thumbnail = { 'size': (300, 300), },             
        upload_to = 'processor_line',
        generate_on_save = True,)
        
    def raw_text(self):
        result = self.brand.raw_text()
        if self.id == 1:
            result += ' netbook'
        if self.id in [2, 11]:
            result += ' subnetbook ultraportatil'
        return result
    
    def __unicode__(self):
        return unicode(self.brand) + ' ' + self.name
    
    class Meta:
        app_label = 'cotizador'
        verbose_name = 'Notebook processor line family'
        ordering = ['brand', 'name']
Beispiel #4
0
class Post(models.Model):
    """Post model."""
    STATUS_CHOICES = (
        (1, _('Draft')),
        (2, _('Public')),
    )
    thumb = ImageWithThumbnailsField(upload_to='blogposts',
                                     thumbnail={
                                         'size': (200, 200),
                                         'options': ('crop', )
                                     },
                                     blank=True,
                                     null=True,
                                     help_text=_('Thumbnail'))
    title = models.CharField(_('title'), max_length=200)
    slug = models.SlugField(_('slug'), unique_for_date='publish')
    author = models.ForeignKey(User, blank=True, null=True)
    body = models.TextField(_('body'), )
    tease = models.TextField(
        _('tease'),
        blank=True,
        help_text=_('Concise text suggested. Does not appear in RSS feed.'))
    status = models.IntegerField(_('status'),
                                 choices=STATUS_CHOICES,
                                 default=2)
    allow_comments = models.BooleanField(_('allow comments'),
                                         default=False,
                                         editable=False)
    publish = models.DateTimeField(_('publish'), default=datetime.datetime.now)
    created = models.DateTimeField(_('created'), auto_now_add=True)
    modified = models.DateTimeField(_('modified'), auto_now=True)
    categories = models.ManyToManyField(Category, blank=True)
    tags = TagField()
    objects = PublicManager()

    class Meta:
        verbose_name = _('post')
        verbose_name_plural = _('posts')
        db_table = 'blog_posts'
        ordering = ('-publish', )
        get_latest_by = 'publish'

    def __unicode__(self):
        return u'%s' % self.title

    @permalink
    def get_absolute_url(self):
        return ('blog_detail', None, {
            'year': self.publish.year,
            'month': self.publish.strftime('%b').lower(),
            'day': self.publish.day,
            'slug': self.slug
        })

    def get_previous_post(self):
        return self.get_previous_by_publish(status__gte=2)

    def get_next_post(self):
        return self.get_next_by_publish(status__gte=2)
Beispiel #5
0
class Layer(models.Model):
    cmap = models.ForeignKey(CareerMap)
    name = models.CharField(max_length=256, default="")
    color = models.CharField(max_length=16, default="#ff0000")

    def __unicode__(self):
        return self.name or "Layer ID %d" % self.id

    def dir(self):
        return dir(self)

    #The columns of stats that need to be shown when this layer is selected:
    county_stat_types = models.ManyToManyField('CountyStatType', blank=True)

    image = ImageWithThumbnailsField(
        upload_to="images/careermapblock/layers/%Y/%m/%d",
        thumbnail={'size': (65, 65)},
        extra_thumbnails={
            'admin': {
                'size': (70, 50),
                'options': ('sharpen', ),
            }
        })

    class Meta:
        order_with_respect_to = 'cmap'

    def save_image(self, f):
        ext = f.name.split(".")[-1].lower()
        basename = slugify(f.name.split(".")[-2].lower())[:20]
        if ext not in ['jpg', 'jpeg', 'gif', 'png']:
            # unsupported image format
            return None
        now = datetime.now()
        path = "images/careermapblock/layers/%04d/%02d/%02d/" % (
            now.year, now.month, now.day)
        try:
            os.makedirs(settings.MEDIA_ROOT + "/" + path)
        except:
            pass
        full_filename = path + "%s.%s" % (basename, ext)
        fd = open(settings.MEDIA_ROOT + "/" + full_filename, 'wb')
        for chunk in f.chunks():
            fd.write(chunk)
        fd.close()
        self.image = full_filename
        self.save()

    def edit_form(self, request=None, files=None):
        the_form = LayerForm(request, files, instance=self)
        the_form.fields['name'] = forms.CharField(initial=self.name)
        the_form.fields['image'] = forms.FileField(label="replace image")
        the_form.fields['county_stat_types'] = forms.ModelMultipleChoiceField(
            queryset=CountyStatType.objects.all(),
            initial=[
                c.pk for c in CountyStatType.objects.all()
                if c in self.county_stat_types.all()
            ])
        return the_form
Beispiel #6
0
class TempGallery(models.Model):
    gallery = models.ForeignKey(PlaceGallery,
                        related_name='temps')
    image = ImageWithThumbnailsField(upload_to=gen_file_name,
                        thumbnail={'size': (150, 150), 'subdir': '_thumb'},
                        verbose_name=_('photo'),
                        blank=True, null=True)
    time = models.DateTimeField(auto_now=True)
Beispiel #7
0
class Profile(models.Model):
    user = AutoOneToOneField(User, primary_key=True, related_name="profile")
    userpic = ImageWithThumbnailsField(upload_to=gen_file_name,\
        thumbnail={'size': (120, 120), 'options': {'crop':'center'}, 'quality': (100), 'subdir': 'large'}, \
        extra_thumbnails = {
            'medium': {'size': (60, 60), 'options': {'crop':',0'}, 'quality': (100), 'subdir': 'medium'},
            'small': {'size': (24, 24), 'options': {'crop':',10'}, 'quality': (100), 'subdir': 'small'},
        },\
        null=True, blank=True)
    sex = models.CharField(max_length=6, choices=SEX_CHOICES, default='none')
    birthday = models.DateField(null=True, blank=True)
    country = models.CharField(max_length=50, null=True, blank=True)
    city = models.CharField(max_length=50, null=True, blank=True)
    web_site = models.URLField(verify_exists=False, null=True, blank=True)
    icq = models.CharField(max_length=15, null=True, blank=True)
    profession = models.TextField(null=True, blank=True)
    company = models.TextField(null=True, blank=True)
    address = models.TextField(null=True, blank=True)
    phone_number = models.CharField(max_length=50, null=True, blank=True)
    interest = models.TextField(null=True, blank=True)
    about = models.TextField(null=True, blank=True)
    access_to_dasboard = models.BooleanField(default=False)
    subscription_accepted = models.BooleanField(default=True)
    subscribed = models.BooleanField(default=False)

    """
    class Meta:
        permissions = (('dashboard_access'),_('Can login to control panel'))
    """ #TODO: Discuss this

    def __unicode__(self):
        if self.user.first_name and self.user.last_name:
            return u"%s %s" % (self.user.first_name, self.user.last_name)

        if self.user.first_name:
            return self.user.first_name

        if self.user.last_name:
            return self.user.last_name

        return self.user.username

    def get_absolute_url(self):
        return reverse('profile_show', args=[self.user.id])

    def can_edit(self, user):
        return self.user == user

    def get_userpic(self):
        if os.path.isfile(self.userpic.path):
            return "/media/%s" % self.userpic
        return "/static/i/no_avatar.png"

    @property
    def filled(self):
        return True
Beispiel #8
0
class Party(Organisation):
    """A political party in a unit, as used in the template representative/unit.html"""
    #: acronym of this party
    acronym = models.CharField(max_length=16, blank=False, null=False,
                               help_text=_('Acronym of this Party'))
    #: url of this representative
    url = models.TextField(blank=True, help_text=_('URL of this Party'))
    #: party logo
    logo = ImageWithThumbnailsField(upload_to='parties',
                                    thumbnail={'size': (100, 84), 'options': ('crop',)},
                                    blank=True, null=True, help_text=_('Party logo'))
Beispiel #9
0
class PlaceGallery(models.Model):
    place = models.ForeignKey(Place,
                    related_name='gallery',
                    verbose_name=_(u'place'))
    image = ImageWithThumbnailsField(verbose_name=_(u'photo'),
                    upload_to=gen_file_name,
                    thumbnail={u'size': (300, 300), u'subdir': u'_thumb'},
                    blank=True, null=True)
    title = models.CharField(_(u'title'),
                    max_length=300,
                    blank=True, null=True)
    order = models.IntegerField(verbose_name=_('order'))

    objects = GalleryManager()

    class Meta:
        verbose_name_plural = _(u'Place galleries')

    def __unicode__(self):
        return u"%s %s" % (self.place.name, self.order)
Beispiel #10
0
class ProductPicture(models.Model):
    picture = ImageWithThumbnailsField(
        thumbnail={
            'size': (90, 90),
        },
        extra_thumbnails={
            'large': {
                'size': (300, 300)
            },
        },
        upload_to='.',
        generate_on_save=True,
    )
    notebook = models.ForeignKey(Product)

    def __unicode__(self):
        return 'Foto de ' + unicode(self.notebook)

    class Meta:
        app_label = 'cotizador'
        verbose_name = 'Notebook picture'
Beispiel #11
0
class Store(models.Model):
    name = models.CharField(max_length = 255)
    classname = models.CharField(max_length = 255)
    url = models.URLField()
    sponsor_cap = models.IntegerField(default = 0)
    picture = ImageWithThumbnailsField(
        thumbnail = { 'size': (140, 90), },                                          
        upload_to = 'store_logos',
        generate_on_save = True,)
    affiliate_id = models.CharField(max_length=255, blank=True, null=True)
    
    def fetch_store(self):
        from solonotebooks.fetch_scripts import *
        return eval(self.classname + '()')
    
    def __unicode__(self):
        return unicode(self.name)
        
    def fetch_product_data(self, url):
        from . import StoreHasProductEntity
        from solonotebooks.fetch_scripts import *
        fetch_store = self.fetch_store()
        product = fetch_store.retrieve_product_data(url)
        if not product:
            return None
        else:
            shpes = StoreHasProductEntity.objects.filter(custom_name = product.custom_name, store = self)
            if shpes:
                return shpes[0]
            else:
                return None
        
    def save_product(self, product):
        from . import StoreHasProductEntity, LogNewEntity, ProductType
        print 'Guardando ' + str(product)
        print 'Buscando si tiene un registro existente'
        try:
            shpe = StoreHasProductEntity.objects.get(comparison_field = product.comparison_field)
            print 'Si tiene registro existente, usandolo'
        except StoreHasProductEntity.DoesNotExist:
            print 'No tiene registro existente, creandolo'
            shpe = StoreHasProductEntity()
            shpe.url = product.url
            shpe.custom_name = product.custom_name
            shpe.comparison_field = product.comparison_field
            shpe.shp = None
            shpe.is_available = True
            shpe.is_hidden = False
            shpe.latest_price = product.price
            shpe.store = self
            try:
                ptype = ProductType.objects.get(classname = product.ptype)
                shpe.ptype = ptype
            except:
                pass
            shpe.save()
            LogNewEntity.new(shpe).save()
            
        shpe.update_with_product(product)
        
    def update_products_from_webpage(self, update_shpes_on_finish = False):
        from . import LogFetchStoreError
        fetch_store = self.fetch_store()
        fetch_log_file_location = os.path.join(settings.LOG_DIRECTORY, fetch_store.__class__.__name__ + '_fetch.txt')
        logger = Logger(sys.stdout, fetch_log_file_location)
        sys.stdout = logger
        
        try:
            store = Store.objects.get(name = fetch_store.name)
        except Store.DoesNotExist:
            store = Store()
            store.name = fetch_store.name
            store.save()
            
        store.set_shpe_prevent_availability_change_flag(False)
            
        try:
            if update_shpes_on_finish:
                for shpe in store.storehasproductentity_set.all():
                    shpe.delete_today_history()
            
            products = fetch_store.get_products()        
            
            update_log_file_location = os.path.join(settings.LOG_DIRECTORY, fetch_store.__class__.__name__ + '_update.txt')
            print update_log_file_location
            logger.change_log_file(update_log_file_location)
            for product in products:
                self.save_product(product)
            
            if update_shpes_on_finish:
                from . import ProductVisit
                product_visits = ProductVisit.get_last_day_visitor_count_for_each_product()

                for shpe in store.storehasproductentity_set.all():
                    shpe.update(recursive=True, product_visits=product_visits)

            try:                
                log_error = LogFetchStoreError.objects.get(log_entry__date = date.today(), store = store)
                log_error.delete()
            except LogFetchStoreError.DoesNotExist, e:
                pass
                
        except Exception, e:
            traceback.print_exc(file=sys.stdout)
            print e
            print('Error al obtener los productos de ' + store.name)
            
            try:                
                log_error = LogFetchStoreError.objects.get(log_entry__date = date.today(), store = store)
            except LogFetchStoreError.DoesNotExist, ex:
                LogFetchStoreError.new(store, str(e))
            
            store.set_shpe_prevent_availability_change_flag(True)
Beispiel #12
0
class TestThumbnailFieldExtensionModel(models.Model):
    photo = ImageWithThumbnailsField(upload_to='test',
                                     thumbnail=extension_thumbnail,
                                     extra_thumbnails=extra_thumbnails)
Beispiel #13
0
class Representative(Person):
    """A representative derived from popit.Person."""
    #: personal photo
    photo = ImageWithThumbnailsField(upload_to='representatives',
                                     thumbnail={
                                         'size': (200, 168),
                                         'options': ('crop', )
                                     },
                                     blank=True,
                                     null=True,
                                     help_text=_('Personal Photo'))
    #: party membership
    party = models.ForeignKey(Party,
                              related_name='representatives',
                              blank=True,
                              null=True,
                              help_text=_('Party Membership'))
    #: unit membership
    unit = models.ForeignKey(Unit,
                             related_name='representatives',
                             blank=True,
                             null=True,
                             help_text=_('Unit Membership'))
    #: committee membership
    committee = models.TextField(blank=True,
                                 null=True,
                                 help_text=_('Committee Membership'))
    #: faction membership
    faction = models.ForeignKey(Faction,
                                related_name='representatives',
                                blank=True,
                                null=True,
                                help_text=_('Faction membership'))

    #: is majoritarian?
    is_majoritarian = models.BooleanField(blank=True,
                                          default=False,
                                          help_text=_('Is Majoritarian?'))
    #: electoral district
    electoral_district = models.TextField(
        blank=True,
        null=True,
        help_text=_('Electoral District (if Majoritarian)'))
    #: date elected
    elected = models.TextField(blank=True,
                               null=True,
                               help_text=_('Date Elected'))
    #: place of birth
    pob = models.TextField(blank=True,
                           null=True,
                           help_text=_('Place of Birth'))
    #: family status
    family_status = models.TextField(blank=True,
                                     null=True,
                                     help_text=_('Family Status'))
    #: education
    education = models.TextField(blank=True,
                                 null=True,
                                 help_text=_('Education'))
    #: contact, address and phone number
    contact_address_phone = models.TextField(
        blank=True, null=True, help_text=_('Contact Address / Phone Number'))
    #: salary
    salary = models.FloatField(default=0,
                               blank=True,
                               null=True,
                               help_text=_('== Wages'))
    #: other income
    other_income = models.FloatField(default=0,
                                     blank=True,
                                     null=True,
                                     help_text=_('== Entrepreneurial Income'))
    #: expenses
    expenses = models.TextField(blank=True, null=True, help_text=_('Expenses'))
    #: property & assets
    property_assets = models.TextField(blank=True,
                                       null=True,
                                       help_text=_('Property & Assets'))
    #: percentage of questions answered on shenmartav.ge
    answered = models.FloatField(
        default=0,
        blank=True,
        null=True,
        help_text=_('Percentage of Answered Questions on chemiparlamenti.ge'))
    #: gender of the representative
    gender = models.IntegerField(default=0,
                                 choices=GENDER_CHOICES,
                                 blank=True,
                                 null=True,
                                 help_text=_('Gender of the Representative'))
    #: terms of the representative
    terms = models.ManyToManyField(
        Term,
        blank=True,
        null=True,
        related_name='representatives',
        help_text=_('Terms during which Representative was part of a Unit.'))
    #: asset declaration id submitted by representative
    declaration_id = models.IntegerField(default=0,
                                         blank=True,
                                         null=True,
                                         help_text=_('Asset Declaration Id'))
    #: submission date - asset declaration
    submission_date = models.DateField(
        blank=True,
        null=True,
        help_text=_('Asset Declaration submission date'))
    #: Representative's entrepreneurial salary
    entrepreneurial_salary = models.FloatField(
        default=0,
        blank=True,
        null=True,
        help_text=_('Representative entrepreneurial salary'))
    #: Representative's work income
    main_salary = models.FloatField(default=0,
                                    blank=True,
                                    null=True,
                                    help_text=_('Representative income'))

    #: managers
    objects = models.Manager()
    parliament = ParliamentManager()
    tbilisi = TbilisiManager()
    ajara = AjaraManager()

    @classmethod
    def _filter_name(cls, name):
        """
        Filter out multiple names in provided name. For example: "Giorgi (gia) Giorgadze" will be converted to
        "Giorgi Giorgadze"
        @param name: Representative name with possible multiple names
        @return: Filtered out representative name with only one name
        """
        name_dict = name.split()
        full_name = ""

        for name in name_dict:
            if "(" not in name:
                full_name += ' ' + name

        return full_name.strip()

    @classmethod
    def _find_firstname_first(cls, name):
        """Find a representative with given name firstname first.

        @param name: name of the representative
        @type name: str
        @return: representative matching the name
        @rtype: representative.Representative
        """
        firstname_first = glt.firstname_first(name)

        # Find rep whose name starts with Firstname and ends with lastname.
        # This is good for people whose name contains different letters in the end or missing "i" etc.
        representative = cls.objects.filter(
            Q(names__name_ka__startswith=firstname_first.split()[0])
            &  # firstname
            Q(names__name_ka__endswith=firstname_first.split()[-1])
            |  # lastname
            Q(names__name_en__startswith=firstname_first.split()[0])
            & Q(names__name_en__endswith=firstname_first.split()[-1])
            | Q(names__name__icontains=firstname_first))

        try:
            return representative[0]
        except IndexError:
            return None

    @classmethod
    def _find_lastname_first(cls, name):
        """Find a representative with given name lastname first.

        @param name: name of the representative
        @type name: str
        @return: representative matching the name
        @rtype: representative.Representative
        """

        lastname_first = glt.lastname_first(name)

        # Find rep whose name starts with Firstname and ends with lastname.
        # This is good for people whose name contains different letters in the end or missing "i" etc.
        representative = cls.objects.filter(
            Q(names__name_ka__startswith=lastname_first.split()[0])
            &  # lastname
            Q(names__name_ka__endswith=lastname_first.split()[1])
            |  # firstname
            Q(names__name_en__startswith=lastname_first.split()[0])
            & Q(names__name_en__endswith=lastname_first.split()[1])
            | Q(names__name__icontains=lastname_first))

        try:
            return representative[0]
        except IndexError:
            return None

    @classmethod
    def _find_startswith(cls, start):
        """Find a representative whose name starts with given start.

        @param start: first charactes of representative's name
        @type start: str
        @return: representative whose name starts with given start
        @rtype: representative.Representative
        """
        if len(start) < NAME_MINLEN:
            return None

        startswith = start[:NAME_MINLEN]
        representative = cls.objects.filter(
            Q(names__name_ka__istartswith=startswith)
            | Q(names__name_en__istartswith=startswith)
            | Q(names__name__istartswith=startswith))

        try:
            return representative[0]
        except IndexError:
            return None

    @classmethod
    def find(cls, name, first=None):
        """Find a representative with given name.

        @param name: name of the representative
        @type name: unicode
        @param first: Set to 'lastname' if first word in input name is lastname and 'firstname' if it's firstname
        @type first: str
        @return: representative matching the name
        @rtype: representative.Representative
        """
        name = cls._filter_name(name)

        if len(name) < NAME_MINLEN:
            representative = None

        elif first == 'lastname':
            representative = cls._find_firstname_first(name)

        elif first == 'firstname':
            representative = cls._find_lastname_first(name)

        else:
            representative = cls._find_lastname_first(name)
            if representative is None:
                representative = cls._find_firstname_first(name)

        if representative:
            return representative
        else:
            representative = cls.objects.filter(
                Q(names__name_ka__icontains=name)
                | Q(names__name_en__icontains=name)
                | Q(names__name__icontains=name))
            if representative:
                return representative
            else:
                return None

    @classmethod
    def by_lastname_firstname_first(cls, representatives=None):
        """Sort given representatives by lastname and show firstname first.

        @param representatives: queryset of representatives to sort, using all() if None
        @type representatives: QuerySet
        @return: sorted list by lastname, including 'firstname_first'
        @rtype: [{
            'pk': int, 'slug': str, 'party__acronym': str,
            'is_majoritarian': bool, 'photo': str,
            'names__name': str, 'names__name_$lang': str,
            'firstname_first': str
        }]
        """
        if representatives is None:
            representatives = cls.objects.all()

        by_lastname = []
        # losing language abstraction, gaining massive reduction in db queries
        name_lang = 'names__name_' + get_language()[:2]
        reps = representatives.values('pk', 'slug', 'party__acronym',
                                      'faction__short', 'is_majoritarian',
                                      'photo', 'names__name', name_lang)
        for r in reps:
            try:
                lastname = r[name_lang].split()[-1]
                r['firstname_first'] = r[name_lang]
            except AttributeError:
                lastname = r['names__name'].split()[-1]
                r['firstname_first'] = r['names__name']
            by_lastname.append((lastname, r))

        return [p[1] for p in sorted(by_lastname, key=itemgetter(0))]
        #return [by_lastname[key] for key in sorted(by_lastname.keys())]

    @classmethod
    def by_lastname_lastname_first(cls, representatives=None, choices=False):
        """Sort given representatives by lastname and show lastname first.

        @param representatives: queryset of representatives to sort, using all() if None
        @type representatives: QuerySet
        @param choices: if list suitable for form choices should be returned
        @type choices: bool
        @return: sorted list by lastname, including 'lastname_first'
        @rtype: [{
            'pk': int, 'slug': str,
            'names_name': str, 'names__name_$lang': str,
            'lastname_first': str
        }]

        """
        if representatives is None:
            representatives = cls.objects.all()

        by_lastname = []
        # losing language abstraction, gaining massive reduction in db queries
        name_lang = 'names__name_' + get_language()[:2]
        reps = representatives.values('pk', 'slug', 'names__name', name_lang)
        for r in reps:
            try:
                splitname = r[name_lang].split()
            except AttributeError:
                splitname = r['names__name'].split()
            lastname = splitname.pop()
            r['lastname_first'] = lastname + ' ' + ' '.join(splitname)
            by_lastname.append((lastname, r))

        if choices:
            return [(p[1]['pk'], p[1]['lastname_first'])
                    for p in sorted(by_lastname, key=itemgetter(0))]
        else:
            return [p[1] for p in sorted(by_lastname, key=itemgetter(0))]

    @property
    def income(self):
        """
        Income of representative
        @return: Dictionary with income values
        @rtype: {
        'total' : int,
        'base' : int
        'entrepreneurial': int,
        'main': int,
        'incomeyear': int,
        'latestsubmissionyear': int,
        'declarationid': int
        }
        """
        #try:
        #    base = int(settings.BASE_INCOME[self.unit.short])
        #except (AttributeError, KeyError, ValueError):
        #    base = 0
        # New MPs haven't been in Parliament for more than one year,
        # so can't calculate their base salary accurately.
        base = 0
        try:
            mpincome = self.declarationtotalincome.all()[0]
        except IndexError:
            mpincome = 0

        main = self.main_salary
        entrepreneurial = self.entrepreneurial_salary

        incomeyear = 0
        submissionyear = 0
        if self.submission_date:
            incomeyear = self.submission_date.year
            submissionyear = self.submission_date.year

        declarationid = self.declaration_id

        return {
            'total': int(main + entrepreneurial),
            'base': base,
            'entrepreneurial': entrepreneurial,
            'main': main,
            'incomeyear': incomeyear,
            'latestsubmissionyear': submissionyear,
            'declarationid': declarationid,
        }

    @property
    def assets_list(self):
        """
        List of assets of representative
        @return: List with assets
        @rtype: list
        """
        if self.property_assets:
            return self.property_assets.split(';')
        return None

    def save(self, *args, **kwargs):
        """
        Update save method in order to enforce slug in default language
        @param args:
        @param kwargs:
        @return:
        """
        # enforce rewriting of slug in default language
        lang = get_language()
        activate(settings.LANGUAGE_CODE)
        self.slug = slugify(str(self.name))
        activate(lang)

        super(Representative, self).save(*args, **kwargs)
Beispiel #14
0
class Place(WithSite):
    category = models.ManyToManyField(PlaceCategory, null=True,
                blank=True, verbose_name=_('category'),
                #related_name='places')
                through='RateCategories')
    name = models.CharField(max_length=255, verbose_name=_('company name'))
    tagging = models.ManyToManyField(Tag, related_name='places', null=True,
                blank=True, verbose_name=_('tagging'))
    description = models.TextField(null=True, blank=True,
                verbose_name=_('description'))
    hits = models.IntegerField(default=0, verbose_name=_('hits'),)
    logotype = ImageWithThumbnailsField(upload_to=gen_file_name,
                thumbnail={'size': (360, 170), 'quality': (100), 'subdir': '_thumb'},
                null=True, blank=True, verbose_name=_('logo of company'))
    logotype_alt = models.CharField(blank=True, null=True,
                verbose_name=_('logotype_alt'), max_length=255)
    photo = ImageWithThumbnailsField(upload_to=gen_file_name,
                thumbnail={'size': (360, 170), 'options': {'crop':',10'}, 'quality': (100), 'subdir': '_thumb'},
                null=True, blank=True, verbose_name=_('photo'))
    photo_alt = models.CharField(blank=True, null=True,
                verbose_name=_('photo_alt'), max_length=255)
    email = models.CharField(max_length=255,
                null=True, blank=True,
                verbose_name=_('email of company'))
    url = models.URLField(verify_exists=False, null=True, blank=True,
                verbose_name=_('web site'))
    url_is_follow = models.BooleanField(_('follow url'), default=False)
    urlhits = models.IntegerField(default=0, verbose_name=_('urlhits'))
    promo_is_up = models.BooleanField(default=False,
                verbose_name=_('promo is published'))
    date_promo_up = models.DateField(null=True, blank=True,
                verbose_name=_('date of pulished promo'))
    date_promo_down = models.DateField(null=True, blank=True,
                verbose_name=_('date of unpublished promo'))
    is_published = models.BooleanField(default=False,
                verbose_name=_('company is published'))
    is_sponsor = models.BooleanField(default=False,
                verbose_name=_('company is the sponsor'))
    sponsor_logo = ImageWithThumbnailsField(upload_to=gen_file_name,
                thumbnail={'size': (200, 45), 'quality': (100), 'subdir': '_thumb'},
                null=True, blank=True, verbose_name=_("sponsor's logo"))
    expert_choice = models.BooleanField(default=False,
                verbose_name=_('expert`s choice'))
    main_address = models.TextField(editable=False,
                verbose_name=_('main address'),
                blank=True, null=True)
    num_comments = models.PositiveIntegerField(_('number of comments'),
                default=0)
    date_modified = models.DateTimeField(auto_now=True, default=datetime.now,
                verbose_name=_('date of change'))
    date_mark_as_new = models.DateTimeField(default=datetime.now,
                verbose_name=_('date of mark as new'), blank=True, null=True)
    priority = models.IntegerField(default=0, verbose_name=_('priority'),)
    kinohod_place_id = models.IntegerField(verbose_name=_('kinohod place id'),
                        default=0, blank=True, null=True)
    can_buy_tiket = models.BooleanField(default=False)
    manual_changed = models.BooleanField(default=True)
    payments = models.ManyToManyField(PaymentSystem, default=None, blank=True, null=True)
    flash3d = models.URLField(default=None, blank=True, null=True,
                verbose_name=_('panorama'))
    identity = models.CharField(max_length=255, default='', blank=True, null=True)
    last_foursquare_update = models.DateTimeField(null=True, blank=True)

    foursquare_show = models.BooleanField(verbose_name=_(u'show foursquare photos'),
                        default=True)

    score = models.FloatField(verbose_name=_(u'Score by votes'), default=0, editable=False)

    search = SphinxSearch(
        index='place_index',
        weights={
            'name': 100,
        },
        mode='SPH_MATCH_ALL',
        rankmode='SPH_RANK_NONE',
    )

    objects = PlaceManager()
    default_manager = models.Manager()

    def save(self, *args, **kwargs):
        self.main_address = self._main_address
        if 'site' in kwargs:
            site = kwargs.pop('site')
        else:
            site = None
        self.score = Vote.objects.get_score(self)['score']
        super(Place, self).save(*args, **kwargs)
        if not self.sites.exists():
            self.sites.add(site or Site.objects.get_current())

    class Meta:
        verbose_name = _('Place')
        verbose_name_plural = _('Places')
        ordering = ['name']

    def __unicode__(self):
        return self.name
        #return u"%s" % self.name

    @models.permalink
    def get_absolute_url(self):
        return ('place_show', [str(self.id)])

    @models.permalink
    def get_edit_url(self):
        return ("control_place_edit", [str(self.pk)])

    @property
    def _main_address(self):
        if self.address.count():
            try:
                address = self.address.filter(
                    is_main_office=True).all()[0].address
            except IndexError:
                address = self.address.all()[0].address
        else:
            address = None
        return address

    def get_main_address(self):
        if self.address.count():
            try:
                return self.address.filter(
                    is_main_office=True).all()[0]
            except IndexError:
                return self.address.all()[0]
        return None

    @property
    def is_taxi(self):
        if self.category.filter(name='Такси').exists():
            return True
        return False

    @property
    def phone(self):
        phones = [
            y.strip()
                for x in self.address.values('phone')
                    for y in x['phone'].split(',')
        ]
        if phones:
            return ', '.join(phones[:2] if len(phones) > 2 else phones)
        return None

    @property
    def has_email(self):
        return bool(self.email.strip())

    @property
    def get_url(self):
        url = self.url
        if url.endswith("/"):
            url = url[:-1]
        if "http://" in url:
            url = url.split('http://')[1]
            return url
        return url

    def dump(self):
        place_object = dict()
        for f in ['name', 'url', 'email']:
            place_object[f] = getattr(self, f, None)

        category = [{
            'id': c.id,
            'name': c.__unicode__(),
        } for c in self.category.all().order_by('name')]
        place_object['category'] = category

        tagging = [{
            'id': c.id,
            'name': c.__unicode__(),
        } for c in self.tagging.all().order_by('name')]
        place_object['tagging'] = tagging

        payments = [p.__unicode__() for p in  self.payments.filter(name__gt='')]
        if payments:
            place_object['payments'] = list(set(payments))
            place_object['payments'].sort()
        else:
            place_object['payments'] = None

        place_object['adr'] = list()
        for adr in self.address.all():
            adr_object = dict()
            adr_object['address'] = adr.address
            adr_object['phone'] = adr.phone
            adr_object['wt_list'] = [wt.dump() for wt in adr.work_time.all()]
            place_object['adr'].append(adr_object)
        return place_object

    def get_fs_photos(self, fsid):
        url = 'https://api.foursquare.com/v2/venues/%s/photos' % fsid
        data = get_json(url, FS_AUTH)
        present_photos = self.foursquare_photo.all().values_list('photo_id', flat=True)
        for k in data['response']['photos']['items']:
            if k['id'] not in present_photos:
                param = {
                    'place': self,
                    'photo_id': k['id'],
                    'prefix': k['prefix'],
                    'suffix': k['suffix'],
                }
                FoursquarePhoto(**param).save()
Beispiel #15
0
class ImagePullQuoteBlock(BasePageBlock):
    image = ImageWithThumbnailsField(
        upload_to="images/%Y/%m/%d",
        thumbnail={
            'size': (65, 65)
        },
        extra_thumbnails={
            'admin': {
                'size': (70, 50),
                'options': ('sharpen', ),
            }
        })
    caption = models.TextField(blank=True)
    alt = models.CharField(max_length=100, null=True, blank=True)

    template_file = "pageblocks/imagepullquoteblock.html"
    summary_template_file = "pageblocks/imagepullquoteblock_summary.html"
    display_name = "Image Pullquote"

    def edit_form(self):
        class EditForm(forms.Form):
            image = forms.FileField(label="replace image")
            caption = forms.CharField(initial=self.caption,
                                      required=False,
                                      widget=forms.widgets.Textarea())
            alt = forms.CharField(initial=self.alt, required=False)
        return EditForm()

    @classmethod
    def add_form(cls):
        class AddForm(forms.Form):
            image = forms.FileField(label="select image")
            caption = forms.CharField(widget=forms.widgets.Textarea(),
                                      required=False)
            alt = forms.CharField(required=False)
        return AddForm()

    @classmethod
    def create(cls, request):
        if 'image' in request.FILES:
            ib = cls.objects.create(
                caption=request.POST.get('caption', ''),
                image="",
                alt=request.POST.get('alt', ''))
            ib.save_image(request.FILES['image'])
            return ib
        else:
            return None

    @classmethod
    def create_from_dict(cls, d):
        # since it's coming from a dict, not a request
        # we assume that some other part is handling the writing of
        # the image file to disk and we just get a path to it
        return cls.objects.create(
            image=d.get('image', ''),
            alt=d.get('alt', ''),
            caption=d.get('caption', ''))

    def edit(self, vals, files):
        self.caption = vals.get('caption', '')
        self.alt = vals.get('alt', '')
        if 'image' in files:
            self.save_image(files['image'])
        self.save()

    def save_image(self, f):
        ext = f.name.split(".")[-1].lower()
        basename = slugify(f.name.split(".")[-2].lower())[:20]
        if ext not in ['jpg', 'jpeg', 'gif', 'png']:
            # unsupported image format
            return None
        now = datetime.now()
        path = "images/%04d/%02d/%02d/" % (now.year, now.month, now.day)
        try:
            os.makedirs(settings.MEDIA_ROOT + "/" + path)
        except OSError:
            pass
        full_filename = path + "%s.%s" % (basename, ext)
        fd = open(settings.MEDIA_ROOT + "/" + full_filename, 'wb')
        for chunk in f.chunks():
            fd.write(chunk)
        fd.close()
        self.image = full_filename
        self.save()

    def as_dict(self):
        return dict(image=self.image.name,
                    alt=self.alt,
                    caption=self.caption)

    def list_resources(self):
        return [self.image.url]
Beispiel #16
0
class TestThumbnailFieldGenerateModel(models.Model):
    photo = ImageWithThumbnailsField(upload_to='test',
                                     thumbnail=thumbnail,
                                     extra_thumbnails=extra_thumbnails,
                                     generate_on_save=True)
Beispiel #17
0
class TestThumbnailFieldModel(models.Model):
    avatar = ThumbnailField(upload_to='test', size=(300, 300))
    photo = ImageWithThumbnailsField(upload_to='test',
                                     thumbnail=thumbnail,
                                     extra_thumbnails=extra_thumbnails)