def ical(request): """Meetings iCal (ics) feed. """ meetings = Meeting.objects.upcoming() cal = vobject.iCalendar() cal.add('method').vaule = u'PUBLISHED' cal.add('x-wr-calname').value = u"GTALUG" for meeting in meetings: vevent = cal.add('vevent') if meeting.tba: vevent.add('summary').value = u"GTALUG Meeting" else: vevent.add('summary').value = u"GTALUG Meeting - %s" % meeting.topic vevent.add('description').value = u"%s" % striptags(meeting.tease).strip() vevent.add('location').value = u"%s" % striptags(meeting.location).strip() vevent.add('dtstart').value = datetime.datetime.combine(meeting.date, meeting.time) vevent.add('url').value = u'http://gtalug.org%s' % meeting.get_absolute_url() icalstream = cal.serialize() response = HttpResponse(icalstream, mimetype='text/calendar') response['Filename'] = 'gtalug.ics' # F*****g IE needs this response['Content-Disposition'] = 'attachment; filename=gtalug.ics' return response
def update_from_related_object(self): """ Updats the meta data from the related object, returning true if changes have been made. """ if self.content_object: # Populate core fields if the object explicitly defines them if hasattr(self.content_object, 'get_absolute_url'): self.path = self.content_object.get_absolute_url() or self.path if hasattr(self.content_object, 'meta_description'): self.description = striptags(self.content_object.meta_description) or self.description if hasattr(self.content_object, 'meta_keywords'): self.keywords = striptags(self.content_object.meta_keywords) or self.keywords if hasattr(self.content_object, 'meta_title'): self.title = self.content_object.meta_title or self.title # Populate the heading, without overwriting existing data self.heading = self.heading or self.content_object.meta_title # Populate using other, non-meta fields, but never overwrite existing data elif hasattr(self.content_object, 'page_title'): self.title = self.title or self.content_object.page_title self.heading = self.heading or self.content_object.page_title elif hasattr(self.content_object, 'title'): self.title = self.title or self.content_object.title self.heading = self.heading or self.content_object.title return True
def detail_ical(request, year, month, slug=None): try: meeting = Meeting.objects.get(slug__iexact=slug, date__year=year, date__month=month) except Meeting.DoesNotExist: raise Http404 cal = vobject.iCalendar() cal.add('method').vaule = u'PUBLISHED' vevent = cal.add('vevent') if meeting.tba: vevent.add('summary').value = u"GTALUG Meeting" else: vevent.add('summary').value = u"GTALUG Meeting - %s" % meeting.topic vevent.add('description').value = u"%s" % striptags(meeting.tease).strip() vevent.add('location').value = u"%s" % striptags(meeting.location).strip() vevent.add('dtstart').value = datetime.datetime.combine(meeting.date, meeting.time) vevent.add('url').value = u'http://gtalug.org%s' % meeting.get_absolute_url() icalstream = cal.serialize() filename = 'gtalug_%s.ics' % meeting.slug response = HttpResponse(icalstream, mimetype='text/calendar') response['Filename'] = filename # F*****g IE needs this response['Content-Disposition'] = 'attachment; filename=%s' % filename return response
def get_content_snippet2(content, keyword, max_lines=10): max_lines = int(max_lines) p = re.compile( r'(?P<before>.*)%s(?P<after>.*)' % re.escape(keyword), re.MULTILINE | re.IGNORECASE | re.DOTALL) m = p.search(content) html = "" if m: words = list(filter( lambda x: x != "", striptags( m.group("before")).split("\n"))) before_lines = words[-max_lines // 2:] words = list(filter( lambda x: x != "", striptags( m.group("after")).split("\n"))) after = "<br/>".join(words[:max_lines - len(before_lines)]) before = "<br/>".join(before_lines) html = "%s %s %s" % (before, striptags(keyword), after) kw_p = re.compile(r'(%s)' % keyword, re.IGNORECASE) html = kw_p.sub(r"<strong>\1</strong>", html) html = mark_safe(html) else: html = " ".join( list(filter( lambda x: x != "", striptags(content).replace( "\n", " ").split(" ")))[ :max_lines]) return html
def testAuthorTemplate(self): class AuthorHolder(object): def __init__(self, pk, authors): self.pk = pk self.authors = authors def all_authors(self): return self.authors result = (render_to_string('magazine/_authors.html', {'object': AuthorHolder(1, [])})) self.assertEqual(result.strip(), '') result = (render_to_string('magazine/_authors.html', {'object': AuthorHolder(2, [self.paul,])})) self.assertEqual(striptags(result).strip(), 'Paul Beasley-Murray') self.assertNotEqual(result.find(self.paul.get_absolute_url()), -1) self.assertEqual(result.find(self.dom.get_absolute_url()), -1) self.assertEqual(result.find(reverse('magazine_author_detail', args=[self.bugs.pk,])), -1) result = render_to_string('magazine/_authors.html', {'object': AuthorHolder(3, [self.paul,self.dom])}) self.assertEqual(striptags(result).strip(), 'Paul Beasley-Murray and Dominic Rodger') self.assertNotEqual(result.find(self.paul.get_absolute_url()), -1) self.assertNotEqual(result.find(self.dom.get_absolute_url()), -1) self.assertEqual(result.find(reverse('magazine_author_detail', args=[self.bugs.pk,])), -1) result = render_to_string('magazine/_authors.html', {'object': AuthorHolder(4, [self.paul, self.dom, self.bugs])}) self.assertEqual(striptags(result).strip(), 'Paul Beasley-Murray, Dominic Rodger and Bugs') self.assertNotEqual(result.find(self.paul.get_absolute_url()), -1) self.assertNotEqual(result.find(self.dom.get_absolute_url()), -1) # Bugs is not indexable, and so should have a link to his profile self.assertEqual(result.find(reverse('magazine_author_detail', args=[self.bugs.pk,])), -1)
def forum_email_notification(post): try: mail_subject = settings.FORUM_MAIL_PREFIX except AttributeError: me = Site.objects.get_current() mail_subject = "[%s Forums]" % me.name try: mail_from = settings.FORUM_MAIL_FROM except AttributeError: mail_from = settings.DEFAULT_FROM_EMAIL mail_tpl = loader.get_template('forum/notify.txt') c = Context({ 'body': wordwrap(striptags(post.body), 72), 'site' : Site.objects.get_current(), 'thread': post.thread, 'author' : post.author, 'subject' : post.thread.title, }) email = EmailMessage( subject=mail_subject+' '+striptags(post.thread.title), body=mail_tpl.render(c), from_email=mail_from, to=[mail_from], bcc=[s.author.email for s in post.thread.subscription_set.all()]) email.send(fail_silently=True)
def create_snippet(self, title, explanation, code, lang, tags, public=True, active=True): title = striptags(title) explanation = striptags(explanation) code = striptags(code) snippet = Snippet(title=title, slug=slugify(title), explanation=explanation, code=code, lang=lang, public=public, active=active) snippet.save() Tag.objects.update_tags(snippet, tags) return snippet
def create_feedentry(self, title, desc, url, feed): print 'title:%s' % title feedentry = self.exists(url=url) if not feedentry: title = striptags(title) desc = striptags(desc) feedentry = FeedEntry(title=title, slug=slugify(title), desc=desc, url=url, feed=feed) feedentry.save() return feedentry
def sold(self): from sell.models import Cart from preferences.models import EmailNotification from django.core.mail import send_mail from django.conf import settings from django.template import Context, Template self.state = "S" self.save() cart = Cart.objects.filter(shop=self.shop, bidder=self.bid_actual.bidder).get() cart.add(self, self.current_bid(), 1) # ------------------------------------------------------------------------ # Send an email to bidder to notify he/she has won the auction c = Context( { "bidder_name": self.bid_actual.bidder.get_full_name(), "bid_amount": self.bid_actual.bid_amount, "bid_time": self.bid_actual.bid_time, "shop": self.shop.name, "session_title": self.session.title, "session_description": striptags(self.session.description), "session_start": str(self.session.start), "session_end": str(self.session.end), "lot_title": self.title, "lot_description": striptags(self.description), } ) admin_email = self.shop.marketplace.contact_email try: notification = EmailNotification.objects.filter(type_notification="AWC", shop=self.shop).get() subj_template = Template(notification.subject) body_template = Template(notification.body) subj_text = subj_template.render(c) body_text = body_template.render(c) send_mail(subj_text, body_text, settings.EMAIL_FROM, [self.bid_actual.bidder.email], fail_silently=True) except EmailNotification.DoesNotExist: msg = ( "You made a bid u$s %s for %s and have won the auction!. Please contact %s to get more details about this purchase. Thanks" % (self.bid_actual.bid_amount, self.title, self.shop.admin.email) ) send_mail("Congratulations!!", msg, settings.EMAIL_FROM, [self.bid_actual.bidder.email], fail_silently=True) except Exception, e: send_mail( "Could not send email to lot winner!", "Message could not be delivered to %s" % self.bid_actual.bidder.email, settings.EMAIL_FROM, [mail for (name, mail) in settings.STAFF] + [admin_email], fail_silently=True, )
def errors_as_json(self, strip_tags=False): error_summary = {} errors = {} for error in self.errors.iteritems(): if self.prefix: errors.update({self.prefix + '-' + error[0]: unicode(striptags(error[1]) \ if strip_tags else error[1])}) else: errors.update({error[0]: unicode(striptags(error[1]) \ if strip_tags else error[1])}) error_summary.update({'errors': errors}) return error_summary
def social_share(): orain = datetime.datetime.now() berriak = Berria.objects.filter(Q(pub_date__lte=orain) & Q(status='1') & Q(shared=False)).order_by('-pub_date') gpak = GamePlaya.objects.filter(Q(pub_date__lte=orain) & Q(status='1') & Q(shared=False)).order_by('-pub_date') atalak = Atala.objects.filter(Q(pub_date__lte=orain) & Q(publikoa_da=True) & Q(shared=False)).order_by('-pub_date') txak = Txapelketa.objects.filter(Q(pub_date__lte=orain) & Q(publikoa_da=True) & Q(shared=False)).order_by('-pub_date') for berria in berriak: post_social(berria) berria.shared=True berria.save() l = Log() l.mota = 'Albistea' l.tituloa = berria.izenburua l.fetxa =datetime.datetime.now() l.user = berria.erabiltzailea l.deskripzioa = filters.striptags(berria.desk)[:400]+'...' l.berria = berria l.save() for gp in gpak: post_social(gp) gp.shared=True gp.save() l = Log() l.mota = 'GP' l.tituloa = gp.izenburua l.fetxa =datetime.datetime.now() l.user = gp.erabiltzailea l.deskripzioa = filters.striptags(gp.desk)[:400]+'...' l.gameplaya = gp l.save() for atal in atalak: post_social(atal) atal.shared=True atal.save() for tx in txak: post_social(tx) tx.shared=True tx.save() return True
def stripped_summary(self): stripped_summary = striptags(self.introduction).replace(' ', '').strip() whitespace_pattern = re.compile('^\s*$') if not stripped_summary or whitespace_pattern.match(stripped_summary): if self.has_sections(): stripped_summary = self.archivearticlesection_set.all()[0].body else: stripped_summary = self.content stripped_summary = striptags(stripped_summary).replace(' ','').strip()[0:settings.ARTICLE_SUMMARY_LENGTH] + '...' return stripped_summary
def render_to_email(subject_template, body_template, context, to, from_email): """ Renders the given templates as an EmailMessage, with plaintext and HTML alternatives. """ subject = striptags(subject_template.render(context)) body = striptags(body_template.render(context)) msg = EmailMultiAlternatives(subject, body, from_email, to) html_body = markdown.markdown(body, output_format="html5") msg.attach_alternative(html_body, "text/html") return msg
def graphs_solution(request, real_solution_id, JSON=True, safe=False): #Check premissions needed_solution = Solution.objects.get(id=real_solution_id) graphs_solution_info_add = {} try: tags = [] for tag in needed_solution.tags.all(): tags.append(tag.name) except: pass owner = needed_solution.owner is_external = False licenses = {} for license in needed_solution.source.licenses.all(): licenses[license.license] = license.license_url source = { 'source': '%s'%needed_solution.source.source, 'image': '%s'%needed_solution.source.image, 'url': '%s'%needed_solution.source.url, 'licenses': licenses} try: vote = Vote.objects.get(is_deleted=False, solution=needed_solution, user=request.user) sol_user_accept_rate = int(vote.vote) sol_user_is_voted = True except: sol_user_accept_rate = 0 sol_user_is_voted = False try: sol_votes_count = needed_solution.votes_count sol_votes = needed_solution.votes_sum sol_accept_rate = float(sol_votes)/int(sol_votes_count) except: sol_accept_rate = 0 sol_votes_count = 0 from django.template.defaultfilters import striptags, timesince from solutioner.templatetags.templatetags.truncatechars import truncatechars problem = striptags(needed_solution.problem) if safe else sanitize(needed_solution.problem) problem_desc = sanitize(truncatechars(striptags(needed_solution.problem_desc),300)) if safe else sanitize(needed_solution.problem_desc) solution = sanitize(truncatechars(striptags(needed_solution.solution),300)) if safe else sanitize(needed_solution.solution) datetime_added_since = timesince(needed_solution.datetime_added) graphs_solution_info = {'id': needed_solution.id, 'is_external': is_external, 'tags': tags, 'problem': '%s'%problem, 'problem_desc': '%s'%problem_desc, 'solution': '%s'%solution, 'datetime_added': '%s'%needed_solution.datetime_added, 'datetime_added_since': '%s'%datetime_added_since, 'viewed': '%s'%needed_solution.viewed, 'source': source, 'category': '%s'%needed_solution.category.name, 'sol_accept_rate': int(sol_accept_rate),'sol_user_accept_rate': int(sol_user_accept_rate), 'sol_user_is_voted': sol_user_is_voted, 'sol_votes_count': sol_votes_count} graphs_solution_info.update(graphs_solution_info_add) if JSON == True: return HttpResponse(simplejson.dumps(graphs_solution_info, sort_keys=True, indent=4), content_type = 'application/json') elif JSON == 'JSON_ready': return graphs_solution_info else: graphs_solution_info['datetime_added'] = needed_solution.datetime_added return graphs_solution_info
def get_summary(self): summary = '' if len(self.summary): summary = self.summary else: contents = self.contents.all() if len(contents) > 0: summary = contents[0].content summary = striptags(mark_safe(summary)) summary = summary.replace(' ', '') summary = summary.replace('”','') summary = summary.replace('“','') summary = summary.replace('\r','') summary = summary.replace('\n','') return striptags(summary)
def compress_html(value, html=1): ssbt = strip_spaces_between_tags(value.strip()) ssbt = RE_MULTISPACE.sub(" ", ssbt) ssbt = RE_NEWLINE.sub("", ssbt) if html == 0: ssbt = striptags( ssbt ) return ssbt
def highlight_block(match): lang = match.group(2) code = format_code(html_entity_decode(striptags(match.group(3))), lang) if code is None: return ''.join((match.group(1), match.group(3), match.group(4))) else: return match.group(1) + code + match.group(4)
def get_blog_items(): # c/o http://stackoverflow.com/questions/1208916/decoding-html-entities-with-python import re def _callback(matches): id = matches.group(1) try: return chr(int(id)) except: return id def decode_unicode_references(data): return re.sub("&#(\d+)(;|(?=\s))", _callback, data) # Fetch from Atom feed. import feedparser feed = feedparser.parse("https://govtracknews.wordpress.com/feed/atom/") from django.template.defaultfilters import truncatewords, striptags # Yield dicts. for i, entry in enumerate(feed["entries"]): if i >= 2: return yield { "url": entry.link, "title": decode_unicode_references(entry.title), "published": datetime(*entry.updated_parsed[0:6]), "snippet": truncatewords(striptags(decode_unicode_references(entry.content[0].value)), 30) }
def save(self, *args, **kwargs): """ if not self.allow_comments: if self.is_page: self.allow_comments = False else: self.allow_comments = True """ self.content_plain = escape(striptags(force_unicode(self.content))) super(Post, self).save(*args, **kwargs) if self.is_page or self.category.noblog(): self.tags = '' if not self.meta_description: self.meta_description = self.content_plain.replace('"','') if not self.meta_keywords: self.meta_keywords = u",".join([tag.name for tag in self.tags.all()]) if not self.publication_date: self.publication_date = self.pub_date return super(Post, self).save(*args, **kwargs)
def update_object(request, method='json', *args, **kwargs): if method == 'json' and request.method == 'POST': login_required = kwargs.get('login_required') model = kwargs.get('model') form_class = kwargs.get('form_class') object_id = kwargs.get('object_id') slug = kwargs.get('slug') slug_field = kwargs.get('slug_field', 'slug') if login_required and not request.user.is_authenticated(): return JsonResponse({'status': 'denied'}) model, form_class = create_update.get_model_and_form_class(model, form_class) obj = create_update.lookup_object(model, object_id, slug, slug_field) if request.method == 'POST': if issubclass(form_class, ModelFormWithRequest): form = form_class(request, request.POST, request.FILES, instance=obj) else: form = form_class(request.POST, request.FILES, instance=obj) if form.is_valid(): obj = form.save() #msg = ugettext("The %(verbose_name)s was updated successfully.") %\ # {"verbose_name": model._meta.verbose_name} #messages.success(request, msg, fail_silently=True) return JsonResponse({'status': 'ok', 'instance': get_instance_json(obj)}) else: errors = [unicode(striptags("%s: %s" % (k, v))) for k, v in form.errors.iteritems()] return JsonResponse({'status': 'failed', 'errors': errors}) else: return create_update.update_object(request, *args, **kwargs)
def bidding_view_item(request, id): #TODO: filter by state lot #TODO: add csrf_token to form item = get_object_or_404(Item, pk=id) request.shop.add_view() t = loader.get_template('bidding/blocks/view_item_form.html') c = RequestContext(request, {'item': item}) block_view_item_form = (t.render(c)) images = [] for img in item.imageitem_set.all(): images.append({'original': img.image.url if img else None, 'small': img.image.url_100x100 if img else None, 'medium': img.image.url_400x400 if img else None, }) param = { 'item': {'title': item.title, 'category': item.category.name, 'subcategory': item.subcategory.name if item.subcategory else "", 'title': item.title, 'description': item.description, }, 'form': block_view_item_form, 'images': images, 'page_title': item.title, 'page_description': '%s, %s' % (item.title, striptags(item.description)) } return HttpResponse(my_render(request, param, 'view_item'))
def handle(self, *args, **options): ''' Defines a function which scrapes the permalink URLs for RSS items to get body text. ''' for item in FeedItem.objects.filter(guid="false"): try: response = urllib2.urlopen(item.xml_url) html = response.read() soup = BeautifulSoup(html) body = striptags(soup.findAll(re.compile('^ece:field'))[0]) body = body.replace("\n", "").replace("\r", "") item.content = body item.guid = "true" item.save() print "Updated %s" % item except: print "Turns out, this isn't a story." for item in FeedItem.objects.filter(guid="true"): response = urllib2.urlopen(item.xml_url) html = response.read() soup = BeautifulSoup(html) try: image = soup.findAll(re.compile('^ece:multimediagroup'))[:1][0] image = image.findAll(re.compile('^ece:multimedia'))[0]['filename'] item.lead_image_url = image item.save() print "Imaged %s" % item except: print "This one doesn't have an image."
def test_non_string_input(self): # Filters shouldn't break if passed non-strings self.assertEqual(addslashes(123), '123') self.assertEqual(linenumbers(123), '1. 123') self.assertEqual(lower(123), '123') self.assertEqual(make_list(123), ['1', '2', '3']) self.assertEqual(slugify(123), '123') self.assertEqual(title(123), '123') self.assertEqual(truncatewords(123, 2), '123') self.assertEqual(upper(123), '123') self.assertEqual(urlencode(123), '123') self.assertEqual(urlize(123), '123') self.assertEqual(urlizetrunc(123, 1), '123') self.assertEqual(wordcount(123), 1) self.assertEqual(wordwrap(123, 2), '123') self.assertEqual(ljust('123', 4), '123 ') self.assertEqual(rjust('123', 4), ' 123') self.assertEqual(center('123', 5), ' 123 ') self.assertEqual(center('123', 6), ' 123 ') self.assertEqual(cut(123, '2'), '13') self.assertEqual(escape(123), '123') self.assertEqual(linebreaks_filter(123), '<p>123</p>') self.assertEqual(linebreaksbr(123), '123') self.assertEqual(removetags(123, 'a'), '123') self.assertEqual(striptags(123), '123')
def to_native(self, obj): """ Serialize objects -> primitives. """ ret = self._dict_class() ret.fields = self._dict_class() ret.empty = obj is None #set_project_locale() for field_name, field in self.fields.items(): if not field_name in settings.ALLOW_TICKET_FIELDS: continue field.initialize(parent=self, field_name=field_name) key = self.get_field_key(field_name) value = field.field_to_native(obj, field_name) if value: if field_name in ['subject', 'text']: value = striptags(value) ret[key] = value ret.fields[key] = field #if self.user.pk == obj.manager return ret
def menu_edit(request): current_site = get_current_site(request) try: menu = Menu.objects.get(site=current_site).json_tree except Menu.DoesNotExist: menu = '[{"title": "", "description": "", "url": ""}]' if request.method =='POST': try: Menu.objects.get(site=current_site).delete() except Menu.DoesNotExist: pass menu = striptags(request.POST.get('menudata')) menu_obj = Menu(json_tree=menu, site_id=current_site.id) menu_obj.save() request.session['success'] = True cache.set('sitemenus_' + current_site.domain, render_menu(current_site), sys.maxint) return redirect('sitemenus_menu_edit') success = request.session.get('success') if success: del request.session['success'] return render(request, 'sitemenus/sitemenus_edit.html', { 'menu': menu, 'success': success })
def render(self, context): self.title = template.Variable(self.title) request = context['request'] getvars = request.GET.copy() try: self.title = force_unicode(self.title.resolve(context)) except (template.VariableDoesNotExist, UnicodeEncodeError): self.title = self.title.var if 'sort' in getvars: sortby = getvars['sort'] del getvars['sort'] else: sortby = '' if 'dir' in getvars: sortdir = getvars['dir'] del getvars['dir'] else: sortdir = '' if sortby == self.fields: getvars['dir'] = sort_directions[sortdir]['inverse'] icon = sort_directions[sortdir]['icon'] else: icon = '' if len(getvars.keys()) > 0: urlappend = "&%s" % getvars.urlencode() else: urlappend = '' if icon: title = "%s %s" % (self.title, icon) else: title = self.title url = '%s?sort=%s%s' % (request.path, self.fields, urlappend) return '<a href="%s" title="%s">%s</a>' % (url, striptags(self.title), title)
def test_removetags(self): self.assertEqual(removetags('some <b>html</b> with <script>alert' '("You smell")</script> disallowed <img /> tags', 'script img'), 'some <b>html</b> with alert("You smell") disallowed tags') self.assertEqual(striptags('some <b>html</b> with <script>alert' '("You smell")</script> disallowed <img /> tags'), 'some html with alert("You smell") disallowed tags')
def send(self, to_addresses, context={}, attachments=None, headers=None): html_body = self.render(context) text_body = self.render_txt(context) or striptags(html_body) subject = self._render_from_string(self.subject, context) if isinstance(to_addresses, (str,unicode)): to_addresses = (to_addresses,) whitelisted_email_addresses = getattr(settings, 'EMAILTEMPLATES_DEBUG_WHITELIST', []) if getattr(settings, 'EMAILTEMPLATES_DEBUG', False): # clean non-whitelisted emails from the to_address cleaned_to_addresses = [] for address in to_addresses: try: email_domain = address.split('@')[1] except IndexError: email_domain = None if email_domain in whitelisted_email_addresses or address in whitelisted_email_addresses: cleaned_to_addresses.append(address) to_addresses = cleaned_to_addresses msg = EmailMultiAlternatives(subject, text_body, self.visible_from_address(), to_addresses, headers=headers) msg.attach_alternative(html_body, "text/html") if attachments is not None: for attach in attachments: msg.attach(*attach) return msg.send()
def clean(self, value): """ Call the form is_valid to ensure every value supplied is valid """ if not value and self.required: raise ValidationError( 'Error found in Form Field: Nothing to validate') if not value: return #if we have an integer, assume that it is a foreignkey relationship. if(isinstance(value,int) and self.related): instance = self.related.objects.get(pk=value) if(issubclass(self.form.__class__,ModelForm)): form = self.form.__class__(instance.__dict__,instance=instance) else: # gather files form = self.form.__class__(instance.__dict__) else: data = dict((bf.name, value[i]) for i, bf in enumerate(self.form) if value[i]) files = dict((k,v) for k, v in data.iteritems() if isinstance(v,UploadedFile)) form = self.form.__class__(data,files=files) if not form.is_valid(): error_dict = form.errors.items() errors = striptags( ", ".join(["%s (%s)" % (v, k) for k, v in error_dict])) raise ValidationError('Error(s) found: %s' % errors) elif self.related: form.save() return form.instance else: #return [ form.cleaned_data.get(f,None) for f in form.fields ] return form.cleaned_data
def _convert_to_dict(post): return { 'Title': post.Title, 'Shortcut': post.Shortcut, 'Repr' : truncatewords_html(striptags(post.Content), 20), 'CreationDateTime': date(post.CreationDateTime, "j F Y") }
def ticket_from_message(message, queue, quiet): # 'message' must be an RFC822 formatted message. msg = message message = email.message_from_string(msg) subject = message.get('subject', _('Created from e-mail')) subject = decode_mail_headers(decodeUnknown(message.get_charset(), subject)) subject = subject.replace("Re: ", "").replace("Fw: ", "").replace( "RE: ", "").replace("FW: ", "").replace("Automatic reply: ", "").strip() sender = message.get('from', _('Unknown Sender')) sender = decode_mail_headers(decodeUnknown(message.get_charset(), sender)) sender_email = parseaddr(sender)[1] body_plain, body_html = '', '' for ignore in IgnoreEmail.objects.filter( Q(queues=queue) | Q(queues__isnull=True)): if ignore.test(sender_email): if ignore.keep_in_mailbox: # By returning 'False' the message will be kept in the mailbox, # and the 'True' will cause the message to be deleted. return False return True matchobj = re.match(r".*\[" + queue.slug + "-(?P<id>\d+)\]", subject) if matchobj: # This is a reply or forward. ticket = matchobj.group('id') else: ticket = None counter = 0 files = [] for part in message.walk(): if part.get_content_maintype() == 'multipart': continue name = part.get_param("name") if name: name = collapse_rfc2231_value(name) if part.get_content_maintype() == 'text' and name is None: if part.get_content_subtype() == 'plain': body_plain = EmailReplyParser.parse_reply( decodeUnknown(part.get_content_charset(), part.get_payload(decode=True))) else: body_html = part.get_payload(decode=True) # make plain text more legible when viewing the ticket body_html, n = re.subn(r'[\r\n]+', r'', body_html) body_html, n = re.subn(r'\>\s+\<', r'><', body_html) body_html = body_html.replace("</h1>", "</h1>\n") body_html = body_html.replace("</h2>", "</h2>\n") body_html = body_html.replace("</h3>", "</h3>\n") body_html = body_html.replace("<p>", "\n<p>") body_html = body_html.replace("</p>", "</p>\n") body_html = body_html.replace("</div>", "</div>\n") body_html = body_html.replace("</tr>", "</tr>\n") body_html = body_html.replace("</td>", "</td> ") body_html = body_html.replace("<table>", "\n<table>") body_html = body_html.replace("</table>", "</table>\n") body_html = body_html.replace("<br />", "<br />\n") try: # strip html tags body_plain = striptags(body_html) except DjangoUnicodeDecodeError: charset = chardet.detect(body_html)['encoding'] body_plain = striptags(str(body_html, charset)) body_plain = unescape(body_plain) else: if not name: ext = mimetypes.guess_extension(part.get_content_type()) name = "part-%i%s" % (counter, ext) files.append( { 'filename': name, 'content': part.get_payload(decode=True), 'type': part.get_content_type() }, ) counter += 1 if body_plain: body = body_plain if body_html: body += '\n\n' body += _( '***Note that HTML tags are stripped out. Please see attachment email_html_body.html for the full html content.' ) else: body = _( 'No plain-text email body available. Please see attachment email_html_body.html.' ) if body_html: files.append({ 'filename': _("email_html_body.html"), 'content': body_html, 'type': 'text/html', }) now = timezone.now() if ticket: try: t = Ticket.objects.get(id=ticket) new = False except Ticket.DoesNotExist: ticket = None priority = 3 smtp_priority = message.get('priority', '') smtp_importance = message.get('importance', '') high_priority_types = ('high', 'important', '1', 'urgent') if smtp_priority in high_priority_types or smtp_importance in high_priority_types: priority = 2 if ticket is None: t = Ticket( title=subject, queue=queue, submitter_email=sender_email, created=now, description=body, priority=priority, ) t.save() new = True #update = '' elif t.status == Ticket.CLOSED_STATUS: t.status = Ticket.REOPENED_STATUS t.save() f = FollowUp( ticket=t, title=_('E-Mail Received from %(sender_email)s' % {'sender_email': sender_email}), date=timezone.now(), public=True, comment=body, ) if t.status == Ticket.REOPENED_STATUS: f.new_status = Ticket.REOPENED_STATUS f.title = _( 'Ticket Re-Opened by E-Mail Received from %(sender_email)s' % {'sender_email': sender_email}) f.save() if not quiet: print((" [%s-%s] %s" % ( t.queue.slug, t.id, t.title, )).encode('ascii', 'replace')) for file in files: if file['content']: filename = file['filename'].encode('ascii', 'replace').replace(' ', '_') filename = re.sub('[^a-zA-Z0-9._-]+', '', filename) a = Attachment( followup=f, filename=filename, mime_type=file['type'], size=len(file['content']), ) a.file.save(filename, ContentFile(file['content']), save=False) a.save() if not quiet: print(" - %s" % filename) context = safe_template_context(t) if new: if sender_email: send_templated_mail( 'newticket_submitter', context, recipients=sender_email, sender=queue.from_address, fail_silently=True, ) if queue.new_ticket_cc: send_templated_mail( 'newticket_cc', context, recipients=queue.new_ticket_cc, sender=queue.from_address, fail_silently=True, ) if queue.updated_ticket_cc and queue.updated_ticket_cc != queue.new_ticket_cc: send_templated_mail( 'newticket_cc', context, recipients=queue.updated_ticket_cc, sender=queue.from_address, fail_silently=True, ) else: context.update(comment=f.comment) #if t.status == Ticket.REOPENED_STATUS: # update = _(' (Reopened)') #else: # update = _(' (Updated)') if t.assigned_to: send_templated_mail( 'updated_owner', context, recipients=t.assigned_to.email, sender=queue.from_address, fail_silently=True, ) if queue.updated_ticket_cc: send_templated_mail( 'updated_cc', context, recipients=queue.updated_ticket_cc, sender=queue.from_address, fail_silently=True, ) return t
def _format_description(description): if description: return truncatewords(striptags(description), 12) return ''
def deliver(self, user, versions, actions): if not user.email: return from_email = getattr(settings, 'DEFAULT_FROM_EMAIL') site = Site.objects.get_current() if 'long' in versions: body = versions['long'] elif 'long_plain' in versions: body = versions['long_plain'] elif 'long_html' in versions: body = striptags(markdown(versions['long_html'])) elif 'short' in versions: body = versions['short'] elif 'short_plain' in versions: body = versions['short_plain'] elif 'short_html' in versions: body = striptags(markdown(versions['short_html'])) media_url = settings.MEDIA_URL static_url = getattr(settings, 'STATIC_URL', '/static') if media_url.startswith('//'): media_url = 'http:%s' % media_url elif not (media_url.startswith('http://') or media_url.startswith('https://')): media_url = 'http://%s%s' % (site.domain, media_url) if static_url.startswith('//'): static_url = 'http:%s' % static_url elif not (static_url.startswith('http://') or static_url.startswith('https://')): static_url = 'http://%s%s' % (site.domain, static_url) ctx = { 'MEDIA_URL': media_url, 'STATIC_URL': static_url, 'SITE': site, 'body': body, 'actions': actions } if ctx['MEDIA_URL'].startswith('/'): ctx['MEDIA_URL'] = 'http://%s%s' % (ctx['SITE'].domain, ctx['MEDIA_URL']) email = EmailMultiAlternatives( versions.get('short_plain') or striptags(markdown(versions.get('short'))) or striptags(versions.get('short_html')), render_to_string('notifications/mail/base.txt', ctx), from_email, ['%s <%s>' % (user.get_full_name() or user.username, user.email)]) if 'long_html' in versions: ctx['body'] = mark_safe(versions['long_html']) elif 'long' in versions: ctx['body'] = markdown(versions['long']) elif 'long_plain' in versions: ctx['body'] = linebreaks(versions['long_plain']) elif 'short_html' in versions: ctx['body'] = mark_safe(versions['short_html']) elif 'short' in versions: ctx['body'] = markdown(versions['short']) elif 'short_plain' in versions: ctx['body'] = linebreaks(versions['short_plain']) email.attach_alternative( render_to_string('notifications/mail/base.html', ctx), "text/html") try: email.send() except: pass
def implosivo(value): # like explosivo but it renders the page as plain text return striptags(explosivo(value))
def extract_text(self): # return the rendered content, with HTML tags stripped. html = render_content_items(request=None, items=self.contentitem_set.all()) return striptags(html)
def bidding_auctions(request, session_id=None): if session_id: session = get_object_or_404(AuctionSession, pk=session_id) lots = Lot.objects.filter(shop=request.shop, session=session, state='A') session_title = session.title else: session_title = 'Highlights' lots = Lot.objects.filter(shop=request.shop, state='A') pager = Paginator(lots, PAGE_LOTS) try: page = int(request.GET.get('page', '1')) except: page = 1 try: lots = pager.page(page) except (EmptyPage, InvalidPage): lots = pager.page(pager.num_pages) paged = (pager.num_pages > 1) lots_list = [] for lot in lots.object_list: image = lot.image() lots_list.append({ 'url': reverse('bidding_view_lot', args=[lot.id]), 'title': lot.title, 'price': money_format(lot.price(), request.shop), 'image': { 'original': image.image.url if image else None, 'small': image.image.url_100x100 if image else None, 'medium': image.image.url_400x400 if image else None, } }) sessions = AuctionSession.objects.filter(shop=request.shop, end__gte=datetime.now()) shop_categories = request.shop.categories_list() shop_subcategories = request.shop.sub_categories_list() t = loader.get_template('bidding/blocks/sessions.html') c = RequestContext(request, {'sessions': sessions}) block_sessions = (t.render(c)) t = loader.get_template('paginator.html') c = RequestContext(request, { 'objects': lots, 'pages': pager.page_range, 'paged': paged, }) paginator = (t.render(c)) try: page = DynamicPageContent.objects.filter(shop=request.shop, page="auctions").get() description = striptags(page.meta_content) except DynamicPageContent.DoesNotExist: description = "No meta description found" param = { 'lots': lots_list, 'sessions': block_sessions, 'session_title': session_title, 'paginator': paginator, 'page_title': 'Auctions', 'page_description': description, 'shop_categories': shop_categories, 'shop_subcategories': shop_subcategories, } return HttpResponse(my_render(request, param, 'auctions'))
def simplify(text): return linebreaks(urlizetrunc(striptags(text), 60))
def item_title(self, notification): return striptags(notification.message)
def reply(request, thread): """ If a thread isn't closed, and the user is logged in, post a reply to a thread. Note we don't have "nested" replies at this stage. """ if not request.user.is_authenticated(): return HttpResponseRedirect('%s?next=%s' % (LOGIN_URL, request.path)) t = get_object_or_404(Thread, pk=thread) if t.closed: return HttpResponseServerError() if not Forum.objects.has_access(t.forum, request.user.groups.all()): return HttpResponseForbidden() if request.method == "POST": form = ReplyForm(request.POST) if form.is_valid(): body = form.cleaned_data['body'] p = Post( thread=t, author=request.user, body=body, time=datetime.now(), ) p.save() sub = Subscription.objects.filter(thread=t, author=request.user) if form.cleaned_data.get('subscribe', False): if not sub: s = Subscription(author=request.user, thread=t) s.save() else: if sub: sub.delete() if t.subscription_set.count() > 0: # Subscriptions are updated now send mail to all the authors subscribed in # this thread. mail_subject = '' try: mail_subject = settings.FORUM_MAIL_PREFIX except AttributeError: mail_subject = '[Forum]' mail_from = '' try: mail_from = settings.FORUM_MAIL_FROM except AttributeError: mail_from = settings.DEFAULT_FROM_EMAIL mail_tpl = loader.get_template('forum/notify.txt') c = Context({ 'body': wordwrap(striptags(body), 72), 'site': Site.objects.get_current(), 'thread': t, }) email = EmailMessage( subject=mail_subject + ' ' + striptags(t.title), body=mail_tpl.render(c), from_email=mail_from, bcc=[s.author.email for s in t.subscription_set.all()], ) email.send(fail_silently=True) return HttpResponseRedirect(p.get_absolute_url()) else: form = ReplyForm() return render_to_response( 'forum/reply.html', RequestContext(request, { 'form': form, 'forum': t.forum, 'thread': t, }))
def _get_word_count(self): """Stupid word counter for an article.""" return len(striptags(self.rendered_content).split(' '))
def format_description(description): return truncatechars(striptags(description), 127) if description else ''
def value(self, obj): val = super(StringField, self).value(obj) if val is None: return None return striptags(val)
def bidding_home(request): from shops.forms import MailingListMemberForm logging.critical(request.GET.get("u", None)) shop = request.shop if request.method == "POST": form = MailingListMemberForm(request.POST) if form.is_valid(): member = form.save(commit=False) member.shop = shop member.save() request.flash['message'] = unicode( _("Email successfully registered.")) request.flash['severity'] = "success" return HttpResponseRedirect(reverse("home")) else: form = MailingListMemberForm() t = loader.get_template('bidding/blocks/mailing_list_form.html') c = RequestContext(request, {'form': form}) block_mailing_list = (t.render(c)) home = Home.objects.filter(shop=request.shop).get() #TODO: replace collections """ news_items """ items = Item.objects.filter(shop=request.shop).order_by('-id')[:10] new_items = [] for i in items: image = i.image() new_items.append({ 'title': i.title, 'description': i.description, 'price': money_format(i.price, request.shop), 'url': reverse('bidding_view_item', args=[i.id]), 'image': { 'original': image.image.url if image else "", 'small': image.image.url_100x100 if image else "", 'medium': image.image.url_400x400 if image else "", } }) last = request.shop.last_post() if last: last_post = { 'url': reverse('bidding_view_post', args=[last.id]), 'title': last.title, 'body': last.body, 'date_time': date(last.date_time, 'F j, Y'), } else: last_post = {} """ Sessions """ sessions = AuctionSession.objects.filter(shop=request.shop, end__gte=datetime.now()) new_sessions = [] new_sessions.append({ 'title': 'Highligths', 'url': reverse('bidding_auctions') }) for session in sessions: new_sessions.append({ 'title': session.title, 'url': reverse('bidding_auctions_id', args=[session.id]), }) about = request.shop.about.body param = { 'about': about, 'home': { 'title': home.title, 'body': home.body, 'image': home.image }, 'new_items': new_items, 'mailing_list': block_mailing_list, 'page_title': 'Home', 'page_title': 'Home', 'page_description': striptags(home.meta_content), 'sessions': new_sessions, 'url_refund': reverse('bidding_refund'), 'url_privacy_policy': reverse('bidding_privacy_policy'), 'url_terms_of_service': reverse('bidding_terms_of_service'), } return HttpResponse(my_render(request, param, 'home'))
def item_title(self, item): return striptags(item.title)
def bidding_search(request): """ """ query = '' form = BiddingSearchForm(shop=request.shop, data=request.GET) if form.is_valid(): query = form.get_query() results = form.search() else: results = form.all_results() pager = Paginator(results, PAGE_SEARCH) try: page = int(request.GET.get('page', '1')) except: page = 1 try: products = pager.page(page) except (EmptyPage, InvalidPage): products = pager.page(pager.num_pages) paged = (pager.num_pages > 1) t = loader.get_template('bidding/blocks/search.html') c = RequestContext( request, { 'form': form, 'products': products, 'pages': pager.page_range, 'paged': paged }) block_search = (t.render(c)) getvars = "&q=%s" % form.cleaned_data.get("q") t = loader.get_template('paginator.html') filter_params = {'q': form.cleaned_data.get("q", '')} c = RequestContext( request, { 'objects': products, 'getvars': getvars, 'filter_params': filter_params, 'pages': pager.page_range, 'paged': paged }) paginator = (t.render(c)) try: page = DynamicPageContent.objects.filter(shop=request.shop, page="search").get() description = striptags(page.meta_content) except DynamicPageContent.DoesNotExist: description = "No meta description found" return HttpResponse( my_render( request, { 'results': block_search, 'paginator': paginator, 'page_title': 'Search', 'page_description': description }, 'search'))
def get_excerpt(self): return truncatewords( embed_videos(html.unescape(striptags(self.content)), strip=True), 55)
def article_body(self, obj): content = truncatewords(striptags(obj.body), 15) return content
def get_summary(self): summary = self.summary or striptags(truncate_paragraphs(self.content, 1)) return truncatewords(summary, 15)
def __str__(self): return self.h1 or truncatechars(striptags(self.text), 20) or str( self.pk)
def short_title_en(self): return truncatechars(striptags(self.title_en), 50)
def clean_html(text): outstr = striptags(text, REMOVE_TAGS) for attr in REMOVE_ATTRIBUTES: for rm in re.findall(' ' + attr + '=".*?"', outstr): outstr = outstr.replace(rm, '') return outstr
def short_content_en(self): return truncatechars(striptags(self.content_en), 100)
def update_chapter_word_count(sender, instance, **kw): from django.template import defaultfilters as filters instance.words = filters.wordcount(filters.striptags(instance.text))
def test_non_string_input(self): self.assertEqual(striptags(123), '123')
def import_page(self, api, site, page, current_site, url_root, user_matching, replace_existing): import pypandoc # Filter titles, to avoid stranges charaters. title = only_printable(page.title) urltitle = slugify(only_printable(urllib.unquote(page.urltitle))[:50]) added = 1 while urltitle in self.articles_worked_on: title = only_printable(page.title) + " " + str(added) urltitle = only_printable( slugify((urllib.unquote(page.urltitle))[:47] + " " + str(added))) added += 1 self.articles_worked_on.append(urltitle) print("Working on %s (%s)" % (title, urltitle)) # Check if the URL path already exists try: urlp = URLPath.objects.get(slug=urltitle) self.matching_old_link_new_link[ page.title] = urlp.article.get_absolute_url() if not replace_existing: print("\tAlready existing, skipping...") return print("\tDestorying old version of the article") urlp.article.delete() except URLPath.DoesNotExist: pass # Create article article = Article() for history_page in page.getHistory()[-2:][::-1]: try: if history_page['user'] in user_matching: user = get_user_model().objects.get( pk=user_matching[history_page['user']]) else: user = get_user_model().objects.get( username=history_page['user']) except get_user_model().DoesNotExist: print( "\tCannot found user with username=%s. Use --user-matching \"%s:<user_pk>\" to manualy set it" % ( history_page['user'], history_page['user'], )) user = None article_revision = ArticleRevision() article_revision.content = pypandoc.convert( history_page['*'], 'md', 'mediawiki') article_revision.title = title article_revision.user = user article_revision.owner = user article.add_revision(article_revision, save=True) article_revision.created = history_page['timestamp'] article_revision.save() # Updated lastest content WITH expended templates # TODO ? Do that for history as well ? article_revision.content = pypandoc.convert( striptags(page.getWikiText(True, True).decode('utf-8')).replace( '__NOEDITSECTION__', '').replace('__NOTOC__', ''), 'md', 'mediawiki') article_revision.save() article.save() upath = URLPath.objects.create(site=current_site, parent=url_root, slug=urltitle, article=article) article.add_object_relation(upath) self.matching_old_link_new_link[ page.title] = upath.article.get_absolute_url() self.articles_imported.append((article, article_revision))
class Course(PhotosMixin, ToolsMixin, FilesMixin, models.Model): name = models.CharField(max_length=64) slug = property(lambda self: slugify(self.name)) active = models.BooleanField( default=True) # only used with the reshedule view _ht = "Used for the events page." short_name = models.CharField(max_length=64, null=True, blank=True, help_text=_ht) get_short_name = lambda self: self.short_name or self.name subjects = models.ManyToManyField(Subject) no_discount = models.BooleanField(default=False) @cached_property def first_room(self): return (self.courseroomtime_set.all() or [self])[0].room presentation = models.BooleanField("Evaluate Presentation", default=True) visuals = models.BooleanField("Evaluate Visuals", default=True) content = models.BooleanField("Evaluate Content", default=True) _ht = "The dashboard (/admin/) won't bug you to reschedule until after this date" reschedule_on = models.DateField(default=datetime.date.today, help_text=_ht) first_date = property(lambda self: self.active_sessions[0].first_date) last_date = property(lambda self: self.active_sessions[-1].last_date) @property def as_json(self): image = get_thumbnail(get_override(self.first_photo, 'landscape_crop'), "298x199", crop="center") out = { 'id': self.pk, 'name': self.name, 'subject_names': [s.name for s in self.subjects.all()], 'subject_ids': [s.pk for s in self.subjects.all()], 'url': self.get_absolute_url(), 'im': { 'width': image.width, 'height': image.height, 'url': image.url }, 'next_time': time.mktime(self.first_date.timetuple()) if self.active_sessions else 0, 'fee': self.fee, 'active_sessions': [s.as_json for s in self.active_sessions], 'past_session_count': len(self.archived_sessions), 'short_description': self.get_short_description(), 'requirements': self.requirements, 'no_discount': self.no_discount, } out['enrolled_status'] = "Enroll" if out[ 'active_sessions'] else "Details" return out fee = models.IntegerField(null=True, blank=True, default=0) fee_notes = models.CharField(max_length=256, null=True, blank=True) requirements = models.CharField(max_length=256, null=True, blank=True) prerequisites = models.CharField(max_length=256, null=True, blank=True) description = models.TextField(null=True, blank=True) short_description = models.TextField(null=True, blank=True) get_short_description = lambda self: self.short_description or truncatewords( striptags(self.description), 40) safety = models.BooleanField(default=False) room = models.ForeignKey(Room) def get_location_string(self): if self.first_room != self.room: s = "This class meets in the %s and then moves to the %s after a half hour lecture." return s % (self.first_room.name.lower(), self.room.name.lower()) return "This class meets in the %s." % (self.room.name.lower()) _ht = "If true, this class will not raise conflict warnings for events in the same room." no_conflict = models.BooleanField(default=False, help_text=_ht) max_students = models.IntegerField(default=16) objects = CourseManager() __unicode__ = lambda self: self.name get_absolute_url = lambda self: reverse("course:detail", args=[self.pk, self.slug]) get_admin_url = lambda self: "/admin/course/course/%s/" % self.id @cached_method def get_tools(self): criterion_ids = Criterion.objects.filter(courses=self).values_list( "id", flat=True) return Tool.objects.filter( permission__criteria__id__in=criterion_ids).distinct() @cached_property def active_sessions(self): # sessions haven't ended yet (and maybe haven't started) first_date = datetime.datetime.now() - datetime.timedelta(0.5) return list(self.sessions.filter(last_date__gte=first_date)) @property def archived_sessions(self): # opposite of active_sessions first_date = datetime.datetime.now() - datetime.timedelta(0.5) last_year = first_date - datetime.timedelta(365) sessions = self.session_set.filter(last_date__lt=first_date, last_date__gte=last_year) return list(sessions.order_by("-first_date")) sessions = lambda self: Session.objects.filter(course=self, active=True) sessions = cached_property(sessions, name="sessions") last_session = lambda self: (list(self.sessions) or [None])[-1] def save(self, *args, **kwargs): super(Course, self).save(*args, **kwargs) #this has to be repeated in the admin because of how that works subjects = self.subjects.all() for subject in subjects: if subject.parent and not (subject.parent in subjects): self.subjects.add(subject.parent) reset_classes_json("Classes reset during course save") #! inherited from section, may not be necessary def get_notes(self): notes = [] if self.requirements: notes.append(('Requirements', self.requirements)) if self.fee_notes: notes.append(('Fee Notes', self.fee_notes)) if self.safety: notes.append(( 'Safety', "This class has a 20 minute safety session before the first session." )) if self.prerequisites: notes.append(('Prerequisites', self.prerequisites)) return notes @property def list_users(self): return list(set([s.user for s in self.active_sessions])) class Meta: ordering = ("name", )
def test_striptags(self): self.assertEqual( striptags('some <b>html</b> with <script>alert' '("You smell")</script> disallowed <img /> tags'), 'some html with alert("You smell") disallowed tags')
def snippet(self, obj: EmailSignature): return striptags(obj.text[:50]).strip()
def reason_truncated(self, obj): return truncatewords(striptags(obj.reason), 15)
def sold(self): from sell.models import Cart from preferences.models import EmailNotification, EmailNotificationHistory, TYPE_NOTIFICATION from django.core.mail import send_mail, EmailMessage from django.conf import settings from django.template import Context, Template self.state = 'S' self.save() cart = Cart.objects.filter(shop=self.shop, bidder=self.bid_actual.bidder).get() cart.add(self, self.current_bid(), 1) # ------------------------------------------------------------------------ # Send an email to bidder to notify he/she has won the auction c = Context({'bidder_name': self.bid_actual.bidder.get_full_name(), 'bid_amount': self.bid_actual.bid_amount, 'bid_time': self.bid_actual.bid_time, 'shop': self.shop.name, 'session_title': self.session.title, 'session_description': striptags(self.session.description), 'session_start': str(self.session.start), 'session_end': str(self.session.end), 'lot_title': self.title, 'lot_description': striptags(self.description) }) admin_email = self.shop.marketplace.contact_email try: notification = EmailNotification.objects.filter(type_notification='AWC', shop=self.shop).get() type_notification_name = dict(TYPE_NOTIFICATION)[notification.type_notification].title() subj_template = Template(notification.subject) body_template = Template(notification.body) subj_text = subj_template.render(c) body_text = body_template.render(c) mail = EmailMessage(subject=subj_text, body=body_text, from_email=settings.EMAIL_FROM, to=[self.bid_actual.bidder.email], headers={'X-SMTPAPI': '{\"category\": \"%s\"}' % type_notification_name}) mail.send(fail_silently=True) # send_mail(subj_text, body_text, settings.EMAIL_FROM, [self.bid_actual.bidder.email], fail_silently=True) notification_history = EmailNotificationHistory(shop=self.shop, type_notification=notification.type_notification, datetime= datetime.datetime.now(), to=self.bid_actual.bidder.email, subject=subj_text, body=body_text) notification_history.save() except EmailNotification.DoesNotExist: msg = "You made a bid u$s %s for %s and have won the auction!. Please contact %s to get more details about this purchase. Thanks" % (self.bid_actual.bid_amount, self.title, self.shop.admin.email) mail = EmailMessage(subject="Congratulations!!", body=msg, from_email=settings.EMAIL_FROM, to=[self.bid_actual.bidder.email], headers={'X-SMTPAPI': '{\"category\": \"%s\"}' % dict(TYPE_NOTIFICATION)['AWC'].title()}) mail.send(fail_silently=True) # send_mail("Congratulations!!", msg, settings.EMAIL_FROM, [self.bid_actual.bidder.email], fail_silently=True) except Exception, e: mail = EmailMessage(subject="Could not send email to lot winner!", body="Message could not be delivered to %s" % self.bid_actual.bidder.email, from_email=settings.EMAIL_FROM, to=[mail for (name, mail) in settings.STAFF]+[admin_email], headers={'X-SMTPAPI': '{\"category\": \"Error\"}'}) mail.send(fail_silently=True)