def display_coalition(request): party_list = list(Party.objects.all()) party_json = [] term = Term.objects.latest() gov_list = request.session.get('coalition_parties', None) if gov_list == None: # six-pack default DEFAULT_PARTIES = ('kok', 'sd', 'vas', 'kd', 'vihr', 'r') gov_list = [] for pn in DEFAULT_PARTIES: for p in party_list: if p.name == pn: gov_list.append(p) break for party in party_list: tn = DjangoThumbnail(party.logo, (38, 38)) d = {'id': party.name, 'name': party.full_name} d['logo'] = tn.absolute_url d['logo_dim'] = dict(x=tn.width(), y=tn.height()) mp_list = Member.objects.active_in_term(term) seats = mp_list.filter(party=party).count() d['nr_seats'] = seats for gp in gov_list: if party.pk == gp.pk: d['gov'] = True break else: d['gov'] = False party_json.append(d) q_models = Question.objects.filter(pk__in=stats_cache.questions) q_models = q_models.select_related('source') question_json = [] for idx, q in enumerate(q_models): name = '%s/%d' % (q.source.url_name, q.order) d = {'id': name, 'text': q.text} d['order'] = idx d['selected'] = True question_json.append(d) args = {'party_json': simplejson.dumps(party_json)} args['content'] = Item.objects.retrieve_content('coalition') args['question_json'] = simplejson.dumps(question_json) args['active_page'] = 'opinions' return render_to_response('opinions/coalition.html', args, context_instance=RequestContext(request))
def thumbnail(image_path, size=(50, 50), options=["crop"]): """ Поле в админке с уменьшенным изображением """ if image_path: try: thumbnail = DjangoThumbnail(image_path, size, options) except ValueError: return "" return '<img src="%s" width="%s" height="%s" />' % ( str(thumbnail.absolute_url), thumbnail.width(), thumbnail.height(), ) else: return ""
def _build_thumbnail(self, args): # Build kwargs kwargs = {} for k, v in args.items(): kwargs[ALL_ARGS[k]] = v # Return thumbnail relative_source_path = getattr(self.instance, self.field.name).name return DjangoThumbnail(relative_source_path, **kwargs)
def testAlternateExtension(self): basename = RELATIVE_PIC_NAME.replace('.', '_') # Control JPG thumb = DjangoThumbnail(relative_source=RELATIVE_PIC_NAME, requested_size=(240, 120)) expected = os.path.join(settings.MEDIA_ROOT, basename) expected += '_240x120_q85.jpg' expected_jpg = expected self.verify_thumbnail((160, 120), thumb, expected_filename=expected) # Test PNG thumb = DjangoThumbnail(relative_source=RELATIVE_PIC_NAME, requested_size=(240, 120), extension='png') expected = os.path.join(settings.MEDIA_ROOT, basename) expected += '_240x120_q85.png' self.verify_thumbnail((160, 120), thumb, expected_filename=expected) # Compare the file size to make sure it's not just saving as a JPG with # a different extension. self.assertNotEqual(os.path.getsize(expected_jpg), os.path.getsize(expected))
def testUnicodeName(self): unicode_name = 'sorl-thumbnail-ążśź_source.jpg' unicode_path = os.path.join(settings.MEDIA_ROOT, unicode_name) Image.new('RGB', PIC_SIZE).save(unicode_path) self.images_to_delete.add(unicode_path) thumb = DjangoThumbnail(relative_source=unicode_name, requested_size=(240, 120)) base_name = unicode_name.replace('.', '_') expected = os.path.join(settings.MEDIA_ROOT, base_name + '_240x120_q85.jpg') self.verify_thumbnail((160, 120), thumb, expected_filename=expected)
def _get_thumbnail(model_instance, field, attrs): # Build kwargs kwargs = {} for k, v in attrs.items(): kwargs[ALL_ARGS[k]] = v # Build relative source path filename = getattr(model_instance, 'get_%s_filename' % field.name)() media_root_len = len(os.path.normpath(settings.MEDIA_ROOT)) filename = os.path.normpath(filename) filename = filename[media_root_len:].lstrip(os.path.sep) # Return thumbnail return DjangoThumbnail(filename, **kwargs)
def testFilenameGeneration(self): basename = RELATIVE_PIC_NAME.replace('.', '_') # Basic filename thumb = DjangoThumbnail(relative_source=RELATIVE_PIC_NAME, requested_size=(240, 120)) expected = os.path.join(settings.MEDIA_ROOT, basename) expected += '_240x120_q85.jpg' self.verify_thumbnail((160, 120), thumb, expected_filename=expected) # Changed quality and cropped thumb = DjangoThumbnail(relative_source=RELATIVE_PIC_NAME, requested_size=(240, 120), opts=['crop'], quality=95) expected = os.path.join(settings.MEDIA_ROOT, basename) expected += '_240x120_crop_q95.jpg' self.verify_thumbnail((240, 120), thumb, expected_filename=expected) # All options on processors = dynamic_import(get_thumbnail_setting('PROCESSORS')) valid_options = get_valid_options(processors) thumb = DjangoThumbnail(relative_source=RELATIVE_PIC_NAME, requested_size=(240, 120), opts=valid_options) expected = (os.path.join(settings.MEDIA_ROOT, basename) + '_240x120_' 'autocrop_bw_crop_detail_max_sharpen_upscale_q85.jpg') self.verify_thumbnail((240, 120), thumb, expected_filename=expected) # Different basedir basedir = 'sorl-thumbnail-test-basedir' self.change_settings.change({'BASEDIR': basedir}) thumb = DjangoThumbnail(relative_source=self.pic_subdir, requested_size=(240, 120)) expected = os.path.join(basedir, self.sub_dir, basename) expected += '_240x120_q85.jpg' self.verify_thumbnail((160, 120), thumb, expected_filename=expected) # Different subdir self.change_settings.change({'BASEDIR': '', 'SUBDIR': 'subdir'}) thumb = DjangoThumbnail(relative_source=self.pic_subdir, requested_size=(240, 120)) expected = os.path.join(settings.MEDIA_ROOT, os.path.basename(self.sub_dir), 'subdir', basename) expected += '_240x120_q85.jpg' self.verify_thumbnail((160, 120), thumb, expected_filename=expected) # Different prefix self.change_settings.change({'SUBDIR': '', 'PREFIX': 'prefix-'}) thumb = DjangoThumbnail(relative_source=self.pic_subdir, requested_size=(240, 120)) expected = os.path.join(self.sub_dir, 'prefix-' + basename) expected += '_240x120_q85.jpg' self.verify_thumbnail((160, 120), thumb, expected_filename=expected)
def _nearby_people_escape(person): """return the person like this {'latitude':<latitude>, 'longitude':<longitude>, 'fullname':<full name>, #'username':<username>, 'location_description':<location_description>, 'photo_thumbnail_url':<photo thumnail url>, 'country_iso_code': <country iso code lowercase>, 'clubs':[{'name':<name>, 'url':<url within this site>}, ...], 'styles':[{'name':<name>, 'url':<url within this site>}, ...], } ...escaped for javascript. """ data = dict( latitude=person.latitude, longitude=person.longitude, fullname=unicode(person), #username=person.user.username, user_url=person.get_absolute_url(), location_description=person.location_description, ) if person.photo: thumbnail = DjangoThumbnail(person.photo, (60, 60), opts=['crop'], processors=thumbnail_processors) data['photo_thumbnail_url'] = thumbnail.absolute_url else: data['photo_thumbnail_url'] = staticfile("/img/upload-a-photo-60.png") data['country_iso_code'] = person.country.iso_code.lower() data['clubs'] = [] for club in person.club_membership.all(): data['clubs'].append({ 'name': club.name, 'url': club.get_absolute_url() }) _optimize_nearby_person_keys(data) return simplejson.dumps(data)
def thumbnail(self): thumb = DjangoThumbnail(self.file, (75,75)) thumb.generate() return '<img src="%s" width="%s" height="%s"/>' % (thumb.absolute_url, thumb.width(), thumb.height())
def get_all_items(model, sort_by): qs = {'clubs': Club, 'styles': Style, 'people': KungfuPerson, 'photos': Photo, }[model].objects.all() if model == 'people': qs = qs.select_related('user') elif model == 'photos': qs = qs.select_related('country','user') if sort_by == 'date': order_by = {'clubs':'-date_added', 'styles':'-date_added', 'people':'-user__date_joined', 'photos':'-date_added', }[model] else: # by name order_by = {'clubs':'name', 'styles':'name', 'people':('user__first_name', 'user__last_name'), 'photos':('location_description', 'country__name'), }[model] if isinstance(order_by, basestring): order_by = (order_by,) qs = qs.order_by(*order_by) count = qs.count() page_title = u"All %s %s" % (count, model) title = "All %s %s on this site so far" % (count, model) # now, turn this queryset into a list of _ListItems _today = datetime.datetime.today() counts_cache_key = 'all-counts-%s' % model counts = cache.get(counts_cache_key, {}) items = [] for item in qs: if model == 'people': if item.photo: thumbnail = DjangoThumbnail(item.photo, (40,40), opts=['crop'], processors=thumbnail_processors) thumbnail_url = thumbnail.absolute_url else: thumbnail_url = gravatar_thumbnail_url(item.user.email, size=40) #thumbnail_url = staticfile('/img/upload-a-photo-40.png') thumbnail_size = (40, 40) info = 'joined %s ago' % timesince(item.user.date_joined, _today) items.append(_ListItem( item.get_absolute_url(), item.user.get_full_name(), info=info, thumbnail_url=thumbnail_url, thumbnail_size=thumbnail_size, )) elif model == 'photos': if not os.path.isfile(os.path.join(settings.MEDIA_ROOT, item.photo.path)): logging.info("Photo id=%s is missing the photo itself!" %\ item.id) continue thumbnail = DjangoThumbnail(item.photo, (40,40), opts=['crop'], processors=thumbnail_processors) thumbnail_url = thumbnail.absolute_url thumbnail_size = (40,40) if item.description: _title = truncate_words(item.description, 10) else: _title = '' _title = ' %s, %s' % (item.location_description, item.country.name) #if item.description: # title = truncate_words(item.description, 10) #else: # title = '' info = 'Added by <a href="/%s/">%s</a>' % (item.user.username, item.user.get_full_name()) info += ' %s ago' % timesince(item.date_added, _today) items.append(_ListItem( item.get_absolute_url(), _title.strip(), info=info, thumbnail_url=thumbnail_url, thumbnail_size=thumbnail_size, )) elif model in ('clubs','styles'): if item.id in counts: people_count = counts[item.id] else: people_count = item.kungfuperson_set.count() counts[item.id] = people_count if people_count: if people_count > 1: info = '%s people' % people_count else: info = '1 person' else: info = 'added %s ago' % timesince(item.date_added, _today) items.append(_ListItem( item.get_absolute_url(), item.name, info=info, )) cache.set(counts_cache_key, counts, ONE_HOUR) return dict(items=items, page_title=page_title, title=title)
def thumbnail(self, obj): thumbnail = DjangoThumbnail(obj.image, (150, 150)) return u'<img src="%s" border="0" alt="" width="%s" height="%s" />' % \ (thumbnail.absolute_url, thumbnail.width(), thumbnail.height())
def picture(self, obj): thumb = DjangoThumbnail(obj.image, (200,200)) return '<img src="%s" />' % thumb.__unicode__()