def getSeasonalActivityTagBanners(latest_news=None, seasonal_settings=None): print 'Get seasonal activity tag banners' if latest_news is None: latest_news = [] if not seasonal_settings: return latest_news for current_season_name, current_season in seasonal_settings.items(): season = SEASONS.get(current_season_name, {}) show = season.get('show_activity_tag_banner_on_homepage', True) if not show: continue tag = season.get('activity_tag', None) if tag: image = current_season.get('activity_tag_banner', None) or None t_titles = {} old_lang = get_language() for lang, _verbose in django_settings.LANGUAGES: translation_activate(lang) t_titles[lang] = unicode(tag) translation_activate(old_lang) latest_news.append({ 'category': 'seasonal_activity_tag', 't_titles': t_titles, 'image': image, 'url': u'/activities/?search=&c_tags=season-{}&is_popular=1'.format(current_season_name), 'hide_title': bool(image), }) return latest_news
def getCharactersBirthdays(queryset, get_name_image_url_from_character, latest_news=None, days_after=12, days_before=1, field_name='birthday'): if not latest_news: latest_news = [] now = timezone.now() characters = list(queryset.filter( birthdays_within(days_after=days_after, days_before=days_before, field_name=field_name) ).order_by('name')) characters.sort(key=lambda c: getattr(c, field_name).replace(year=2000)) for character in characters: name, image, url = get_name_image_url_from_character(character) t_titles = {} old_lang = get_language() for lang, _verbose in django_settings.LANGUAGES: translation_activate(lang) t_titles[lang] = u'{}, {}! {}'.format( _('Happy Birthday'), name, date_format(getattr(character, field_name), format='MONTH_DAY_FORMAT', use_l10n=True), ) translation_activate(old_lang) latest_news.append({ 't_titles': t_titles, 'background': image, 'url': url, 'hide_title': False, 'ajax': False, 'css_classes': 'birthday', }) return latest_news
def log_in(request): """ Log in a member. """ error = False if request.method == "POST": form = LogInForm(request.POST) if form.is_valid(): username = form.cleaned_data["username"] password = form.cleaned_data["password"] user = authenticate(username=username, password=password) if user: login(request, user) profile = Profile.objects.get(user=user) if profile.locale and profile.locale != "": translation_activate(profile.locale) request.session[LANGUAGE_SESSION_KEY] = profile.locale redirect_url = request.GET.get("next") if redirect_url: return redirect(redirect_url) else: error = True else: form = LogInForm() return render(request, "base/login.html", locals())
def getUsersBirthdaysToday(image, latest_news=None, max_usernames=4): if not latest_news: latest_news = [] now = timezone.now() users = list(models.User.objects.filter( preferences__birthdate__day=now.day, preferences__birthdate__month=now.month, ).order_by('-preferences___cache_reputation')) if users: usernames = u'{}{}'.format( u', '.join([user.username for user in users[:max_usernames]]), u' + {}'.format(len(users[max_usernames:])) if users[max_usernames:] else '', ) t_titles = {} old_lang = get_language() for lang, _verbose in django_settings.LANGUAGES: translation_activate(lang) t_titles[lang] = u'{} 🎂🎉 {}'.format( _('Happy Birthday'), usernames, ) translation_activate(old_lang) latest_news.append({ 't_titles': t_titles, 'image': image, 'url': ( users[0].item_url if len(users) == 1 else u'/users/?ids={}&ordering=preferences___cache_reputation&reverse_order=on'.format(u','.join([unicode(user.id) for user in users])) ), 'hide_title': False, 'css_classes': 'birthday font0-5', }) return latest_news
def setUp(self): # create test user self.client = Client() self.test_user_id = settings.TEST_USER_ID self.test_user_password = settings.TEST_USER_PASSWORD user = User.objects.create_user(self.test_user_id, '', self.test_user_password) translation_activate('en')
def handle(self, *args, **options): sent = [] notifications = models.Notification.objects.filter( email_sent=False).select_related('owner', 'owner__preferences') for notification in notifications: preferences = notification.owner.preferences if preferences.is_notification_email_allowed(notification.message): notification_sent = notification.owner.email + notification.english_message + notification.website_url if notification_sent in sent: print u' Duplicate not sent to {}: {}'.format( notification.owner.username, notification.english_message) else: language = preferences.language if preferences.i_language else 'en' translation_activate(language) context = emailContext() context['notification'] = notification context['user'] = notification.owner try: send_email( subject=u'{} {}: {}'.format( SITE_NAME_PER_LANGUAGE.get( language, SITE_NAME), unicode(_('Notification')), notification.localized_message), template_name='notification', to=[notification.owner.email], context=context, ) try: print u'Email sent to {}: {}'.format( notification.owner.username, notification.localized_message.replace( '\n', '')) except: print 'Email sent' sent.append(notification_sent) except Exception, e: print u'!! Error when sending email to {} !!'.format( notification.owner.email) print e notification.owner.preferences.invalid_email = True notification.owner.preferences.save() else: try: print ' No email for {}: {}'.format( notification.owner.username, notification.localized_message.replace('\n', '')) except: print 'No email' notification.email_sent = True notification.save()
def lending_end(request, lending_id): """ Finishes the lending and adds a finish date. """ lending = get_object_or_404(Lending, pk=lending_id) if request.method == "POST": form = LendingEndForm(request.POST, instance=lending) if form.is_valid(): queues = Queue.objects.filter(book_copy__id=lending.book_copy.id).order_by("added_date").all() if len(queues) > 0: # send an email to queue 0 if queues[0].borrower.email: current_locale = to_locale(get_language()) # Tries to switch to the receiver locale. try: profile = Profile.objects.get(user=lending.borrower) translation_activate(profile.locale) except Profile.DoesNotExist: pass # Creates the mail body. d = Context({"book_copy": lending.book_copy}) plaintext_mail = get_template("mails/sharing/queue_book_ready.txt").render(d) html_mail = get_template("mails/sharing/queue_book_ready.html").render(d) # Sends it with the locale translation. send_mail( _("Your book is ready !"), "*****@*****.**", plaintext_mail.replace("\n", ""), [queues[0].borrower.email], html_message=html_mail, fail_silently=False, ) # Sets locale back to current user preferences. translation_activate(current_locale) form.save() messages.add_message( request, messages.SUCCESS, _("The lending has been updated and the new end date is now %s." % lending.end_date), ) return redirect("book_detail", book_id=lending.book_copy.book.id) else: form = LendingEndForm(instance=lending, initial={"end_date": timezone.now()}) return render(request, "sharing/lending_form.html", {"form": form})
def test_get_cached_one(self): expected = { 'ajax_item_url': u'/ajax/idol/1/', 'full_item_url': u'http://test.com/idol/1/Deby/', 'http_item_url': u'http://test.com/idol/1/Deby/', u'id': 1, u'image': u'idols/deby.png', 'image_url': u'//localhost:8000/idols/deby.png', u'http_image_url': u'https://localhost:8000/idols/deby.png', 'item_url': u'/idol/1/Deby/', u'japanese_name': u'デビ', u'name': u'Deby', 'names': {'ru': u'Деби'}, 't_name': u'Deby', 'pk': 1, 'unicode': u'Deby', } self.assertEqual(self.card.cached_idol, expected) translation_activate('ru') expected['t_name'] = u'Деби' self.assertEqual(self.card.cached_idol, expected) translation_activate('en')
def profile_edit(request): """ Show a member's profile and allows him to edit it. """ profile = get_object_or_404(Profile, user__id=request.user.id) if request.method == "POST": form_user = UserEditForm(request.POST, instance=request.user) form_profile = ProfileForm(request.POST, request.FILES, instance=profile) if form_user.is_valid() and form_profile.is_valid(): confirm_password = form_user.cleaned_data["confirm_password"] password = form_user.cleaned_data["password"] # Either both passwords have been sent and are equal # Or none has been sent if (not confirm_password and not password) or confirm_password == password: user = form_user.save(commit=False) # Only update password if both have been sent otherwise it will logout the user. if confirm_password and password: user.set_password(password) user.save() user = authenticate(username=user.username, password=password) if user is not None: if user.is_active: login(request, user) # We otherwise save the email modifications. else: user.save() profile = form_profile.save() translation_activate(profile.locale) request.session[LANGUAGE_SESSION_KEY] = profile.locale messages.add_message(request, messages.SUCCESS, _("Your profile has been successfully updated !")) return redirect(reverse("profile_show", args=[request.user.id])) else: messages.add_message(request, messages.ERROR, _("The two passwords are different or you forgot one.")) else: form_user = UserEditForm(instance=request.user) form_profile = ProfileForm(instance=profile) return render(request, "sharing/member_form.html", {"form_user": form_user, "form_profile": form_profile})
def handle(self, *args, **options): sent = [] notifications = models.Notification.objects.filter(email_sent=False, seen=False).select_related('owner', 'owner__preferences') for notification in notifications: preferences = notification.owner.preferences if preferences.is_notification_email_allowed(notification.message): try: notification_sent = notification.owner.email + notification.english_message + notification.website_url except Exception, e: print u'!! Error when parsing notification', notification.id, e continue if notification_sent in sent: print u' Duplicate not sent to {}: {}'.format(notification.owner.username, notification.english_message) else: language = preferences.language if preferences.i_language else 'en' translation_activate(language) context = emailContext() context['notification'] = notification context['user'] = notification.owner try: send_email( subject=u'{} {}: {}'.format(SITE_NAME_PER_LANGUAGE.get(language, SITE_NAME), unicode(_('Notification')), notification.localized_message), template_name='notification', to=[notification.owner.email], context=context, ) try: print u'Email sent to {}: {}'.format(notification.owner.username, notification.localized_message.replace('\n', '')) except: print 'Email sent' sent.append(notification_sent) except Exception, e: print u'!! Error when sending email to {} !!'.format(notification.owner.email) print e notification.owner.preferences.invalid_email = True notification.owner.preferences.save()
def test_get_cached_one(self): expected = { 'ajax_item_url': u'/ajax/idol/1/', 'full_item_url': u'http://test.com/idol/1/Deby/', 'http_item_url': u'http://test.com/idol/1/Deby/', u'id': 1, u'image': u'idols/deby.png', 'image_url': u'//localhost:8000/idols/deby.png', u'http_image_url': u'https://localhost:8000/idols/deby.png', 'item_url': u'/idol/1/Deby/', u'japanese_name': u'デビ', u'name': u'Deby', 'names': { 'ru': u'Деби' }, 't_name': u'Deby', 'pk': 1, 'unicode': u'Deby', } self.assertEqual(self.card.cached_idol, expected) translation_activate('ru') expected['t_name'] = u'Деби' self.assertEqual(self.card.cached_idol, expected) translation_activate('en')
def getUsersBirthdaysToday(image=None, latest_news=None, max_usernames=4): print 'Show a happy birthday banner for the users whose birthday is today' if not latest_news: latest_news = [] now = timezone.now() users = list(models.User.objects.filter( preferences__birthdate__day=now.day, preferences__birthdate__month=now.month, ).order_by('-preferences___cache_reputation')) if users: usernames = u'{}{}'.format( u', '.join([user.username for user in users[:max_usernames]]), u' + {}'.format(len(users[max_usernames:])) if users[max_usernames:] else '', ) t_titles = {} old_lang = get_language() for lang, _verbose in django_settings.LANGUAGES: translation_activate(lang) t_titles[lang] = u'{} 🎂🎉 {}'.format( _('Happy Birthday'), usernames, ) translation_activate(old_lang) latest_news.append({ 'category': 'users_birthdays', 't_titles': t_titles, 'image': image or USERS_BIRTHDAYS_BANNER, 'url': ( users[0].item_url if len(users) == 1 else u'/users/?ids={}&ordering=preferences___cache_reputation&reverse_order=on'.format(u','.join([unicode(user.id) for user in users])) ), 'hide_title': False, 'css_classes': 'birthday font0-5', }) return latest_news
def getCharactersBirthdays(queryset, get_name_image_url_from_character=defaultGetNameImageURLFromCharacter, latest_news=None, days_after=12, days_before=1, field_name='birthday', category='characters_birthdays'): print 'Show a banner for current and upcoming {}'.format(snakeCaseToTitle(category)) if not latest_news: latest_news = [] now = timezone.now() characters = list(queryset.filter( birthdays_within(days_after=days_after, days_before=days_before, field_name=field_name) ).order_by('name')) characters.sort(key=lambda c: getattr(c, field_name).replace(year=2000)) for character in characters: name, image, url = get_name_image_url_from_character(character) if name is None: continue t_titles = {} old_lang = get_language() for lang, _verbose in django_settings.LANGUAGES: translation_activate(lang) t_titles[lang] = u'{}, {}! {}'.format( _('Happy Birthday'), name, date_format(getattr(character, field_name), format='MONTH_DAY_FORMAT', use_l10n=True), ) translation_activate(old_lang) latest_news.append({ 'category': category, 'color': getattr(character, 'color', None), 't_titles': t_titles, 'background': image, 'url': url, 'hide_title': False, 'ajax': False, 'css_classes': 'birthday', }) return latest_news
def generate_settings(): ############################################################ # MagiCircles print 'Get staff configurations and latest news' staff_configurations, latest_news = getStaffConfigurations() print 'Get seasonal settings' seasonal_settings = seasonalGeneratedSettings(staff_configurations) print 'Get the latest news' now = timezone.now() old_lang = get_language() ############################################################ # Birthdays def get_name_image_url_from_character(character): card = models.Card.objects.filter(member=character).filter( show_art_on_homepage=True).order_by('-i_rarity', '-release_date')[0] return character.first_name, card.art_original_url, character.item_url latest_news = getCharactersBirthdays( models.Member.objects.all(), get_name_image_url_from_character, latest_news=latest_news, ) # Users birthdays latest_news = getUsersBirthdaysToday( staticImageURL('happy_birthday.png'), latest_news=latest_news, max_usernames=4, ) ############################################################ # BanG Dream! # Events & Gachas two_days_ago = now - datetime.timedelta(days=2) in_twelve_days = now + datetime.timedelta( days=12) # = event length 7d + 5d margin events_with_cards = [] for version_name, version in models.Account.VERSIONS.items(): for event in (list( models.Event.objects.filter( **{ version['prefix'] + 'end_date__gte': two_days_ago, version['prefix'] + 'end_date__lte': in_twelve_days, }) ) + list( models.Gacha.objects.filter( **{ version['prefix'] + 'end_date__gte': now, version['prefix'] + 'end_date__lte': in_twelve_days, }))): if version_name in ['JP', 'EN']: events_with_cards.append(event) image = getattr(event, u'{}image_url'.format(version['prefix'])) if not image: continue translation_activate(version['code']) latest_news.append({ 'title': unicode(event.t_name), 'image': image, 'url': event.item_url, 'hide_title': True, 'ajax': False, #event.ajax_item_url, weird carousel bug with data-ajax }) translation_activate(old_lang) # User Profile Backgrounds print 'Get the backgrounds' background_choices = models.Asset.objects.filter( i_type=models.Asset.get_i('type', 'background')) backgrounds = [{ 'id': background.id, 'thumbnail': background.top_image_list, 'image': background.top_image, 'name': background.name, 'd_names': background.names, } for background in background_choices if background.top_image] print 'Get the characters' all_members = models.Member.objects.all().order_by('id') favorite_characters = [( member.pk, member.name, member.square_image_url, ) for member in all_members] print 'Get homepage cards' cards = models.Card.objects.exclude( (Q(art__isnull=True) | Q(art='')) & (Q(art_trained__isnull=True) | Q(art_trained='')) & (Q(transparent__isnull=True) | Q(transparent='')), ).exclude( show_art_on_homepage=False, show_trained_art_on_homepage=False, ).order_by('-release_date') is_character_birthday = False christmas_cards = django_settings.STAFF_CONFIGURATIONS.get( 'christmas_theme_cards', '').split(',') birthday_today_members_id = models.Member.objects.filter( birthdays_within(days_after=1, days_before=1)).values_list('id', flat=True) if birthday_today_members_id: filtered_cards = cards.filter( member_id__in=birthday_today_members_id)[:20] is_character_birthday = True elif len(christmas_cards) > 1 and 'christmas' in seasonal_settings: filtered_cards = cards.filter(id__in=christmas_cards) else: condition = Q() for event in events_with_cards: if event._meta.model.__name__ == 'Gacha': condition |= Q(gachas=event) else: condition |= Q(secondary_card_event=event) condition |= Q(main_card_event=event) ten_days_ago = now - datetime.timedelta(days=10) condition |= Q(is_promo=True, release_date__gte=ten_days_ago) filtered_cards = cards.filter(condition) if filtered_cards: filtered_cards = filtered_cards[:20] else: filtered_cards = cards[:10] is_character_birthday = False homepage_arts = [] position = {'size': 'cover', 'x': 'center', 'y': 'center'} for c in filtered_cards: # Normal if c.show_art_on_homepage: if c.trainable and c.art: homepage_arts.append({ 'url': c.art_url, 'hd_url': c.art_2x_url or c.art_original_url, 'about_url': c.item_url, }) elif c.transparent: homepage_arts.append({ 'foreground_url': c.transparent_url, 'about_url': c.item_url, 'position': position, }) # Trained if c.trainable and c.show_trained_art_on_homepage: if c.trainable and c.art_trained: homepage_arts.append({ 'url': c.art_trained_url, 'hd_url': c.art_trained_2x_url or c.art_trained_original_url, 'about_url': c.item_url, }) elif c.transparent_trained: homepage_arts.append({ 'foreground_url': c.transparent_trained_url, 'about_url': c.item_url, 'position': position, }) if 'christmas' in seasonal_settings and not birthday_today_members_id: christmas_homepage_arts = django_settings.STAFF_CONFIGURATIONS.get( 'christmas_theme_arts', None) if christmas_homepage_arts: homepage_arts += json.loads(christmas_homepage_arts) if not homepage_arts: homepage_arts = [{ 'url': '//i.bandori.party/u/c/art/838Kasumi-Toyama-Happy-Colorful-Poppin-U7hhHG.png', 'hd_url': '//i.bandori.party/u/c/art/838Kasumi-Toyama-Happy-Colorful-Poppin-WV6jFP.png', }] print 'Get max stats' stats = { 'performance_max': None, 'performance_trained_max': None, 'technique_max': None, 'technique_trained_max': None, 'visual_max': None, 'visual_trained_max': None, 'overall_max_': None, 'overall_trained_max_': None, } try: for stat in stats.keys(): max_stats = models.Card.objects.all().extra( select={ 'overall_max_': 'performance_max + technique_max + visual_max', 'overall_trained_max_': 'performance_trained_max + technique_trained_max + visual_trained_max', }).order_by('-' + stat)[0] stats[stat] = getattr(max_stats, stat) stats['overall_max'] = stats['overall_max_'] del (stats['overall_max_']) stats['overall_trained_max'] = stats['overall_trained_max_'] del (stats['overall_trained_max_']) except IndexError: pass print 'Get schools' schools = models.Member.objects.filter(school__isnull=False).values_list( 'school', flat=True).distinct() print 'Get areas' areas = [{ 'id': area.id, 'image': area.image_url, 'name': area.name, 'd_names': area.names, } for area in models.Area.objects.all()] print 'Save generated settings' generateSettings({ 'LATEST_NEWS': latest_news, 'HOMEPAGE_ARTS': homepage_arts, 'IS_CHARACTER_BIRTHDAY': is_character_birthday, 'STAFF_CONFIGURATIONS': staff_configurations, 'FAVORITE_CHARACTERS': favorite_characters, 'BACKGROUNDS': backgrounds, 'MAX_STATS': stats, 'SCHOOLS': schools, 'AREAS': areas, })
def generateCharactersSettings( queryset, generated_settings, imports=None, for_favorite=True, base_name=None, to_image=None, ): imports.append('from collections import OrderedDict') if not base_name: if for_favorite: base_name = 'FAVORITE_CHARACTERS' else: base_name = camelToSnakeCase(queryset.model.__name__, upper=True) + u'S' print u'Get the {}'.format(snakeCaseToTitle(base_name)) generated_settings[base_name] = [] original_names = {} for character in queryset: name = unicode(character) if to_image: image = to_image(character) else: for image_field in [ 'image_for_favorite_character', 'top_image_list', 'top_image', 'image_thumbnail_url', 'image_url', ]: image = getattr(character, image_field, None) if image: break if image and name: original_names[character.pk] = name generated_settings[base_name].append(( character.pk, name, image, )) all_names = OrderedDict() for language, _verbose in django_settings.LANGUAGES: for character in queryset: if character.pk not in original_names: continue translation_activate(language) name = unicode(character) if name != original_names[character.pk]: if character.pk not in all_names: all_names[character.pk] = {} all_names[character.pk][language] = name translation_activate('en') generated_settings[u'{}_NAMES'.format(base_name)] = all_names if modelHasField(queryset.model, 'birthday'): generated_settings[u'{}_BIRTHDAYS'.format(base_name)] = OrderedDict([ (character.pk, (character.birthday.month, character.birthday.day)) for character in birthdayOrderingQueryset(queryset.exclude(birthday=None), order_by=True) if character.pk in original_names and getattr(character, 'birthday', None) ]) generated_settings[u'{}_BIRTHDAY_TODAY'.format(base_name)] = queryset.filter( birthdays_within(days_after=1, days_before=1)).values_list( 'pk', flat=True)
def moderatereport(request, report, action): if not request.user.is_authenticated() or not hasPermission( request.user, 'moderate_reports') or request.method != 'POST': raise PermissionDenied() report = get_object_or_404( models.Report.objects.exclude(owner=request.user).select_related( 'owner', 'owner__preferences'), pk=report, i_status=models.Report.get_i('status', 'Pending')) if (not request.user.is_superuser and ((action == 'Edited' and not report.allow_edit) or (action == 'Deleted' and not report.allow_delete))): raise PermissionDenied() report.staff = request.user old_language = get_language() moderated_reports = [] context = emailContext() context['report'] = report if action == 'Edited' or action == 'Deleted': # Get the reported thing queryset = report.reported_thing_collection.queryset thing = get_object_or_404(queryset, pk=report.reported_thing_id) # Make sure there's an owner if not hasattr(thing, 'owner') and isinstance(thing, models.User): thing.owner = thing # Get staff message if 'staff_message' not in request.POST or not request.POST[ 'staff_message']: raise PermissionDenied() report.staff_message = request.POST['staff_message'] # Get reason reason = request.POST.get('reason', None) if reason and reason != '_other': report.reason = reason # Action: Ignore if action == 'Ignored': report.i_status = models.Report.get_i('status', 'Ignored') report.save() moderated_reports = [report.pk] # Action: Edit elif action == 'Edited': if report.reported_thing_collection.item_view.enabled: context['item_url'] = thing.http_item_url context['item_open_sentence'] = thing.open_sentence else: context['item_url'] = None context['item_open_sentence'] = None report.i_status = models.Report.get_i('status', 'Edited') # Notify reporter if report.owner: translation_activate(report.owner.preferences.language if report. owner.preferences.language else 'en') context['sentence'] = _( u'This {thing} you reported has been reviewed by a moderator and {verb}. Thank you so much for your help!' ).format(thing=_(report.reported_thing_title), verb=_(u'edited')) context['user'] = report.owner context['show_donation'] = True context['subject'] = u'{} {}'.format( SITE_NAME, unicode( _(u'Thank you for reporting this {thing}').format( thing=_(report.reported_thing_title)))) send_email(context['subject'], template_name='report', to=[context['user'].email], context=context) # Notify owner if thing.owner: translation_activate(thing.real_owner.preferences.language if thing .real_owner.preferences.language else 'en') context['sentence'] = _( u'Your {thing} has been reported, and a moderator confirmed it should be {verb}.' ).format(thing=_(report.reported_thing_title), verb=_(u'edited')) context['user'] = thing.real_owner context['show_donation'] = False context['subject'] = u'{} {}'.format( SITE_NAME, unicode( _(u'Your {thing} has been {verb}').format( thing=_(report.reported_thing_title), verb=_(u'edited')))) send_email(context['subject'], template_name='report', to=[context['user'].email], context=context) report.save() moderated_reports = [report.pk] elif action == 'Deleted': report.i_status = models.Report.get_i('status', 'Deleted') report.saved_data = dumpModel(thing) # Notify all reporters all_reports = models.Report.objects.filter( reported_thing=report.reported_thing, reported_thing_id=report.reported_thing_id, i_status=models.Report.get_i('status', 'Pending'), ).select_related('owner', 'owner__preferences') for a_report in all_reports: if a_report.owner: translation_activate( a_report.owner.preferences.language if a_report.owner. preferences.language else 'en') context['sentence'] = _( u'This {thing} you reported has been reviewed by a moderator and {verb}. Thank you so much for your help!' ).format(thing=_(report.reported_thing_title), verb=_(u'deleted')) context['user'] = a_report.owner context['show_donation'] = True context['subject'] = u'{} {}'.format( SITE_NAME, unicode( _(u'Thank you for reporting this {thing}').format( thing=_(report.reported_thing_title)))) send_email(context['subject'], template_name='report', to=[context['user'].email], context=context) # Notify owner if thing.owner: translation_activate(thing.real_owner.preferences.language if thing .real_owner.preferences.language else 'en') context['sentence'] = _( u'Your {thing} has been reported, and a moderator confirmed it should be {verb}.' ).format(thing=_(report.reported_thing_title), verb=_(u'edited')) context['user'] = thing.real_owner context['show_donation'] = False context['subject'] = u'{} {}'.format( SITE_NAME, unicode( _(u'Your {thing} has been {verb}').format( thing=_(report.reported_thing_title), verb=_(u'deleted')))) send_email(context['subject'], template_name='report', to=[context['user'].email], context=context) moderated_reports = [a_report.pk for a_report in all_reports] all_reports.update( staff=request.user, staff_message=report.staff_message, saved_data=report.saved_data, i_status=models.Report.get_i('status', 'Deleted'), ) thing.delete() translation_activate(old_language) return JsonResponse({ 'moderated_reports': moderated_reports, 'action': action, })
def generate_settings(): ############################################################ # BanG Dream! print 'Get schools' schools = listUnique( models.Member.objects.filter(school__isnull=False).values_list( 'school', flat=True).distinct()) print 'Get areas' areas = [{ 'id': area.id, 'image': area.image_url, 'name': area.name, 'd_names': area.names, } for area in models.Area.objects.all()] ############################################################ # Girls Band Party # Events & Gachas print 'Add events and gachas to latest news' latest_news = [] old_lang = get_language() for version_name, events in getCurrentEventsAndGachas().items(): version = models.Account.VERSIONS[version_name] for event in events: image = getattr(event, u'{}image_url'.format(version['prefix'])) if not image: continue translation_activate(version['code']) latest_news.append({ 'title': unicode(event.t_name), 'image': image, 'url': event.item_url, 'hide_title': True, 'ajax': False, #event.ajax_item_url, weird carousel bug with data-ajax }) translation_activate(old_lang) print 'Get max stats' stats = { 'performance_max': None, 'performance_trained_max': None, 'technique_max': None, 'technique_trained_max': None, 'visual_max': None, 'visual_trained_max': None, 'overall_max_': None, 'overall_trained_max_': None, } try: for stat in stats.keys(): max_stats = models.Card.objects.all().extra( select={ 'overall_max_': 'performance_max + technique_max + visual_max', 'overall_trained_max_': 'performance_trained_max + technique_trained_max + visual_trained_max', }).order_by('-' + stat)[0] stats[stat] = getattr(max_stats, stat) stats['overall_max'] = stats['overall_max_'] del (stats['overall_max_']) stats['overall_trained_max'] = stats['overall_trained_max_'] del (stats['overall_trained_max_']) except IndexError: pass ############################################################ print 'Save generated settings' generateSettings({ 'LATEST_NEWS': latest_news, 'MAX_STATS': stats, 'SCHOOLS': schools, 'AREAS': areas, })