我们从Python开源项目中,提取了以下41个代码示例,用于说明如何使用django.utils.formats.date_format()。
def shortdate(value): now = timezone.template_localtime(timezone.now()) diff = now - value if diff < timezone.timedelta(): return date_format(value, "DATE_FORMAT") elif diff.days < 1: return _('today') elif diff.days < 2: return _('yesterday') elif diff.days < 30: return ungettext_lazy('%d day ago', '%d days ago') % diff.days else: months = diff.days // 30 if months <= 6: return ungettext_lazy('a month ago', '%d months ago') % months else: return date_format(value, "DATE_FORMAT")
def get_display_date(self): tz = timezone.get_current_timezone() start_time = self.start_time.astimezone(tz) end_time = self.end_time.astimezone(tz) if start_time.date() == end_time.date(): date = formats.date_format(start_time, 'DATE_FORMAT') return _("le {date}, de {start_hour} à {end_hour}").format( date=date, start_hour=formats.time_format(start_time, 'TIME_FORMAT'), end_hour=formats.time_format(end_time, 'TIME_FORMAT') ) return _("du {start_date}, {start_time} au {end_date}, {end_time}").format( start_date=formats.date_format(start_time, 'DATE_FORMAT'), start_time=formats.date_format(start_time, 'TIME_FORMAT'), end_date=formats.date_format(end_time, 'DATE_FORMAT'), end_time=formats.date_format(end_time, 'TIME_FORMAT'), )
def format(self): if self.part == DateTimePart.date: return date_format(self.datetime, format='D, j. N Y') elif self.part == DateTimePart.time: return date_format(self.datetime, format='H:i') elif self.part == DateTimePart.datetime: return date_format(self.datetime, format='D, j. N Y H:i')
def __str__(self): """Display string for EmailLog.""" return "%s - %s" % (formats.date_format(self.date_sent), self.subject)
def date(value, arg=None): """Formats a date according to the given format.""" if value in (None, ''): return '' if arg is None: arg = settings.DATE_FORMAT try: return formats.date_format(value, arg) except AttributeError: try: return format(value, arg) except AttributeError: return ''
def postDate(dt, prefix=''): dt_now = datetime.utcnow().replace(tzinfo=utc) if dt.date() == dt_now.date(): delta = dt_now - dt hours = int(delta.seconds / 3600) string = getAmountContext(hours, 'hour') if string: return '%s ago' % string minutes = int(delta.seconds / 60) string = getAmountContext(minutes, 'minute') if string: return '%s ago' % string return 'less than a minute ago' return prefix + formats.date_format(dt.date(), "DATE_FORMAT")
def get_context_data(self, **kwargs): context = super(GeoReferenceUpdateView, self).get_context_data(**kwargs) if len(self.object.potential_georeferences.values()) < 2: self.object.auto_geolocate() self.object.save() context['feature_type_choices'] = models.FeatureType.objects.all() context['geographical_position_form'] = forms.GeographicalPositionForm() context['potential_geographical_positions'] = self.object.get_serialized_geolocations() same_collector = [] if self.object.locality_date and self.object.group_id: date_upper = self.object.locality_date + relativedelta(months=+3) date_lower = self.object.locality_date + relativedelta(months=-3) same_collector_points = models.GeoReference.objects.filter(group_id=self.object.group_id, locality_date__range=[date_lower, date_upper], geographical_position__isnull=False) for p in same_collector_points: # p.geographical_position.origin = models.GeographicalPosition.SAME_GROUP p.geographical_position.notes = 'Visited by same collector on ' + formats.date_format(p.locality_date, "SHORT_DATE_FORMAT") # same_collector.append(p.geographical_position) same_collector.append(p) if same_collector: context['same_collector'] = serialize('custom_geojson', same_collector, geometry_field='point') if self.object.geographical_position: if self.object.geographical_position.point: context['geographical_position'] = serialize('geojson', [self.object.geographical_position, ], geometry_field='point') else: context['geographical_position'] = serialize('geojson', [self.object.geographical_position, ], geometry_field='polygon') return context
def test_can_see_talk(client, event, slot): response = client.get(slot.submission.urls.public, follow=True) assert event.schedules.count() == 2 assert response.status_code == 200 content = response.content.decode() assert content.count(slot.submission.title) >= 2 # meta+h1 assert slot.submission.abstract in content assert slot.submission.description in content assert formats.date_format(slot.start, 'Y-m-d, H:i') in content assert formats.date_format(slot.end, 'H:i') in content assert str(slot.room.name) in content assert 'fa-pencil' not in content # edit btn assert 'fa-video-camera' not in content # do not record
def test_orga_can_see_new_talk(orga_client, event, unreleased_slot): slot = unreleased_slot response = orga_client.get(slot.submission.urls.public, follow=True) assert event.schedules.count() == 1 assert response.status_code == 200 content = response.content.decode() assert content.count(slot.submission.title) >= 2 # meta+h1 assert slot.submission.abstract in content assert slot.submission.description in content assert formats.date_format(slot.start, 'Y-m-d, H:i') in content assert formats.date_format(slot.end, 'H:i') in content assert str(slot.room.name) in content assert 'fa-pencil' not in content # edit btn assert 'fa-video-camera' not in content # do not record
def query_anomalies(request, system_name): cache_result = cache.get('json_cache:%s' % system_name) if cache_result is None: rv = {} current_anoms = get_object_or_404(System, name=system_name).anomaly_set.select_related('owner') if current_anoms.count() == 0: return JsonResponse({'anomalies': {}}) last_update = current_anoms.order_by('-last_seen').values_list('last_seen')[0][0] for a in current_anoms.all(): if (last_update - a.last_seen).total_seconds() > 300: continue rv[a.signature] = { 'type': a.site_type, 'last': formats.date_format(a.last_seen), 'first': formats.date_format(a.first_seen), 'claimed': a.claimed, } if a.owner is not None: rv[a.signature]['owner'] = a.owner.get_full_name() rv[a.signature]['owner_id'] = a.owner.character_id cache_result = {'last_update': formats.date_format(last_update), 'anomalies': rv} cache.set('json_cache:%s' % system_name, cache_result) return JsonResponse(cache_result)
def date_el(datetime, arg=None): if not datetime: return '' return mark_safe('<time datetime="%s">%s</time>' % (datetime.isoformat(), formats.date_format(datetime, arg)))
def solve_time(user, challenge): try: solve_dt = challenge.get_solve_time(user) if solve_dt: return "You solved this challenge at %s" % date_format(solve_dt, 'SHORT_DATETIME_FORMAT', True) return '' except Solver.DoesNotExist: return ''
def join_time(user, challenge): try: join_dt = challenge.get_join_time(user) if join_dt: return "You started solving this challenge on %s." % date_format(join_dt, 'SHORT_DATETIME_FORMAT', True) return '' except Solver.DoesNotExist: return ''
def date(value, arg=None): """Formats a date according to the given format.""" if value in (None, ''): return '' try: return formats.date_format(value, arg) except AttributeError: try: return format(value, arg) except AttributeError: return ''
def get_published(self, obj): return date_format(obj.published, 'SHORT_DATETIME_FORMAT')
def process_map_updates(self): if self.request.called_directly: logger.info('Processing map updates by direct command...') else: logger.info('Processing map updates...') from c3nav.mapdata.models import MapUpdate try: try: updates = MapUpdate.process_updates() except DatabaseError: if self.request.called_directly: raise logger.info('Processing is already running, retrying in 30 seconds.') raise self.retry(countdown=30) except MaxRetriesExceededError: logger.info('Cannot retry, retries exceeded. Exiting.') return if updates: print() logger.info(ungettext_lazy('%d map update processed.', '%d map updates processed.', len(updates)) % len(updates)) if updates: logger.info(_('Last processed update: %(date)s (#%(id)d)') % { 'date': date_format(updates[-1].datetime, 'DATETIME_FORMAT'), 'id': updates[-1].pk, })
def _serialize_field(self, data): if isinstance(data, Decimal): return float(data) elif isinstance(data, datetime.datetime): return formats.date_format(data, 'DSMR_EXPORT_DATETIME_FORMAT') elif isinstance(data, datetime.date): # pragma: no cover return formats.date_format(data, 'DSMR_DATEPICKER_DATE_FORMAT')
def get_context_data(self, **kwargs): context_data = super(ArchiveXhrSummary, self).get_context_data(**kwargs) context_data['capabilities'] = dsmr_backend.services.get_capabilities() context_data['frontend_settings'] = FrontendSettings.get_solo() selected_datetime = timezone.make_aware(timezone.datetime.strptime( self.request.GET['date'], formats.get_format('DSMR_STRFTIME_DATE_FORMAT') )) selected_level = self.request.GET['level'] context_data['statistics'] = { 'days': dsmr_stats.services.day_statistics(selected_datetime.date()), 'months': dsmr_stats.services.month_statistics(selected_datetime.date()), 'years': dsmr_stats.services.year_statistics(selected_datetime.date()), }[selected_level] context_data['title'] = { 'days': formats.date_format(selected_datetime.date(), 'DSMR_GRAPH_LONG_DATE_FORMAT'), 'months': formats.date_format(selected_datetime.date(), 'DSMR_DATEPICKER_MONTH'), 'years': selected_datetime.date().year, }[selected_level] # Only day level allows some additional data. if selected_level == 'days': try: # This WILL fail when we either have no prices at all or conflicting ranges. context_data['energy_price'] = EnergySupplierPrice.objects.by_date( target_date=selected_datetime.date() ) except (EnergySupplierPrice.DoesNotExist, EnergySupplierPrice.MultipleObjectsReturned): # Default to zero prices. context_data['energy_price'] = EnergySupplierPrice() context_data['notes'] = Note.objects.filter(day=selected_datetime.date()) context_data['selected_level'] = selected_level context_data['selected_datetime'] = selected_datetime context_data['django_date_format'] = 'DJANGO_DATE_FORMAT' return context_data
def calculate_min_max_consumption_watt(): """ Returns the lowest and highest Wattage consumed for each phase. """ FIELDS = { 'total_min': ('currently_delivered', ''), 'total_max': ('currently_delivered', '-'), 'l1_max': ('phase_currently_delivered_l1', '-'), 'l2_max': ('phase_currently_delivered_l2', '-'), 'l3_max': ('phase_currently_delivered_l3', '-'), } data = {} for name, args in FIELDS.items(): field, sorting = args try: read_at, value = ElectricityConsumption.objects.filter(**{ '{}__gt'.format(field): 0, # Skip (obvious) zero values. '{}__isnull'.format(field): False, # And skip empty data. }).order_by( '{}{}'.format(sorting, field) ).values_list('read_at', field)[0] except IndexError: continue data.update({ name: ( formats.date_format(timezone.localtime(read_at), 'DSMR_GRAPH_LONG_DATE_FORMAT'), int(value * 1000) ) }) return data
def update_data(self): now = timezone.localtime(timezone.now(), self.timezone) self.time = formats.time_format(now, 'TIME_FORMAT') self.date = formats.date_format(now, 'SHORT_DATE_FORMAT') self.save()
def last_Auswertungstermin_to_late_human(self): """Der erste Tag der nach dem letzten Auswertungstermin liegt formatiert""" toLateDate = self.last_Auswertungstermin() + datetime.timedelta(days=1) return formats.date_format(toLateDate, 'DATE_FORMAT')
def post_by_date(self, request, year, month=None, day=None, *args, **kwargs): self.posts = self.get_posts().filter(date__year=year) self.search_type = 'date' self.search_term = year if month: self.posts = self.posts.filter(date__month=month) df = DateFormat(date(int(year), int(month), 1)) self.search_term = df.format('F Y') if day: self.posts = self.posts.filter(date__day=day) self.search_term = date_format(date(int(year), int(month), int(day))) return Page.serve(self, request, *args, **kwargs)
def brodcast_dificulties(request, message, subject): msg = TalkMessages() msg.text = message msg.user = request.user msg.subject = subject simple_notify = textwrap.shorten(strip_tags(msg.text), width = 30, placeholder = "...") for p in subject.professor.all(): talks = Conversation.objects.filter((Q(user_one = request.user) & Q(user_two__email = p.email)) | (Q(user_two = request.user) & Q(user_one__email = p.email))) if talks.count() > 0: msg.talk = talks[0] else: msg.talk = Conversation.objects.create(user_one = request.user, user_two = p) msg.save() notification = { "type": "chat", "subtype": subject.slug, "space": "subject", "user_icon": request.user.image_url, "notify_title": str(request.user), "simple_notify": simple_notify, "view_url": reverse("chat:view_message", args = (msg.id, ), kwargs = {}), "complete": render_to_string("chat/_message.html", {"talk_msg": msg}, request), "container": "chat-" + str(request.user.id), "last_date": _("Last message in %s")%(formats.date_format(msg.create_date, "SHORT_DATETIME_FORMAT")) } notification = json.dumps(notification) Group("user-%s" % p.id).send({'text': notification}) sendChatPushNotification(p, msg) ChatVisualizations.objects.create(viewed = False, message = msg, user = p)
def form_valid(self, form): message = form.cleaned_data.get('comment') image = form.cleaned_data.get("image",'') users = (self.request.POST.get('users[]','')).split(",") user = self.request.user subject = self.ytvideo.topic.subject if (users[0] is not ''): for u in users: to_user = User.objects.get(email=u) talk, create = Conversation.objects.get_or_create(user_one=user,user_two=to_user) created = TalkMessages.objects.create(text=message,talk=talk,user=user,subject=subject,image=image) simple_notify = textwrap.shorten(strip_tags(message), width = 30, placeholder = "...") if image is not '': simple_notify += " ".join(_("[Photo]")) notification = { "type": "chat", "subtype": "subject", "space": subject.slug, "user_icon": created.user.image_url, "notify_title": str(created.user), "simple_notify": simple_notify, "view_url": reverse("chat:view_message", args = (created.id, ), kwargs = {}), "complete": render_to_string("chat/_message.html", {"talk_msg": created}, self.request), "container": "chat-" + str(created.user.id), "last_date": _("Last message in %s")%(formats.date_format(created.create_date, "SHORT_DATETIME_FORMAT")) } notification = json.dumps(notification) Group("user-%s" % to_user.id).send({'text': notification}) ChatVisualizations.objects.create(viewed = False, message = created, user = to_user) success = str(_('The message was successfull sent!')) return JsonResponse({"message":success}) erro = HttpResponse(str(_("No user selected!"))) erro.status_code = 404 return erro
def form_valid(self, form): message = form.cleaned_data.get('comment') image = form.cleaned_data.get("image",'') users = (self.request.POST.get('users[]','')).split(",") user = self.request.user subject = self.goal.topic.subject if (users[0] is not ''): for u in users: to_user = User.objects.get(email=u) talk, create = Conversation.objects.get_or_create(user_one=user,user_two=to_user) created = TalkMessages.objects.create(text=message,talk=talk,user=user,subject=subject,image=image) simple_notify = textwrap.shorten(strip_tags(message), width = 30, placeholder = "...") if image is not '': simple_notify += " ".join(_("[Photo]")) notification = { "type": "chat", "subtype": "subject", "space": subject.slug, "user_icon": created.user.image_url, "notify_title": str(created.user), "simple_notify": simple_notify, "view_url": reverse("chat:view_message", args = (created.id, ), kwargs = {}), "complete": render_to_string("chat/_message.html", {"talk_msg": created}, self.request), "container": "chat-" + str(created.user.id), "last_date": _("Last message in %s")%(formats.date_format(created.create_date, "SHORT_DATETIME_FORMAT")) } notification = json.dumps(notification) Group("user-%s" % to_user.id).send({'text': notification}) ChatVisualizations.objects.create(viewed = False, message = created, user = to_user) success = str(_('The message was successfull sent!')) return JsonResponse({"message":success}) erro = HttpResponse(str(_("No user selected!"))) erro.status_code = 404 return erro
def observation(notification): msg = '' if notification.level == 1: if notification.meta: msg = _('Goal defined to task realization: %s')%(formats.date_format(notification.meta.astimezone(timezone.get_current_timezone()), "SHORT_DATETIME_FORMAT")) elif notification.level == 2: if notification.meta: if notification.meta < timezone.now(): msg = _('Goal defined to task realization: %s')%(formats.date_format(notification.meta.astimezone(timezone.get_current_timezone()), "SHORT_DATETIME_FORMAT")) else: msg = _('New goal defined to task realization: %s')%(formats.date_format(notification.meta.astimezone(timezone.get_current_timezone()), "SHORT_DATETIME_FORMAT")) return msg
def _get_response(self): timestamp = date_format(self.object.created_on, 'DATETIME_FORMAT') data = { 'text': self.object.text, 'signature': "{} | {}".format(self.object.sent_by.username, timestamp), } return {'status': True, 'data': data}
def create(): """ Creates a backup of the database. Optionally gzipped. """ # Backup file with day name included, for weekly rotation. backup_file = os.path.join(get_backup_directory(), 'dsmrreader-{}-backup-{}.sql'.format( connection.vendor, formats.date_format(timezone.now().date(), 'l') )) # PostgreSQL backup. if connection.vendor == 'postgresql': # pragma: no cover backup_process = subprocess.Popen( [ settings.DSMRREADER_BACKUP_PG_DUMP, '--host={}'.format(settings.DATABASES['default']['HOST']), '--user={}'.format(settings.DATABASES['default']['USER']), settings.DATABASES['default']['NAME'], ], env={ 'PGPASSWORD': settings.DATABASES['default']['PASSWORD'] }, stdout=open(backup_file, 'w') # pragma: no cover ) # MySQL backup. elif connection.vendor == 'mysql': # pragma: no cover backup_process = subprocess.Popen( [ settings.DSMRREADER_BACKUP_MYSQLDUMP, '--compress', '--hex-blob', '--extended-insert', '--quick', '--host', settings.DATABASES['default']['HOST'], '--user', settings.DATABASES['default']['USER'], '--password={}'.format(settings.DATABASES['default']['PASSWORD']), settings.DATABASES['default']['NAME'], ], stdout=open(backup_file, 'w') # pragma: no cover ) # SQLite backup. elif connection.vendor == 'sqlite': # pragma: no cover backup_process = subprocess.Popen( [ settings.DSMRREADER_BACKUP_SQLITE, settings.DATABASES['default']['NAME'], '.dump', ], stdout=open(backup_file, 'w') ) # pragma: no cover else: raise NotImplementedError('Unsupported backup backend: {}'.format(connection.vendor)) # pragma: no cover backup_process.wait() backup_settings = BackupSettings.get_solo() if backup_settings.compress: compress(file_path=backup_file) backup_settings.latest_backup = timezone.now() backup_settings.save()
def test_archive(self, now_mock): now_mock.return_value = timezone.make_aware(timezone.datetime(2016, 1, 1)) response = self.client.get( reverse('{}:archive'.format(self.namespace)) ) self.assertEqual(response.status_code, 200) self.assertIn('capabilities', response.context) # XHR's. data = { 'date': formats.date_format(timezone.now().date(), 'DSMR_DATEPICKER_DATE_FORMAT'), } if self.support_data: self.assertEqual(response.context['start_date'], date(2016, 1, 1)) self.assertEqual(response.context['end_date'], date(2016, 1, 2)) for current_level in ('days', 'months', 'years'): # Test both with tariffs sparated and merged. for merge in (False, True): frontend_settings = FrontendSettings.get_solo() frontend_settings.merge_electricity_tariffs = merge frontend_settings.save() data.update({'level': current_level}) response = self.client.get( reverse('{}:archive-xhr-summary'.format(self.namespace)), data=data ) self.assertEqual(response.status_code, 200) response = self.client.get( reverse('{}:archive-xhr-graphs'.format(self.namespace)), data=data ) self.assertEqual(response.status_code, 200, response.content) # Invalid XHR. data.update({'level': 'INVALID DATA'}) response = self.client.get( reverse('{}:archive-xhr-summary'.format(self.namespace)), data=data ) self.assertEqual(response.status_code, 500) response = self.client.get( reverse('{}:archive-xhr-graphs'.format(self.namespace)), data=data ) self.assertEqual(response.status_code, 500)
def test_show_add_cases_to_run(self): self.login_tester() url = reverse('add-cases-to-run', args=[self.test_run.pk]) response = self.client.get(url) self.assertNotContains( response, '<a href="{0}">{1}</a>'.format( reverse('testcases-get', args=[self.proposed_case.pk]), self.proposed_case.pk), html=True ) confirmed_cases = [self.case, self.case_1, self.case_2, self.case_3] # Check selected and unselected case id checkboxes # cls.case is not added to cls.test_run, so it should not be checked. self.assertContains( response, '<td align="left">' '<input type="checkbox" name="case" value="{0}">' '</td>'.format(self.case.pk), html=True) # other cases are added to cls.test_run, so must be checked. for case in confirmed_cases[1:]: self.assertContains( response, '<td align="left">' '<input type="checkbox" name="case" value="{0}" ' 'disabled="true" checked="true">' '</td>'.format(case.pk), html=True) # Check listed case properties # note: the response is ordered by 'case' for loop_counter, case in enumerate(confirmed_cases, 1): html_pieces = [ '<a href="{0}">{1}</a>'.format( reverse('testcases-get', args=[case.pk]), case.pk), '<td class="js-case-summary" data-param="{0}">' '<a id="link_{0}" class="blind_title_link" ' 'href="javascript:void(0);">{1}</a></td>'.format(loop_counter, case.summary), '<td>{0}</td>'.format(case.author.username), '<td>{0}</td>'.format( formats.date_format(case.create_date, 'DATETIME_FORMAT')), '<td>{0}</td>'.format(case.category.name), '<td>{0}</td>'.format(case.priority.value), ] for html in html_pieces: self.assertContains(response, html, html=True)
def form_valid(self, form): message = form.cleaned_data.get('comment') image = form.cleaned_data.get("image") users = (self.request.POST.get('users[]','')).split(",") user = self.request.user subject = self.pdf_file.topic.subject if (users[0] is not ''): for u in users: to_user = User.objects.get(email=u) talk, create = Conversation.objects.get_or_create(user_one=user,user_two=to_user) created = TalkMessages.objects.create(text=message,talk=talk,user=user,subject=subject,image=image) simple_notify = textwrap.shorten(strip_tags(message), width = 30, placeholder = "...") if image is not '': simple_notify += " ".join(_("[Photo]")) notification = { "type": "chat", "subtype": "subject", "space": subject.slug, "user_icon": created.user.image_url, "notify_title": str(created.user), "simple_notify": simple_notify, "view_url": reverse("chat:view_message", args = (created.id, ), kwargs = {}), "complete": render_to_string("chat/_message.html", {"talk_msg": created}, self.request), "container": "chat-" + str(created.user.id), "last_date": _("Last message in %s")%(formats.date_format(created.create_date, "SHORT_DATETIME_FORMAT")) } notification = json.dumps(notification) Group("user-%s" % to_user.id).send({'text': notification}) ChatVisualizations.objects.create(viewed = False, message = created, user = to_user) success = str(_('The message was successfull sent!')) return JsonResponse({"message":success}) erro = HttpResponse(str(_("No user selected!"))) erro.status_code = 404 return erro
def form_valid(self, form): message = form.cleaned_data.get('comment') image = form.cleaned_data.get("image") users = (self.request.POST.get('users[]','')).split(",") user = self.request.user subject = self.link.topic.subject if (users[0] is not ''): for u in users: to_user = User.objects.get(email=u) talk, create = Conversation.objects.get_or_create(user_one=user,user_two=to_user) created = TalkMessages.objects.create(text=message,talk=talk,user=user,subject=subject,image=image) simple_notify = textwrap.shorten(strip_tags(message), width = 30, placeholder = "...") if image is not '': simple_notify += " ".join(_("[Photo]")) notification = { "type": "chat", "subtype": "subject", "space": subject.slug, "user_icon": created.user.image_url, "notify_title": str(created.user), "simple_notify": simple_notify, "view_url": reverse("chat:view_message", args = (created.id, ), kwargs = {}), "complete": render_to_string("chat/_message.html", {"talk_msg": created}, self.request), "container": "chat-" + str(created.user.id), "last_date": _("Last message in %s")%(formats.date_format(created.create_date, "SHORT_DATETIME_FORMAT")) } notification = json.dumps(notification) Group("user-%s" % to_user.id).send({'text': notification}) ChatVisualizations.objects.create(viewed = False, message = created, user = to_user) success = str(_('The message was successfull sent!')) return JsonResponse({"message":success}) erro = HttpResponse(str(_("No user selected!"))) erro.status_code = 404 return erro
def form_valid(self, form): message = form.cleaned_data.get('comment') image = form.cleaned_data.get("image") users = (self.request.POST.get('users[]','')).split(",") user = self.request.user subject = self.webconference.topic.subject if (users[0] is not ''): for u in users: to_user = User.objects.get(email=u) talk, create = Conversation.objects.get_or_create(user_one=user,user_two=to_user) created = TalkMessages.objects.create(text=message,talk=talk,user=user,subject=subject,image=image) simple_notify = textwrap.shorten(strip_tags(message), width = 30, placeholder = "...") if image is not '': simple_notify += " ".join(_("[Photo]")) notification = { "type": "chat", "subtype": "subject", "space": subject.slug, "user_icon": created.user.image_url, "notify_title": str(created.user), "simple_notify": simple_notify, "view_url": reverse("chat:view_message", args = (created.id, ), kwargs = {}), "complete": render_to_string("chat/_message.html", {"talk_msg": created}, self.request), "container": "chat-" + str(created.user.id), "last_date": _("Last message in %s")%(formats.date_format(created.create_date, "SHORT_DATETIME_FORMAT")) } notification = json.dumps(notification) Group("user-%s" % to_user.id).send({'text': notification}) ChatVisualizations.objects.create(viewed = False, message = created, user = to_user) success = str(_('The message was successfull sent!')) return JsonResponse({"message":success}) erro = HttpResponse(str(_("No user selected!"))) erro.status_code = 404 return erro
def form_valid(self, form): message = form.cleaned_data.get('comment') image = form.cleaned_data.get("image") users = (self.request.POST.get('users[]','')).split(",") user = self.request.user subject = self.bulletin.topic.subject if (users[0] is not ''): for u in users: to_user = User.objects.get(email=u) talk, create = Conversation.objects.get_or_create(user_one=user,user_two=to_user) created = TalkMessages.objects.create(text=message,talk=talk,user=user,subject=subject,image=image) simple_notify = textwrap.shorten(strip_tags(message), width = 30, placeholder = "...") if image is not '': simple_notify += " ".join(_("[Photo]")) notification = { "type": "chat", "subtype": "subject", "space": subject.slug, "user_icon": created.user.image_url, "notify_title": str(created.user), "simple_notify": simple_notify, "view_url": reverse("chat:view_message", args = (created.id, ), kwargs = {}), "complete": render_to_string("chat/_message.html", {"talk_msg": created}, self.request), "container": "chat-" + str(created.user.id), "last_date": _("Last message in %s")%(formats.date_format(created.create_date, "SHORT_DATETIME_FORMAT")) } notification = json.dumps(notification) Group("user-%s" % to_user.id).send({'text': notification}) ChatVisualizations.objects.create(viewed = False, message = created, user = to_user) success = str(_('The message was successfull sent!')) return JsonResponse({"message":success}) erro = HttpResponse(str(_("No user selected!"))) erro.status_code = 404 return erro
def form_valid(self, form): message = form.cleaned_data.get('comment') image = form.cleaned_data.get("image") users = (self.request.POST.get('users[]','')).split(",") user = self.request.user subject = self.webpage.topic.subject if (users[0] is not ''): for u in users: to_user = User.objects.get(email=u) talk, create = Conversation.objects.get_or_create(user_one=user,user_two=to_user) created = TalkMessages.objects.create(text=message,talk=talk,user=user,subject=subject,image=image) simple_notify = textwrap.shorten(strip_tags(message), width = 30, placeholder = "...") if image is not '': simple_notify += " ".join(_("[Photo]")) notification = { "type": "chat", "subtype": "subject", "space": subject.slug, "user_icon": created.user.image_url, "notify_title": str(created.user), "simple_notify": simple_notify, "view_url": reverse("chat:view_message", args = (created.id, ), kwargs = {}), "complete": render_to_string("chat/_message.html", {"talk_msg": created}, self.request), "container": "chat-" + str(created.user.id), "last_date": _("Last message in %s")%(formats.date_format(created.create_date, "SHORT_DATETIME_FORMAT")) } notification = json.dumps(notification) Group("user-%s" % to_user.id).send({'text': notification}) ChatVisualizations.objects.create(viewed = False, message = created, user = to_user) success = str(_('The message was successfull sent!')) return JsonResponse({"message":success}) erro = HttpResponse(str(_("No user selected!"))) erro.status_code = 404 return erro
def form_valid(self, form): message = form.cleaned_data.get('comment') image = form.cleaned_data.get("image") users = (self.request.POST.get('users[]','')).split(",") user = self.request.user subject = self.filelink.topic.subject if (users[0] is not ''): for u in users: to_user = User.objects.get(email=u) talk, create = Conversation.objects.get_or_create(user_one=user,user_two=to_user) created = TalkMessages.objects.create(text=message,talk=talk,user=user,subject=subject,image=image) simple_notify = textwrap.shorten(strip_tags(message), width = 30, placeholder = "...") if image is not '': simple_notify += " ".join(_("[Photo]")) notification = { "type": "chat", "subtype": "subject", "space": subject.slug, "user_icon": created.user.image_url, "notify_title": str(created.user), "simple_notify": simple_notify, "view_url": reverse("chat:view_message", args = (created.id, ), kwargs = {}), "complete": render_to_string("chat/_message.html", {"talk_msg": created}, self.request), "container": "chat-" + str(created.user.id), "last_date": _("Last message in %s")%(formats.date_format(created.create_date, "SHORT_DATETIME_FORMAT")) } notification = json.dumps(notification) Group("user-%s" % to_user.id).send({'text': notification}) ChatVisualizations.objects.create(viewed = False, message = created, user = to_user) success = str(_('The message was successfull sent!')) return JsonResponse({"message":success}) erro = HttpResponse(str(_("No user selected!"))) erro.status_code = 404 return erro