def index(request): sett = Setting.get_data() img_site = Meta(url=sett.get_logo()) meta = Meta( title=sett.site_name, description=sett.site_desc, keywords=[ 'NolSatu', 'Open Source', 'Pelatihan', 'Gratis', 'Cloud Computing', 'DevOps', 'Btech', 'Pemrograman' ], image=img_site.url, use_og=True, use_facebook=True, use_twitter=True ) seleksi = Student.objects.pre_test().count() peserta = Student.objects.participants().count() context = { 'title': 'Home', 'instructors': Instructor.objects.order_by('order'), 'pengguna': User.objects.actived().count(), 'seleksi': seleksi + peserta, 'peserta': peserta, 'lulus': Student.objects.graduated().count(), 'tersalurkan': Graduate.objects.filter(is_channeled=True).count(), 'logo_partners': LogoPartner.objects.filter(is_visible=True).order_by('display_order'), 'logo_sponsors': LogoSponsor.objects.filter(is_visible=True).order_by('display_order'), 'meta': meta } return render(request, 'website/home.html', context)
def get_generic_meta(title=None, api=False): image_filename = 'screen-bg_11.jpg' if api is False else 'screen-bg_10.jpg' image_url = static('arcsecond/img/' + image_filename) meta = Meta( keywords=[ 'astronomy', 'astrophysics', 'cloud', 'data', 'bigdata', 'REST', 'API', 'integration', 'sun', 'moon', 'sky', 'planets', 'exoplanets', 'earth', 'observing sites', 'telescopes' ], description=_("The astronomy cloud."), url='http://www.arcsecond.io', site_name='arcsecond.io', use_og=True, use_twitter=True, twitter_creator="@onekiloparsec", twitter_site="@arcsecond_io", twitter_card="summary_large_image", object_type="website", image="http://www.arcsecond.io{0}".format(image_url), ) if title is not None: meta.title = title if settings.SITE_ID == 3: # PROD facebook_app_id = '884448981631297' meta.extra_custom_props = [ ('property', 'fb:app_id', facebook_app_id), ] return meta
def test_get_full_url_without_schema(self): meta.settings.SITE_PROTOCOL = 'https' m = Meta() self.assertEqual( m.get_full_url('//foo.com/foo/bar'), 'https://foo.com/foo/bar' )
def test_get_full_url_without_schema(self): settings.SITE_PROTOCOL = 'https' m = Meta() self.assertEqual( m.get_full_url('//foo.com/foo/bar'), 'https://foo.com/foo/bar' )
def test_get_full_url_with_absolute_path(self): meta.settings.SITE_PROTOCOL = 'https' meta.settings.SITE_DOMAIN = 'foo.com' m = Meta() self.assertEqual( m.get_full_url('/foo/bar'), 'https://foo.com/foo/bar' )
def test_get_full_url_with_domain_and_protocol(self): meta.settings.SITE_PROTOCOL = 'https' meta.settings.SITE_DOMAIN = 'foo.com' m = Meta() self.assertEqual( m.get_full_url('foo/bar'), 'https://foo.com/foo/bar' )
def test_get_full_url_without_site_id_with_request_will_not_raise(self): settings.USE_SITES = True settings.SITE_PROTOCOL = 'http' factory = RequestFactory() request = factory.get('/') Site.objects.create(domain=request.get_host()) m = Meta(request=request) self.assertEqual(m.get_full_url('foo/bar'), 'http://testserver/foo/bar')
def test_get_full_url_without_site_id_with_request_will_not_raise(self): settings.USE_SITES = True settings.SITE_PROTOCOL = 'http' factory = RequestFactory() request = factory.get('/') Site.objects.create(domain=request.get_host()) m = Meta(request=request) self.assertEqual( m.get_full_url('foo/bar'), 'http://testserver/foo/bar' )
def test_pages_appid(self): settings.FB_APPID = 'appid' m = Meta(fb_pages='fbpages') self.assertEqual(m.fb_pages, 'fbpages') self.assertEqual(m.og_app_id, 'appid') settings.FB_PAGES = 'fbpages' m = Meta() self.assertEqual(m.fb_pages, 'fbpages') self.assertEqual(m.og_app_id, 'appid') settings.FB_PAGES = '' settings.FB_APPID = ''
def get_context_data(self, *args, **kwargs) -> Dict: """Return the context dictionary used to render the view.""" context = super().get_context_data(*args, **kwargs) context['object_list'] = [ instance.serialize() for instance in context['object_list'] if instance ] context['count'] = self.results_count or 0 query = self.request.GET.get(QUERY_KEY) context[QUERY_KEY] = query initial_data: Dict[str, Any] = {} search_form = SearchForm( request=self.request, query=query, suppress_unverified=self.suppress_unverified, order_by_relevance=self.sort_by_relevance, excluded_content_types=self.excluded_content_types, entities=self.entities, topics=self.topics, initial=initial_data, ) context['search_form'] = search_form title = f'{query or "Historical"} occurrences, quotes, sources, and more | ModularHistory' context['meta'] = Meta( title=title, description=( f'{title}, filterable by topic, date, entity, and content type.' ), ) return context
def get_meta(self) -> Meta: return Meta( title=self.get_title(), description=html2text(self.get_description()), keywords=[self.yeast.name.lower(), 'yeast', 'fermentation'], url=object_url(self.yeast), )
def view(request): meta = Meta( title="SEO Digital Marketing Services Agency Toronto | JM Digital", og_title='SEO Digital Marketing Services Agency Toronto | JM Digital', twitter_title= 'SEO Digital Marketing Services Agency Toronto | JM Digital', schemaorg_title= 'SEO Digital Marketing Services Agency Toronto | JM Digital', image='', image_object={ 'url': '', 'secure_url': '', 'type': 'image/jpeg', 'width': 1200, 'height': 630, 'alt': 'JM Digital Marketing Services Image', }, image_height=1230, image_width=630, object_type='Website Home', description= 'JM Digital Marketing Services is a Toronto based digital marketing services agency. Our experts in the field of SEO and Social Media Marketing can help your website rank on Google, Bing & Yahoo. Call +1(877) 861-5464 for a FREE Website Audit Today!', site_name='JM Digital Marketing Services', # keywords=[ # 'seo toronto', 'social media marketing', 'toronto web design', # 'digital marketing agency toronto', 'app developers toronto', # 'local seo company', 'seo company near me', 'shopify expert toronto', # 'social media marketing agency', 'toronto web development' # ], extra_custom_props=[ ('http-equiv', 'Content-Type', 'text/html; charset=UTF-8'), ]) return render(request, "home/index.html")
def social_connect_failed(request): meta = Meta(title="Failed Social Connection - %s" % (get_current_site(request).name), description="Your social media connection failed") return render(request, './socialapp/dashboard/failed_connection.html', context={'meta': meta})
def get(self, request, *args, **kwargs): twitter_callback_url = settings.SITE_URL + reverse( 'social_media_connect_twitter') instagram_props = { 'app_id': settings.INSTAGRAM['APP_ID'], 'redirect_uri': settings.SITE_URL + '/dashboard/connect/instagram', 'scope': 'user_profile,user_media', 'response_type': 'code', 'state': 1 } instagram_url = settings.INSTAGRAM['AUTH_URL'] + '?' + parse.urlencode( instagram_props) profile = Profile.objects.get(user=request.user) accounts = profile.accounts.all().values('social_name') accounts = [[name['social_name'], True] for name in accounts] meta = Meta(title="Connect your social media account - %s" % (get_current_site(request).name), description="Connect your social media account") return render(request, self.template_name, context={ 'twitter_callback_url': twitter_callback_url, 'instagram_url': instagram_url, 'account': dict(accounts), 'meta': meta })
def get_context_data(self, **kwargs): context = super(AnnouncementListView, self).get_context_data(**kwargs) meta = Meta(title=get_site_title('Announcements')) context['is_announcement_page'] = 'active' context['meta'] = meta return context
def presentation_list(request, year=None): conference = get_object_or_404(Conference, year=year or timezone.now().year) presentations = Presentation.objects.filter( active=True, conference__year=year).order_by("type") speakers = Speaker.objects.all().prefetch_related( Prefetch("presentations", queryset=presentations)) speakers = filter(lambda speaker: any(speaker.presentations.all()), speakers) presentation_count = presentations.count() context = { 'speakers': speakers, 'meta': Meta( description= f"This year we will be hosting {presentation_count} presentations including" f" talks, keynotes as well as workshops at {conference}." f" Follow this link to get more details !", title=f"{conference} - Speakers", image=conference.conference_logo.url if conference.conference_logo else None) } return render(request, 'speakers.html', context)
def get_meta(self) -> Meta: return Meta( title=self.get_title(), description=self.get_description(), keywords=['yeasts'], url=self.get_url(), )
def test_defaults(self): m = Meta() self.assertEqual(m.title, None) self.assertEqual(m.description, None) self.assertEqual(m.extra_props, None) self.assertEqual(m.extra_custom_props, None) self.assertEqual(m.custom_namespace, None) self.assertEqual(m.keywords, []) self.assertEqual(m.url, None) self.assertEqual(m.image, None) self.assertEqual(m.object_type, None) self.assertEqual(m.site_name, None) self.assertEqual(m.twitter_site, None) self.assertEqual(m.twitter_creator, None) self.assertEqual(m.twitter_card, None) self.assertEqual(m.locale, None) self.assertEqual(m.facebook_app_id, None) self.assertEqual(m.use_og, False) self.assertEqual(m.use_sites, False) self.assertEqual(m.use_twitter, False) self.assertEqual(m.use_facebook, False) self.assertEqual(m.use_googleplus, False) self.assertEqual(m.fb_pages, '') self.assertEqual(m.og_app_id, '') self.assertEqual(m.use_title_tag, False)
def threadPage(request, topic_title='', thread_id='', slug=''): if topic_title and thread_id: try: topic = Topic.getTopic(topic_title) thread = Thread.objects.get(id=thread_id) if thread.topic == topic: if not slug or slug != thread.slug or topic.urlTitle != topic_title: return HttpResponseRedirect(thread.relativeUrl) if thread.op.content: description = thread.op.content[:160] else: description = getattr( settings, "DJEDDIT_DESCRIPTION", "The link sharing and discussion portal") meta = Meta( title=thread.title, use_title_tag=True, description=description, ) thread.views += 1 thread.save() context = dict(thread=thread, nodes=thread.op.getSortedReplies(), meta=meta) return render(request, 'djeddit/thread.html', context) except (Topic.DoesNotExist, Thread.DoesNotExist): pass raise Http404
def test_set_image_with_default_image_url(self): settings.SITE_PROTOCOL = 'https' settings.SITE_DOMAIN = 'foo.com' settings.IMAGE_URL = '/thumb/' settings.DEFAULT_IMAGE = 'img/image.gif' m = Meta() self.assertEqual(m.image, 'https://foo.com/thumb/img/image.gif')
def details(request, slug): queryset = Blog.objects.filter(is_active=True) blog = get_object_or_404(queryset, slug=slug) meta = Meta(title=blog.seo_title, og_title=blog.seo_title, twitter_title=blog.seo_title, schemaorg_title=blog.seo_title, image=blog.image_url, image_object={ 'url': blog.image_url, 'secure_url': blog.image_url, 'type': 'image/jpeg', 'width': 1200, 'height': 630, 'alt': 'JM Digital Marketing Services Image', }, image_height=1230, image_width=630, object_type='Blog of J. M. Digital Marketing Services', description=blog.seo_description, site_name='JM Digital Marketing Services', extra_custom_props=[ ('http-equiv', 'Content-Type', 'text/html; charset=UTF-8'), ]) context = { 'blog': blog, 'has_contact': True, 'contact_header': 'GET A FREE SITE AUDIT', 'meta': meta } return render(request, 'blog/details/index.html', context)
def get_meta(self) -> Meta: return Meta( title=self.get_title(), description=self.get_description(), keywords=['malts', 'fermentables'], url=self.get_url(), )
def test_meta_namespaces_facebook_and_custom(self): context = { 'meta': Meta(use_facebook=True, custom_namespace='my-website') } result = meta_namespaces(context) expected = ' prefix="og: http://ogp.me/ns# fb: http://ogp.me/ns/fb# my-website: http://ogp.me/ns/my-website#"' self.assertEqual(result, expected)
def get_meta(self) -> Meta: return Meta( title=self.get_title(), description=self.get_description(), keywords=[self.style.name.lower(), 'style'], url=object_url(self.style), )
def speaker_detail(request, slug=None): if slug: q = Q(slug=slug) elif "pk" in request.GET.keys(): q = Q(pk=request.GET['pk']) else: raise Http404() speaker = get_object_or_404(Speaker, q) presentations = speaker.presentations.filter(active=True).prefetch_related( 'conference').order_by('-conference__year') conf = defaultdict(list) for presentation in presentations: conf[presentation.conference.year].append(presentation) speaker_image = speaker.images.all().first( ).profile_picture.url if speaker.images.exists() else None most_recent_year = list(conf.keys())[0] context = { 'speaker': speaker, 'conf': dict(conf), 'meta': Meta(description=truncatewords(strip_tags(speaker.description), 20), image=speaker_image, title=f"{speaker.full_name} @ PyCon Balkan {most_recent_year}") } return render(request, 'speaker.html', context)
def register(request): """Register a non-logged in user""" # Redirect to the homepage in case user is logged in. if request.user.is_authenticated: messages.warning(request, 'You are already logged in!') return redirect('ideas:home') template_name = 'users/register.html' context = {} if (request.method == 'POST'): context['form'] = form = UserRegisterForm(request.POST) if (form.is_valid()): user = form.save() username = form.cleaned_data.get('username') messages.success( request, f'Account created for {username}. You will now be able to Log In!' ) log_in_user(request, user) return redirect('ideas:home') else: # On GET request return a new form context['form'] = UserRegisterForm() context['meta'] = Meta(title='Register | IdeaFare', description='Register on IdeaFare', keywords=meta_home.keywords + ['register']) return render(request, template_name, context=context)
def about(request): about_meta = meta_defaults.copy() about_meta["title"] = about_meta["og_title"] = about_meta[ "twitter_title"] = about_meta["gplus_title"] = "About | {}".format( generic_title) about_meta["url"] = reverse("about") items = AboutItem.objects.order_by("order") if MODE == "app": items = items.filter(app_mode=True) else: items = items.filter(web_mode=True) items = items.all() for item in items: item.question = item.question.replace( "{medium}", "app" if MODE == "app" else "site") item.answer = item.answer.replace("{medium}", "app" if MODE == "app" else "site") item.question_json = BeautifulSoup( item.question.replace('"', '\\"').replace("\n", ""), "lxml").text item.answer_json = item.answer.replace('"', '\\"').replace( "\n", "").replace("<h5>", "").replace("</h5>", "").replace("<p>", "").replace("</p>", "") return render(request, "office/about.html", { "items": items, "meta": Meta(**about_meta) })
def get_meta_tags_dict(title=settings.DEFAULT_TITLE, description=settings.DEFAULT_DESCRIPTION, keywords=settings.DEFAULT_KEYWORDS, url="/", image=settings.DEFAULT_LOGO_URL, object_type="website"): """ Get meta data dictionary for a page Parameters ---------- title : string The title of the page used in og:title, twitter:title, <title> tag etc. description : string Description used in description meta tag as well as the og:description and twitter:description property. keywords : list List of keywords related to the page url : string Full or partial url of the page image : string Full or partial url of an image object_type : string Used for the og:type property. """ meta = Meta(title=title, description=description, keywords=keywords + settings.DEFAULT_KEYWORDS, url=url, image=image, object_type=object_type, use_og=True, use_twitter=True, use_facebook=True, use_title_tag=True) return meta
def PostIndex(request, tag_slug=None, cat_slug=None, author_user=None): meta = Meta( title="وبلاگ", description= 'پست های هفتگی انواع پروژه های مختلف اینترنت اشیا و هوش مصنوعی و طراحی سایت به همراه آموزش با پایتون ', keywords=['طراحی سایت', 'هوش مصنوعی', 'اینترنت اشیا'], locale='fa_IR') posts = Post.objects.filter( status=1, published_date__lte=timezone.now()).order_by('-published_date') tag = None msg = None if tag_slug: tag = get_object_or_404(Tag, slug=urlunquote(tag_slug)) posts = posts.filter(tags__in=[tag]) msg = f"فیلتر شده بر اساس تگ: \"{urlunquote(tag_slug)}\"" if cat_slug: posts = posts.filter(category__name=urlunquote(cat_slug)) msg = f"فیلتر شده بر اساس دسته بندی: \"{urlunquote(cat_slug)}\"" posts = paginate(request, posts, 5) context = { "posts": posts, 'tag': tag, "msg": msg, 'cat': cat_slug, "meta": meta } return render(request, "blog/blog_index.html", context)
def get_meta(self) -> Meta: """Get the metadata to include in the head of the node's page.""" json = self.json node_type = schema_node_type(json) if node_type in ("CodeChunk", "CodeExpression"): lang = json.get("programmingLanguage", "") kind = "code chunk" if node_type == "CodeChunk" else "code expression" title = f"{lang.title()} {kind}" elif node_type in ("MathBlock", "MathFragment"): lang = json.get("mathLanguage", "") kind = "math block" if node_type == "MathBlock" else "math fragment" title = f"{lang.title()} {kind}" else: title = node_type + " node" description = "Created" if self.creator: description += f" by { get_name(self.creator) }" app_name, app_url = self.get_app() if app_name: description += f" using { app_name }" if self.created: description += f" at { self.created } UTC" return Meta(object_type="article", title=title, description=description,)
def signup_thank_you(request): settings_meta = meta_defaults.copy() settings_meta["title"] = settings_meta["og_title"] = settings_meta["twitter_title"] = settings_meta[ "gplus_title" ] = "Thank you | {}".format(generic_title) settings_meta["url"] = reverse("settings") return render(request, "office/signup_thank_you.html", {"h1": True, "meta": Meta(**settings_meta)})
def evening_prayer(request, year, month, day): ep = EveningPrayer("{}-{}-{}".format(year, month, day)) ep_meta = meta_defaults.copy() ep_meta["title"] = ep_meta["og_title"] = ep_meta["twitter_title"] = ep_meta["gplus_title"] = ep.title ep_meta["description"] = ep.description ep_meta["url"] = reverse("evening_prayer", kwargs={"year": year, "month": month, "day": day}) return render(request, "office/office.html", {"office": ep, "meta": Meta(**ep_meta)})
def test_get_full_url_with_full_url(self): m = Meta() self.assertEqual( m.get_full_url('http://example.com/foo'), 'http://example.com/foo' )
def test_get_full_url_with_None(self): m = Meta() self.assertEqual(m.get_full_url(None), None)
def test_get_full_url_with_absolute_path(self): meta.settings.SITE_PROTOCOL = "https" meta.settings.SITE_DOMAIN = "foo.com" m = Meta() self.assertEqual(m.get_full_url("/foo/bar"), "https://foo.com/foo/bar")
def test_get_full_url_without_site_id_will_raise(self): settings.USE_SITES = True settings.SITE_PROTOCOL = 'http' m = Meta() with self.assertRaises(ImproperlyConfigured): m.get_full_url('foo/bar')
def test_get_full_url_without_protocol_will_raise(self): m = Meta() with self.assertRaises(ImproperlyConfigured): m.get_full_url('foo/bar')
def get_page_meta(page, language): """ Retrieves all the meta information for the page in the given language :param page: a Page instance :param lang: a language code :return: Meta instance :type: object """ from django.core.cache import cache from meta.views import Meta from .models import PageMeta, TitleMeta try: meta_key = get_cache_key(page, language) except AttributeError: return None gplus_server = 'https://plus.google.com' meta = cache.get(meta_key) if not meta: meta = Meta() title = page.get_title_obj(language) meta.extra_custom_props = [] meta.title = page.get_page_title(language) if not meta.title: meta.title = page.get_title(language) if title.meta_description: meta.description = title.meta_description.strip() try: titlemeta = title.titlemeta if titlemeta.description: meta.description = titlemeta.description.strip() if titlemeta.keywords: meta.keywords = titlemeta.keywords.strip().split(',') meta.locale = titlemeta.locale meta.og_description = titlemeta.og_description.strip() if not meta.og_description: meta.og_description = meta.description meta.twitter_description = titlemeta.twitter_description.strip() if not meta.twitter_description: meta.twitter_description = meta.description meta.gplus_description = titlemeta.gplus_description.strip() if not meta.gplus_description: meta.gplus_description = meta.description if titlemeta.image: meta.image = title.titlemeta.image.canonical_url or title.titlemeta.image.url for item in titlemeta.extra.all(): attribute = item.attribute if not attribute: attribute = item.DEFAULT_ATTRIBUTE meta.extra_custom_props.append((attribute, item.name, item.value)) except (TitleMeta.DoesNotExist, AttributeError): # Skipping title-level metas if meta.description: meta.og_description = meta.description meta.twitter_description = meta.description meta.gplus_description = meta.description defaults = { 'object_type': meta_settings.FB_TYPE, 'og_type': meta_settings.FB_TYPE, 'og_app_id': meta_settings.FB_APPID, 'fb_pages': meta_settings.FB_PAGES, 'og_profile_id': meta_settings.FB_PROFILE_ID, 'og_publisher': meta_settings.FB_PUBLISHER, 'og_author_url': meta_settings.FB_AUTHOR_URL, 'twitter_type': meta_settings.TWITTER_TYPE, 'twitter_site': meta_settings.TWITTER_SITE, 'twitter_author': meta_settings.TWITTER_AUTHOR, 'gplus_type': meta_settings.GPLUS_TYPE, 'gplus_author': meta_settings.GPLUS_AUTHOR, } try: pagemeta = page.pagemeta meta.object_type = pagemeta.og_type meta.og_type = pagemeta.og_type meta.og_app_id = pagemeta.og_app_id meta.fb_pages = pagemeta.fb_pages meta.og_profile_id = pagemeta.og_author_fbid meta.twitter_type = pagemeta.twitter_type meta.twitter_site = pagemeta.twitter_site meta.twitter_author = pagemeta.twitter_author meta.gplus_type = pagemeta.gplus_type meta.gplus_author = pagemeta.gplus_author if meta.og_type == 'article': meta.og_publisher = pagemeta.og_publisher meta.og_author_url = pagemeta.og_author_url try: from djangocms_page_tags.utils import get_title_tags, get_page_tags tags = list(get_title_tags(page, language)) tags += list(get_page_tags(page)) meta.tag = ','.join([tag.name for tag in tags]) except ImportError: # djangocms-page-tags not available pass if not meta.image and pagemeta.image: meta.image = pagemeta.image.canonical_url or pagemeta.image.url for item in pagemeta.extra.all(): attribute = item.attribute if not attribute: attribute = item.DEFAULT_ATTRIBUTE meta.extra_custom_props.append((attribute, item.name, item.value)) except PageMeta.DoesNotExist: pass if meta.gplus_author and not meta.gplus_author.startswith('http'): if not meta.gplus_author.startswith('/'): meta.gplus_author = '{0}/{1}'.format(gplus_server, meta.gplus_author) else: meta.gplus_author = '{0}{1}'.format(gplus_server, meta.gplus_author) if page.publication_date: meta.published_time = page.publication_date.isoformat() if page.changed_date: meta.modified_time = page.changed_date.isoformat() if page.publication_end_date: meta.expiration_time = page.publication_end_date.isoformat() for attr, val in defaults.items(): if not getattr(meta, attr, '') and val: setattr(meta, attr, val) meta.url = page.get_absolute_url(language) return meta
def test_get_full_url_without_domain_will_raise(self): meta.settings.SITE_PROTOCOL = 'http' m = Meta() with self.assertRaises(ImproperlyConfigured): m.get_full_url('foo/bar')
def get_page_meta(page, language): """ Retrieves all the meta information for the page in the given language :param page: a Page instance :param lang: a language code :return: Meta instance :type: object """ from django.core.cache import cache from meta.views import Meta from .models import PageMeta, TitleMeta meta_key = get_cache_key(page, language) meta = cache.get(meta_key) if not meta: meta = Meta() title = page.get_title_obj(language) meta.title = page.get_title(language) try: titlemeta = title.titlemeta meta.description = titlemeta.description.strip() meta.keywords = titlemeta.keywords.strip().split(",") meta.locale = titlemeta.locale if titlemeta.image: meta.image = title.titlemeta.image.url except TitleMeta.DoesNotExist: # Skipping title-level metas pass try: pagemeta = page.pagemeta meta.object_type = pagemeta.og_type meta.og_type = pagemeta.og_type meta.og_app_id = pagemeta.og_app_id meta.og_profile_id = pagemeta.og_author_fbid meta.twitter_type = pagemeta.twitter_type meta.twitter_site = pagemeta.twitter_site meta.twitter_author = pagemeta.twitter_author meta.gplus_type = pagemeta.gplus_type meta.gplus_author = pagemeta.gplus_author meta.published_time = page.publication_date.isoformat() meta.modified_time = page.changed_date.isoformat() if page.publication_end_date: meta.expiration_time = page.publication_end_date.isoformat() if meta.og_type == 'article': meta.og_publisher = pagemeta.og_publisher if pagemeta.og_author_url: meta.og_author_url = pagemeta.og_author_url elif pagemeta.og_author: meta.og_author = { 'first_name': pagemeta.og_author.first_name, 'last_name': pagemeta.og_author.last_name } try: from djangocms_page_meta.utils import get_title_tags, get_page_meta tags = get_title_tags(page, language) tags += get_page_meta(page, language) meta.tag = ",".join(tags) except ImportError: # djangocms-page-meta not available pass if not meta.image and pagemeta.image: meta.image = pagemeta.image.url except PageMeta.DoesNotExist: # Skipping page-level metas pass if not meta.description and page.get_meta_description(language): meta.description = page.get_meta_description(language).strip() meta.url = page.get_absolute_url(language) return meta
def get_page_meta(page, language): """ Retrieves all the meta information for the page in the given language :param page: a Page instance :param lang: a language code :return: Meta instance :type: object """ from django.core.cache import cache from meta.views import Meta from .models import PageMeta, TitleMeta try: meta_key = get_cache_key(page, language) except AttributeError: return None meta = cache.get(meta_key) if not meta: meta = Meta() title = page.get_title_obj(language) meta.title = page.get_page_title(language) if not meta.title: meta.title = page.get_title(language) if title.meta_description: meta.description = title.meta_description.strip() try: titlemeta = title.titlemeta if titlemeta.description: meta.description = titlemeta.description.strip() if titlemeta.keywords: meta.keywords = titlemeta.keywords.strip().split(',') meta.locale = titlemeta.locale meta.og_description = titlemeta.og_description.strip() if not meta.og_description: meta.og_description = meta.description meta.twitter_description = titlemeta.twitter_description.strip() if not meta.twitter_description: meta.twitter_description = meta.description meta.gplus_description = titlemeta.gplus_description.strip() if not meta.gplus_description: meta.gplus_description = meta.description if titlemeta.image: meta.image = title.titlemeta.image.url except (TitleMeta.DoesNotExist, AttributeError): if meta.description: meta.og_description = meta.description meta.twitter_description = meta.description meta.gplus_description = meta.description # Skipping title-level metas pass try: pagemeta = page.pagemeta meta.object_type = pagemeta.og_type meta.og_type = pagemeta.og_type meta.og_app_id = pagemeta.og_app_id meta.og_profile_id = pagemeta.og_author_fbid meta.twitter_type = pagemeta.twitter_type meta.twitter_site = pagemeta.twitter_site meta.twitter_author = pagemeta.twitter_author meta.gplus_type = pagemeta.gplus_type meta.gplus_author = pagemeta.gplus_author if not meta.gplus_author.startswith('http'): if not meta.gplus_author.startswith('/'): meta.gplus_author = 'https://plus.google.com/{0}'.format(meta.gplus_author) else: meta.gplus_author = 'https://plus.google.com{0}'.format(meta.gplus_author) if page.publication_date: meta.published_time = page.publication_date.isoformat() if page.changed_date: meta.modified_time = page.changed_date.isoformat() if page.publication_end_date: meta.expiration_time = page.publication_end_date.isoformat() if meta.og_type == 'article': meta.og_publisher = pagemeta.og_publisher if pagemeta.og_author_url: meta.og_author_url = pagemeta.og_author_url try: from djangocms_page_tags.utils import get_title_tags, get_page_tags tags = list(get_title_tags(page, language)) tags += list(get_page_tags(page)) meta.tag = ','.join([tag.name for tag in tags]) except ImportError: # djangocms-page-tags not available pass if not meta.image and pagemeta.image: meta.image = pagemeta.image.url except PageMeta.DoesNotExist: # Skipping page-level metas pass meta.url = page.get_absolute_url(language) return meta
def test_get_full_url_with_domain_and_protocol(self): meta.settings.SITE_PROTOCOL = "https" meta.settings.SITE_DOMAIN = "foo.com" m = Meta() self.assertEqual(m.get_full_url("foo/bar"), "https://foo.com/foo/bar")