def get_feed(self, obj, request): current_site = Site.objects.get_current() link = self._Feed__get_dynamic_attr('link', obj) link = add_domain(current_site.domain, link) feed = self.feed_type( title=self._Feed__get_dynamic_attr('title', obj), link=link, description=self._Feed__get_dynamic_attr('description', obj), ) title_tmp = None if self.title_template is not None: try: title_tmp = template.loader.get_template(self.title_template) except template.TemplateDoesNotExist: pass description_tmp = None if self.description_template is not None: try: description_tmp = template.loader.get_template(self.description_template) except template.TemplateDoesNotExist: pass for item in self._Feed__get_dynamic_attr('items', obj): if title_tmp is not None: title = title_tmp.render( template.RequestContext(request, { 'obj': item, 'site': current_site })) else: title = self._Feed__get_dynamic_attr('item_title', item) if description_tmp is not None: description = description_tmp.render( template.RequestContext(request, { 'obj': item, 'site': current_site })) else: description = self._Feed__get_dynamic_attr('item_description', item) link = add_domain( current_site.domain, self._Feed__get_dynamic_attr('item_link', item), ) pubdate = self._Feed__get_dynamic_attr('item_pubdate', item) if pubdate and not hasattr(pubdate, 'tzinfo'): ltz = tzinfo.LocalTimezone(pubdate) pubdate = pubdate.replace(tzinfo=ltz) feed.add_item( title=title, link=link, description=description, unique_id=self._Feed__get_dynamic_attr('item_guid', item, link), pubdate=pubdate, comment_status=self._Feed__get_dynamic_attr('item_comment_status', item, 'open'), comments=self._get_comments(item) ) return feed
def get_feed(self, obj, request): current_site = Site.objects.get_current() link = self._Feed__get_dynamic_attr('link', obj) link = add_domain(current_site.domain, link) feed = self.feed_type( title = self._Feed__get_dynamic_attr('title', obj), link = link, description = self._Feed__get_dynamic_attr('description', obj), ) title_tmp = None if self.title_template is not None: try: title_tmp = template.loader.get_template(self.title_template) except template.TemplateDoesNotExist: pass description_tmp = None if self.description_template is not None: try: description_tmp = template.loader.get_template(self.description_template) except template.TemplateDoesNotExist: pass for item in self._Feed__get_dynamic_attr('items', obj): if title_tmp is not None: title = title_tmp.render( template.RequestContext(request, { 'obj': item, 'site': current_site })) else: title = self._Feed__get_dynamic_attr('item_title', item) if description_tmp is not None: description = description_tmp.render( template.RequestContext(request, { 'obj': item, 'site': current_site })) else: description = self._Feed__get_dynamic_attr('item_description', item) link = add_domain( current_site.domain, self._Feed__get_dynamic_attr('item_link', item), ) pubdate = self._Feed__get_dynamic_attr('item_pubdate', item) if pubdate and not hasattr(pubdate, 'tzinfo'): ltz = tzinfo.LocalTimezone(pubdate) pubdate = pubdate.replace(tzinfo=ltz) feed.add_item( title = title, link = link, description = description, unique_id = self._Feed__get_dynamic_attr('item_guid', item, link), pubdate = pubdate, comment_status = self._Feed__get_dynamic_attr('item_comment_status', item, 'open'), comments = self._get_comments(item) ) return feed
def test_add_domain(self): """ Test add_domain() prefixes domains onto the correct URLs. """ self.assertEqual(views.add_domain('example.com', '/foo/?arg=value'), 'http://example.com/foo/?arg=value') self.assertEqual( views.add_domain('example.com', 'http://djangoproject.com/doc/'), 'http://djangoproject.com/doc/') self.assertEqual( views.add_domain('example.com', 'https://djangoproject.com/doc/'), 'https://djangoproject.com/doc/') self.assertEqual( views.add_domain('example.com', 'mailto:[email protected]'), 'mailto:[email protected]')
class TestView(ListView): template_name = 'subscribes/test.html' context_object_name = 'article_list' queryset = Article.objects.filter(activity=True).order_by('-pub_date')[:5] domain = add_domain(SITE_DOMAIN_NAME, '', False) def get_context_data(self, **kwargs): context = super(TestView, self).get_context_data(**kwargs) context['domain'] = self.domain context['pretty_domain'] = self.domain.replace('http://', '').replace( 'https://', '').replace('//', '').replace('www', '') context['subject'] = getattr(settings, 'SUBSCRIBES_SUBJECT', _('«МК-Киев». Выбор редактора')) html = render_to_string('subscribes/email.html', context) text = render_to_string('subscribes/email.txt', context) email = '*****@*****.**' token = base64.encodestring( hmac.new(settings.SECRET_KEY, email, sha1).digest()).rstrip() unsubscribe_link = '%s%s?t=%s&e=%s&d=1' % ( self.domain, reverse('subscribes-index'), token, email) context = Context({'unsubscribe_link': unsubscribe_link}) return { 'html': Template(html).render(context), 'text': Template(text).render(context) } @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super(TestView, self).dispatch(*args, **kwargs)
def get_absolute_url(self): """ Returns the full URL of the page, adds a "view on site" button to admin. """ domain = Site.objects.get(pk=settings.SITE_ID).domain return add_domain(domain, self.url)
def item_enclosures(self, item): for blob in item.blob_set.all(): if blob.link: # add_domain adds the domain only if the url doesn't already have one link = add_domain(self.request.get_host(), blob.link, self.request.is_secure()) # When an enclosure's size cannot be determined, a publisher should use a length of 0. yield Enclosure(link, length='0', mime_type="audio/mpeg")
def get_ical(self, obj, request): """ Returns a populated iCalendar instance. """ cal = vobject.iCalendar() cal.add('method').value = 'PUBLISH' # IE/Outlook needs this items = self.__get_dynamic_attr("items", obj) cal_name = self.__get_dynamic_attr("cal_name", obj) cal_desc = self.__get_dynamic_attr("cal_desc", obj) # Add calendar name and description if set if cal_name: cal.add('x-wr-calname').value = cal_name if cal_desc: cal.add('x-wr-caldesc').value = cal_desc if get_current_site: current_site = get_current_site(request) else: current_site = None for item in items: event = cal.add('vevent') for vkey, key in EVENT_ITEMS: value = self.__get_dynamic_attr(key, item) if value: if vkey == 'rruleset': event.rruleset = value else: if vkey == 'url' and current_site: value = add_domain( current_site.domain, value, request.is_secure(), ) event.add(vkey).value = value return cal
def get_feed(self, obj, request, reverse_name): """ Returns an unpopulated :class:`django.utils.feedgenerator.DefaultFeed` object for this object. """ try: current_site = Site.objects.get_current() except Site.DoesNotExist: current_site = RequestSite(request) feed_type = self.get_feed_type(request) node = request.node link = node.get_absolute_url(with_domain=True, request=request, secure=request.is_secure()) feed = feed_type( title = self.__get_dynamic_attr('title', obj), subtitle = self.__get_dynamic_attr('subtitle', obj), link = link, description = self.__get_dynamic_attr('description', obj), language = settings.LANGUAGE_CODE.decode(), feed_url = add_domain( current_site.domain, self.__get_dynamic_attr('feed_url', obj) or node.construct_url(node._subpath, with_domain=True, request=request, secure=request.is_secure()), request.is_secure() ), author_name = self.__get_dynamic_attr('author_name', obj), author_link = self.__get_dynamic_attr('author_link', obj), author_email = self.__get_dynamic_attr('author_email', obj), categories = self.__get_dynamic_attr('categories', obj), feed_copyright = self.__get_dynamic_attr('feed_copyright', obj), feed_guid = self.__get_dynamic_attr('feed_guid', obj), ttl = self.__get_dynamic_attr('ttl', obj), **self.feed_extra_kwargs(obj) ) return feed
def feed_extra_kwargs(self, obj): copyright = escape('%s & %s %s %s') % ( '℗', '©', timezone.now().year, escape(obj.copyright or obj.title)) current_site = get_current_site(self.request) image_url = add_domain(current_site.domain, obj.get_image_url(), self.request.is_secure()) return { 'copyright': copyright, 'itunes': { 'subtitle': obj.subtitle, 'summary': obj.summary, 'author': { 'name': obj.author_name, 'email': obj.author_email, }, 'owner': { 'name': obj.owner_name or obj.author_name, 'email': obj.owner_email or obj.author_email, }, 'image': image_url, 'categories': obj.get_categories_dict(), 'explicit': obj.get_explicit(), 'block': obj.get_block(), 'complete': obj.get_complete(), } }
def test_add_domain(self): """ add_domain() prefixes domains onto the correct URLs. """ prefix_domain_mapping = ( (("example.com", "/foo/?arg=value"), "http://example.com/foo/?arg=value"), ( ("example.com", "/foo/?arg=value", True), "https://example.com/foo/?arg=value", ), ( ("example.com", "http://djangoproject.com/doc/"), "http://djangoproject.com/doc/", ), ( ("example.com", "https://djangoproject.com/doc/"), "https://djangoproject.com/doc/", ), ( ("example.com", "mailto:[email protected]"), "mailto:[email protected]", ), ( ("example.com", "//example.com/foo/?arg=value"), "http://example.com/foo/?arg=value", ), ) for prefix in prefix_domain_mapping: with self.subTest(prefix=prefix): self.assertEqual(views.add_domain(*prefix[0]), prefix[1])
def item_extra_kwargs(self, item): current_site = get_current_site(self.request) image_url = item.image.url if item.image else item.show.get_image_url() image = add_domain(current_site.domain, image_url, self.request.is_secure()) try: enclosure = Enclosure.objects.get(episode=item) cc = enclosure.get_cc() duration = enclosure.get_duration() except Enclosure.DoesNotExist: cc = None duration = None return { 'itunes': { 'subtitle': item.subtitle, 'summary': item.summary, 'author': { 'name': item.get_author_name(), 'email': item.get_author_email(), }, 'image': image, 'explicit': item.get_explicit(), 'block': item.get_block(), 'cc': cc, 'duration': duration, } }
def item_enclosure_url(self, item): try: current_site = get_current_site(self.request) enclosure_url = Enclosure.objects.get(episode=item).file.url return add_domain(current_site.domain, enclosure_url, self.request.is_secure()) except Enclosure.DoesNotExist: return None
def robots(request): """Basic robots file""" current_site = get_current_site(request) base_url = add_domain(current_site.domain, "/", request.is_secure())[:-1] template_values = {"base_url": base_url} return TemplateResponse( request, "djangofloor/robots.txt", template_values, content_type="text/plain" )
def item_enclosure_url(self, item): """ We use the link to the audio file given by the storage backend. We also add current domain because Django has a little bug here. """ current_site = get_current_site(self.request) url = item.file.url return add_domain(current_site.domain, url, self.request.is_secure())
def get_feed(self, obj, request, reverse_name, feed_type=None, *args, **kwargs): """ Returns an unpopulated :class:`django.utils.feedgenerator.DefaultFeed` object for this object. :param obj: The object for which the feed should be generated. :param request: The current request. :param reverse_name: The name which can be used to reverse the URL of the page corresponding to this feed. :param feed_type: The slug used to register the feed class that will be instantiated and returned. :returns: An instance of the feed class registered as ``feed_type``, falling back to :attr:`feed_type` if ``feed_type`` is ``None``. """ try: current_site = Site.objects.get_current() except Site.DoesNotExist: current_site = RequestSite(request) feed_type = self.get_feed_type(request, feed_type) node = request.node link = node.construct_url(self.reverse(reverse_name, args=args, kwargs=kwargs), with_domain=True, request=request, secure=request.is_secure()) feed = feed_type( title=self.__get_dynamic_attr('title', obj), subtitle=self.__get_dynamic_attr('subtitle', obj), link=link, description=self.__get_dynamic_attr('description', obj), language=settings.LANGUAGE_CODE.decode(), feed_url=add_domain( current_site.domain, self.__get_dynamic_attr('feed_url', obj) or node.construct_url(self.reverse( "%s_%s" % (reverse_name, registry.get_slug(feed_type)), args=args, kwargs=kwargs), with_domain=True, request=request, secure=request.is_secure()), request.is_secure()), author_name=self.__get_dynamic_attr('author_name', obj), author_link=self.__get_dynamic_attr('author_link', obj), author_email=self.__get_dynamic_attr('author_email', obj), categories=self.__get_dynamic_attr('categories', obj), feed_copyright=self.__get_dynamic_attr('feed_copyright', obj), feed_guid=self.__get_dynamic_attr('feed_guid', obj), ttl=self.__get_dynamic_attr('ttl', obj), **self.feed_extra_kwargs(obj)) return feed
def show_url(context, **kwargs): """Return the show feed URL with different protocol.""" if len(kwargs) != 2: raise TemplateSyntaxError( _('"show_url" tag takes exactly two keyword arguments.')) request = context['request'] current_site = get_current_site(request) url = add_domain(current_site.domain, kwargs['url']) return re.sub(r'https?:\/\/', '%s://' % kwargs['protocol'], url)
def test_add_domain(self): """ Test add_domain() prefixes domains onto the correct URLs. """ self.assertEqual( views.add_domain('example.com', '/foo/?arg=value'), 'http://example.com/foo/?arg=value' ) self.assertEqual( views.add_domain('example.com', 'http://djangoproject.com/doc/'), 'http://djangoproject.com/doc/' ) self.assertEqual( views.add_domain('example.com', 'https://djangoproject.com/doc/'), 'https://djangoproject.com/doc/' ) self.assertEqual( views.add_domain('example.com', 'mailto:[email protected]'), 'mailto:[email protected]' )
def item_extra_kwargs(self, post): return { 'thumbnail_url': add_domain(domain=self.current_site.domain, url=post.get('image'), secure=True), 'thumbnail_width': 100, 'thumbnail_height': 100, }
def item_extra_kwargs(self, post): return { 'thumbnail_url': add_domain(domain=self.current_site.domain, url=post.image.full.url, secure=True), 'thumbnail_width': post.image.full.width, 'thumbnail_height': post.image.full.height, }
def get_url(self, action, obj=None, domain=True): if not obj: url = reverse('actstream_detail', None, (action.pk,)) elif hasattr(obj, 'get_absolute_url'): url = obj.get_absolute_url() else: ctype = ContentType.objects.get_for_model(obj) url = reverse('actstream_actor', None, (ctype.pk, obj.pk)) if domain: return add_domain(Site.objects.get_current().domain, url) return url
def get(self, request, *args, **kwargs): episode = self.get_object() current_site = get_current_site(request) domain_url = add_domain(current_site.domain, episode.enclosure.file.url, self.request.is_secure()) response = HttpResponse(urlopen(domain_url), content_type=episode.enclosure.type) response['Content-Disposition'] = 'attachment; filename="%s.%s%s"' % ( episode.show.slug, episode.slug, episode.enclosure.get_extension()) return response
def make_item_content_encoded(self, text1, text2, url, comment_name): """ Called from item_content_encoded() in children. text1 and text2 are chunks of HTML text (or empty strings). url is the URL of the item (no domain needed, eg '/diary/1666/10/31/'). comment_name is one of 'comment' or 'annotation'. """ return '%s %s <p><strong><a href="%s#%ss">Read the %ss</a></strong></p>' % ( force_unicode(smartypants.smartyPants(text1)), force_unicode(smartypants.smartyPants(text2)), add_domain(Site.objects.get_current().domain, url), comment_name, comment_name)
def item_extra_kwargs(self, post): return { "thumbnail_url": add_domain( domain=self.current_site.domain, url=post.get("image"), secure=True, ), "thumbnail_width": 100, "thumbnail_height": 100, }
def get_index_feed(self, obj): feed_type = TimemapLinkIndexGenerator timemap_url = add_domain( self.current_site.domain, self.request.path, self.request.is_secure(), ) feed = feed_type( original_url=self.get_original_url(obj), timemap_url=timemap_url, ) paginator = self.get_paginator(self.queryset) item_list = [] for page in paginator.page_range: link = add_domain( self.current_site.domain, "%s?%s=%s" % (timemap_url, self.page_kwarg, page), self.request.is_secure(), ) item_list.append(dict(link=link)) [feed.add_item(**d) for d in item_list] return feed
def show_url(context, *args, **kwargs): """Return the show feed URL with different protocol.""" if len(kwargs) != 2: raise TemplateSyntaxError( _('"show_url" tag takes exactly two keyword arguments.')) try: request = context['request'] except IndexError: raise TemplateSyntaxError( _('"show_url" tag requires request in the template context. Add the request context processor to settings.' )) current_site = get_current_site(request) url = add_domain(current_site.domain, kwargs['url']) return re.sub(r'https?:\/\/', '%s://' % kwargs['protocol'], url)
def make_item_content_encoded(self, text1, text2, url, comment_name): """ Called from item_content_encoded() in children. text1 and text2 are chunks of HTML text (or empty strings). url is the URL of the item (no domain needed, eg '/diary/1666/10/31/'). comment_name is one of 'comment' or 'annotation'. """ return '%s %s <p><strong><a href="%s#%ss">Read the %ss</a></strong></p>' % ( force_unicode(smartypants.smartypants(text1)), force_unicode(smartypants.smartypants(text2)), add_domain(Site.objects.get_current().domain, url), comment_name, comment_name )
def get_list_feed(self, obj, page_number=None): feed_type = TimemapLinkListGenerator feed = feed_type( original_url=self.get_original_url(obj), timemap_url=add_domain( self.current_site.domain, self.request.path, self.request.is_secure(), ), ) if page_number: page = self.get_page(page_number) self.queryset = page.object_list item_list = [] for item in self.queryset: link = add_domain( self.current_site.domain, self.__get_dynamic_attr('memento_link', item), self.request.is_secure(), ) item_datetime = self.__get_dynamic_attr('memento_datetime', item) if item_datetime and is_naive(item_datetime): item_datetime = utc(item_datetime) item_list.append(dict( link=link, datetime=item_datetime, )) if not page_number: item_list[0]['first'] = True item_list[-1]['last'] = True else: if page_number == 1: item_list[0]['first'] = True elif not page.has_next(): item_list[-1]['last'] = True [feed.add_item(**d) for d in item_list] return feed
def post(self, request, *args, **kwargs): form = SubscribeForm(request.POST) if form.is_valid(): email = form.cleaned_data['email'] domain = add_domain(SITE_DOMAIN_NAME, '', request.is_secure()) token = urlsafe_base64_encode( self.make_token(settings.SECRET_KEY, email)) pretty_domain = domain.replace('http://', '').replace('https://', '').replace('//', '') from_email_name = getattr(settings, 'SUBSCRIBES_FROM_EMAIL_NAME', 'no-reply') from_email = '%s@%s' % (from_email_name, pretty_domain) subject = _('Подтверждение подписки для %s' % pretty_domain) url = '%s%s?t=%s&e=%s' % (domain, reverse('subscribes-index'), token, email) print email, domain, pretty_domain, url, from_email_name, from_email text_message = '%s:\n\n%s\n\n--\n%s' % ( _('Скопируйте ссылку в браузер.'), url, domain) html_message = '<a href="%s">%s</a><br><br>---<br>%s' % ( url, _('Подписаться на рассылку.'), domain) connection = mail.get_connection() connection.open() msg = mail.EmailMultiAlternatives(subject, text_message, from_email, [email]) msg.attach_alternative(html_message, 'text/html') try: msg.send() messages.success( request, _('На ваш почтовый адрес выслано подтверждение подписки. Проверьте ваш почтовый ящик' )) except SMTPException: messages.error( request, _('Ошибка в отправке подтверждения подписки на ваш почтовый адрес' )) raise finally: connection.close() else: for error in form.errors['email']: messages.error(request, error) return self.render_to_response(context={})
def test_add_domain(self): """ add_domain() prefixes domains onto the correct URLs. """ prefix_domain_mapping = ( (('example.com', '/foo/?arg=value'), 'http://example.com/foo/?arg=value'), (('example.com', '/foo/?arg=value', True), 'https://example.com/foo/?arg=value'), (('example.com', 'http://djangoproject.com/doc/'), 'http://djangoproject.com/doc/'), (('example.com', 'https://djangoproject.com/doc/'), 'https://djangoproject.com/doc/'), (('example.com', 'mailto:[email protected]'), 'mailto:[email protected]'), (('example.com', '//example.com/foo/?arg=value'), 'http://example.com/foo/?arg=value'), ) for prefix in prefix_domain_mapping: with self.subTest(prefix=prefix): self.assertEqual(views.add_domain(*prefix[0]), prefix[1])
def get_url(self, action, obj=None, domain=True): """ Returns an RFC3987 IRI for a HTML representation of the given object, action. If domain is true, the current site's domain will be added. """ if not obj: url = reverse('actstream_detail', None, (action.pk,)) elif hasattr(obj, 'get_absolute_url'): url = obj.get_absolute_url() else: ctype = ContentType.objects.get_for_model(obj) url = reverse('actstream_actor', None, (ctype.pk, obj.pk)) if domain: return add_domain(Site.objects.get_current().domain, url) return url
def handle(self, **options): """Validates All the Feeds""" titles = Title.objects.filter(deleted=False) bad_titles = [] for title in titles: url = add_domain(Site.objects.get_current().domain, reverse_lazy('title_episodes_feed', args={title.slug})) result = feedparser.parse(url) if result.get('bozo', 0) == 1: bad_titles.append({title: result.get('bozo')}) if len(bad_titles) > 0: print ("BAD TITLES FOUND") print (bad_titles) else: print ("ALL TITLES HAVE VALID FEEDS")
def get_url(self, action, obj=None, domain=True): """ Returns an RFC3987 IRI for a HTML representation of the given object, action. If domain is true, the current site's domain will be added. """ if not obj: url = reverse('actstream_detail', None, (action.pk, )) elif hasattr(obj, 'get_absolute_url'): url = obj.get_absolute_url() else: ctype = ContentType.objects.get_for_model(obj) url = reverse('actstream_actor', None, (ctype.pk, obj.pk)) if domain: return add_domain(Site.objects.get_current().domain, url) return url
def related_pages_generator(request, related_pages): for related_page in related_pages: if related_page.page: page_url = related_page.page.get_absolute_url() url = add_domain(request.get_host(), page_url, secure=request.is_secure()) else: url = related_page.link # Remove common prefix url = re.sub(r'^https?://(?:www\.)?', '', url, flags=re.IGNORECASE) # Remove common suffix if url.endswith('/'): url = url.rstrip('/') yield related_page, url
def handle(self, **options): """Validates All the Feeds""" titles = Title.objects.filter(deleted=False) bad_titles = [] for title in titles: url = add_domain( Site.objects.get_current().domain, reverse_lazy('title_episodes_feed', args={title.slug})) result = feedparser.parse(url) if result.get('bozo', 0) == 1: bad_titles.append({title: result.get('bozo')}) if len(bad_titles) > 0: print("BAD TITLES FOUND") print(bad_titles) else: print("ALL TITLES HAVE VALID FEEDS")
def pay(self, request): shop = self.shop order = shop.get_order(request) order.status = Order.CONFIRMED order.save() site = get_current_site(request) site_url = add_domain(site.domain, '', request.is_secure()) order_id = shop.get_order_unique_id(order) order_total = shop.get_order_total(order) # Split the order total by a decimal point and remove all dots # and commas that might be used in a tousand separator. total_amount = '{:.2f}'.format(order_total).rsplit('.', 1) total_amount[0] = total_amount[0].replace(',', '').replace('.', '') signature_total_amount = ''.join(total_amount) # Add a comma as a decimal separator. total_amount = ','.join(total_amount) signature_str = '{shop_id}{secret_key}{shopping_cart_id}{secret_key}'\ '{total_amount}{secret_key}'.format( shop_id=sws.SHOP_ID, secret_key=sws.SECRET_KEY, shopping_cart_id=order_id, total_amount=signature_total_amount) signature = hashlib.md5() signature.update(signature_str) signature = signature.hexdigest() data = { 'ShopID': sws.SHOP_ID, 'ShoppingCartID': order_id, 'TotalAmount': total_amount, 'Signature': signature, 'ReturnURL': site_url + reverse('wspay-verify'), 'CancelURL': site_url + reverse('wspay-cancel'), 'ReturnErrorURL': site_url + reverse('wspay-error'), } form = WSPayForm(initial=data) return render(request, 'shop_wspay/pay.html', { 'form': form, 'form_url': sws.FORM_URL, 'order': order, })
def get_feed(self, obj, request, reverse_name, feed_type=None, *args, **kwargs): """ Returns an unpopulated :class:`django.utils.feedgenerator.DefaultFeed` object for this object. :param obj: The object for which the feed should be generated. :param request: The current request. :param reverse_name: The name which can be used to reverse the URL of the page corresponding to this feed. :param feed_type: The slug used to register the feed class that will be instantiated and returned. :returns: An instance of the feed class registered as ``feed_type``, falling back to :attr:`feed_type` if ``feed_type`` is ``None``. """ try: current_site = Site.objects.get_current() except Site.DoesNotExist: current_site = RequestSite(request) feed_type = self.get_feed_type(request, feed_type) node = request.node link = node.construct_url(self.reverse(reverse_name, args=args, kwargs=kwargs), with_domain=True, request=request, secure=request.is_secure()) feed = feed_type( title = self.__get_dynamic_attr('title', obj), subtitle = self.__get_dynamic_attr('subtitle', obj), link = link, description = self.__get_dynamic_attr('description', obj), language = settings.LANGUAGE_CODE.decode(), feed_url = add_domain( current_site.domain, self.__get_dynamic_attr('feed_url', obj) or node.construct_url(self.reverse("%s_%s" % (reverse_name, registry.get_slug(feed_type)), args=args, kwargs=kwargs), with_domain=True, request=request, secure=request.is_secure()), request.is_secure() ), author_name = self.__get_dynamic_attr('author_name', obj), author_link = self.__get_dynamic_attr('author_link', obj), author_email = self.__get_dynamic_attr('author_email', obj), categories = self.__get_dynamic_attr('categories', obj), feed_copyright = self.__get_dynamic_attr('feed_copyright', obj), feed_guid = self.__get_dynamic_attr('feed_guid', obj), ttl = self.__get_dynamic_attr('ttl', obj), **self.feed_extra_kwargs(obj) ) return feed
def item_extra_kwargs(self, post): if not post.image.name: return {} try: return { "thumbnail_url": add_domain( domain=self.current_site.domain, url=post.image.full.url, secure=True, ), "thumbnail_width": post.image.full.width, "thumbnail_height": post.image.full.height, } except IOError as e: logger.exception("File does not exists error") return {}
def test_add_domain(self): """ Test add_domain() prefixes domains onto the correct URLs. """ self.assertEqual(views.add_domain("example.com", "/foo/?arg=value"), "http://example.com/foo/?arg=value") self.assertEqual(views.add_domain("example.com", "/foo/?arg=value", True), "https://example.com/foo/?arg=value") self.assertEqual( views.add_domain("example.com", "http://djangoproject.com/doc/"), "http://djangoproject.com/doc/" ) self.assertEqual( views.add_domain("example.com", "https://djangoproject.com/doc/"), "https://djangoproject.com/doc/" ) self.assertEqual( views.add_domain("example.com", "mailto:[email protected]"), "mailto:[email protected]" ) self.assertEqual( views.add_domain("example.com", "//example.com/foo/?arg=value"), "http://example.com/foo/?arg=value" )
def item_enclosure_url(self, obj): file_url = obj.file.url domain = Site.objects.get_current().domain return add_domain(domain=domain, url=file_url)
def get_site_url(site, path): """Retrieve current site site Always returns as http (never https) """ return add_domain(site.domain, path, False)
def item_guid(self, video): if video.guid: return video.guid return add_domain(video.site.domain, video.get_absolute_url())
def populate_feed(self, feed, items, request): """Populates a :class:`django.utils.feedgenerator.DefaultFeed` instance as is returned by :meth:`get_feed` with the passed-in ``items``.""" if self.item_title_template: title_template = DjangoTemplate(self.item_title_template.code) else: title_template = None if self.item_description_template: description_template = DjangoTemplate(self.item_description_template.code) else: description_template = None node = request.node try: current_site = Site.objects.get_current() except Site.DoesNotExist: current_site = RequestSite(request) if self.feed_length is not None: items = items[:self.feed_length] for item in items: if title_template is not None: title = title_template.render(RequestContext(request, {'obj': item})) else: title = self.__get_dynamic_attr('item_title', item) if description_template is not None: description = description_template.render(RequestContext(request, {'obj': item})) else: description = self.__get_dynamic_attr('item_description', item) link = node.construct_url(self.reverse(obj=item), with_domain=True, request=request, secure=request.is_secure()) enc = None enc_url = self.__get_dynamic_attr('item_enclosure_url', item) if enc_url: enc = feedgenerator.Enclosure( url = smart_unicode(add_domain( current_site.domain, enc_url, request.is_secure() )), length = smart_unicode(self.__get_dynamic_attr('item_enclosure_length', item)), mime_type = smart_unicode(self.__get_dynamic_attr('item_enclosure_mime_type', item)) ) author_name = self.__get_dynamic_attr('item_author_name', item) if author_name is not None: author_email = self.__get_dynamic_attr('item_author_email', item) author_link = self.__get_dynamic_attr('item_author_link', item) else: author_email = author_link = None pubdate = self.__get_dynamic_attr('item_pubdate', item) if pubdate and not pubdate.tzinfo: ltz = tzinfo.LocalTimezone(pubdate) pubdate = pubdate.replace(tzinfo=ltz) feed.add_item( title = title, link = link, description = description, unique_id = self.__get_dynamic_attr('item_guid', item, link), enclosure = enc, pubdate = pubdate, author_name = author_name, author_email = author_email, author_link = author_link, categories = self.__get_dynamic_attr('item_categories', item), item_copyright = self.__get_dynamic_attr('item_copyright', item), **self.item_extra_kwargs(item) )
def add_domain(self, link): return add_domain(self._site.domain, link, self._request.is_secure())
def item_link(item, current_site): return add_domain(current_site.domain, item.get_absolute_url(), not settings.DEBUG)
def item_image_link(item, current_site): product_image = item.get_first_image() if product_image: image = product_image.image return add_domain(current_site.domain, image.url, False) return None
def image(self, obj): if settings.MEDIA_DOMAIN: return get_cover_url_at_width(obj, 1400) else: return add_domain(Site.objects.get_current().domain, get_cover_url_at_width(obj, 1400))
def robots(request): current_site = get_current_site(request) base_url = add_domain(current_site.domain, '/', request.is_secure())[:-1] template_values = {'base_url': base_url} return TemplateResponse('easydjango/robots.txt', template_values, content_type='text/plain')
def item_comments(self, obj): return add_domain(Site.objects.get_current().domain, obj.title.get_absolute_url())
def itunes_image(self): file_url = staticfiles_storage.url(settings.PODCAST_IMAGE) domain = Site.objects.get_current().domain return add_domain(domain=domain, url=file_url)
def item_image_link(item, current_site): image = item.get_first_image() if image: return add_domain(current_site.domain, image.url, False) else: return None
def registration(request, template): if not registration_open(): return render_to_response( request.LANGUAGE_CODE + "/closed_registration.html", context_instance=RequestContext(request) ) if request.method == "POST": form = RegisteringForm(request.POST) if form.is_valid(): cd = form.cleaned_data # retrieve the school if cd["school_exists"] == SCHOOL_NOT_EXIST: # if a new one school, created = School.objects.get_or_create( # if already exists, does not create a new one name=cd["new_school_name"], city=cd["new_school_city"], postal_code=cd["new_school_postal_code"], ##category = cd["contest_category"] ) # should never raise a IntegrityError, right? else: # if school selected in the list school = cd["school"] # create the contestant token = _gen_token() contestant = Contestant( surname=cd["surname"], firstname=cd["firstname"], gender=cd["gender"], email=cd["email"], address=cd["address"], city=cd["city"], postal_code=cd["postal_code"], dob=cd["dob"], # contest_category = cd["contest_category"], school=school, year_study=cd["year_study"], language=cd["language"], semifinal_center=cd["semifinal_center"], token=token, contest_year=contest_year(), ) try: # if using postgres >=8.2, should use database-level autocommit instead sid = transaction.savepoint() contestant.save() transaction.savepoint_commit(sid) except IntegrityError: # triggered by db or model validation transaction.savepoint_rollback(sid) test = Contestant.objects.count() return HttpResponseRedirect(reverse("registration-error", args=[request.LANGUAGE_CODE])) # get the full url for mail data if Site._meta.installed: current_site = Site.objects.get_current() else: current_site = RequestSite(request) # mail sending context = Context( { "NAME": cd["firstname"] + " " + cd["surname"], # "CONTEST": dict(CONTEST_CHOICES)[cd["contest_category"]], "CENTER_NAME": cd["semifinal_center"], } ) mail_template = get_template("emails/" + request.LANGUAGE_CODE + "/registration.txt") context["CENTER_DETAILS"] = add_domain( current_site.domain, reverse("semifinal-places", args=[request.LANGUAGE_CODE]) ) send_mail( _("Registering to Belgian Olympiads in Informatics"), mail_template.render(context), "*****@*****.**", [cd["email"]], fail_silently=True, ) # redirect to confirmation page return HttpResponseRedirect( reverse("registration-confirm", args=[request.LANGUAGE_CODE, cd["semifinal_center"].id]) ) else: if request.LANGUAGE_CODE == "fr": initial_lang = LANG_FR else: initial_lang = LANG_NL form = RegisteringForm(initial={"language": initial_lang}) return render_to_response( template, {"form": form, "global_errors": form.non_field_errors()}, context_instance=RequestContext(request) )