I don't think this is actually possible, but is there any clean and tidy way to get paginated content working with Django sitemaps?
For example, my landing page has news on it, and there are no permalinks to news posts, the only way to use them is to paginate 5 at a time through them all.
Another part gets lists of items in various genres and other criteria.
If it isn't possible, what is the best way to handle it? To not provide urls to the sitemap for any of these? To get just the first page for paginated pages?
My best idea is that I should just give the landing page as an url, and not bother with the listing pages at all since they aren't really important search engine-wise. But if this is the best course of action, how can I just provide a link to the landing page from within the sitemaps framework?
Any suggestions are welcome.
I've included urls for my paginated list views in the XML sitemap using the following code:
from django.conf import settings
from django.contrib.sitemaps import Sitemap
from django.core.paginator import Paginator
from django.core.urlresolvers import reverse
class ArticleListSitemap(Sitemap):
def items(self):
objects = Article.objects.all()
paginator = Paginator(objects, settings.ARTICLE_PAGINATE_BY)
return paginator.page_range
def location(self, page):
return reverse('article_list', kwargs={'page': page})
Related
Let's say I've created a blog for my website. The tree structure setup in the Wagtail admin looks like this:
Homepage > Blog Index > Blog Post
Is it possible to keep the Blog Index page in the admin page tree but remove it from the URL so that my URL's look like this:
Homepage > Blog Post
I am assigning a custom group to the Blog Index page which allows them to edit only Blog Posts that they have created, which is why Blog Index needs to stay in the tree on the admin side.
I've done a little work with the routablepagemixin but not to eliminate anything from the URL, only add to it.
I'm not entirely certain if a RoutablePageMixin is the right way to go about this, but that's how I've solved this before.
Here's an example of how you could do it with a RoutablePageMixin and a route (Note: I chopped this together pretty quickly and didn't test it, you might need to do some adjusting)
from django.http import HttpResponseRedirect
from wagtail.contrib.routable_page.models import RoutablePageMixin, route
from wagtail.core.models import Page
from blog.models import BlogPage
class HomePage(RoutablePageMixin, Page):
"""A home page class."""
# HomePage Fields here...
# This route will collect the blog slug
# We'll look for the live BlogPost page.
#route(r"^(?P<blog_slug>[-\w]*)/$", name="blog_post")
def blog_post(self, request, blog_slug, *args, **kwargs):
try:
# Get the blog page
blog_page = BlogPage.objects.live().get(slug=blog_slug)
except BlogPage.DoesNotExist:
# 404 or post is not live yet
return HttpResponseRedirect("/")
except Exception:
# Handle your other exceptions here; here's a simple redirect back to home
return HttpResponseRedirect("/")
# Additional logic if you need to perform something before serving the blog post
# Let the blog post page handle the serve
return blog_page.specific.serve(request, *args, **kwargs)
One other thing to note: you'll want to change the sitemap url on your original blog post pages so they don't show up as /blog/blog-slug/ inside of sitemap.xml.
I've created an app "Blog". In my app I've got several models including "BlogIndex(Page)". When I run local server I find myself at "home_page.html". What I want is to start my local server at "blog_index.html". I know that I can set a root page at settings>site>localhost to make my "blog_index.html" a root page, but I can't do this because in my app I've got some other models that live at the same level as "BlogIndex(Page)" and they are children of the root which is "HomePage" so it would brake my code. So my question is: can I make a redirect from "HomePage(Page)" to my "BlogIndex" so that when i start my server I would be automatically redirected from "HomePage" to "BlogIndex"? How can I do it? How much it will affect the performance of the site and it's optimization?
I know that there is settings>redirect but it works only for inactive pages, but i need "HomePage" to be active.
Thank you.
Perhaps a better approach would be to display your blog posts (and any other models you want) on your homepage. Just override get_context(). See here: Wagtail Views: extra context
Update:
You can redirect by overriding the serve() method. For example, in your model, you would do something like:
# home/models.py
...
from django.http import HttpResponseRedirect
from django.urls import reverse
class HomePage(Page):
body = RichTextField(blank=True)
content_panels = Page.content_panels + [
FieldPanel('body', classname="full"),
]
def serve(self, request):
# Redirect to blog index page
return HttpResponseRedirect('/blog/')
# only do this if you're using urls.py and namespaces
# return HttpResponseRedirect(reverse('blog:index'))
More info: http://docs.wagtail.io/en/latest/reference/pages/model_recipes.html?highlight=serve()#overriding-the-serve-method
I'm trying to build a super simple dashboard to show to users their Google Analytics data well formatted.
I'm using oAuth2Client and Django 1.10.4 and Python 3.5.
I've followed the example within the documentation and now I have a very simple app, the landing page will ask you to login, you click on a link to authorise, the Google page loads and asks you if you want to share your GA data and if you accept you are redirect to a page you can see only if you are logged in. All good so far.
However I can't manage to actually get users data, what's the best way to get for example the list of properties in a user's account or even better the number of page views a property had in the last week?
This is my code so far:
/pools/models.py
from django import http
from oauth2client.contrib.django_util import decorators
from django.views.generic import ListView
# from polls.models import GoogleAnalytic
from django.http import HttpResponse
# Google Analytics
from apiclient.discovery import build
# def index(request):
# return http.HttpResponse("Hello and Welcome! </br> </br> Click <a href='/profile_enabled'> here</a> to login")
#decorators.oauth_required
def get_profile_required(request):
resp, content = request.oauth.http.request(
'https://www.googleapis.com/plus/v1/people/me')
return http.HttpResponse(content)
#decorators.oauth_enabled
def get_profile_optional(request):
if request.oauth.has_credentials():
# this could be passed into a view
# request.oauth.http is also initialized
return http.HttpResponse('You are signed in.</br> </br>'+'User email: {}'.format(
request.oauth.credentials.id_token['email']) + "</br></br>Click <a href='/ga'> here </a> to view your metrics")
else:
return http.HttpResponse(
'Hello And Welcome!</br></br>'
'You need to sign in to view your data. </br></br>' +
'Here is an OAuth Authorize link:Authorize'
.format(request.oauth.get_authorize_redirect()))
########## MY CODE! ###############
#decorators.oauth_required
def google_analytics(object):
return HttpResponse('These are your results for last week:')
urls.py
from django.conf import urls
from polls import views
import oauth2client.contrib.django_util.site as django_util_site
urlpatterns = [
urls.url(r'^$', views.get_profile_optional),
urls.url(r'^profile_required$', views.get_profile_required),
# urls.url(r'^profile_enabled$', views.get_profile_optional),
urls.url(r'^oauth2/', urls.include(django_util_site.urls)),
urls.url(r'^ga/$', views.google_analytics)
]
settings.py
[...]
GOOGLE_OAUTH2_CLIENT_ID = 'XXX.apps.googleusercontent.com'
GOOGLE_OAUTH2_CLIENT_SECRET = 'XXX'
GOOGLE_OAUTH2_SCOPES = ('email','https://www.googleapis.com/auth/analytics')
So my problem is I don't really understand where Django saves the token to access the data of that particular user, I know it works because it prints out the email address correctly etc, but I can't figure out what I should add to def google_analytics(object): to actually get specific Google API methods.
If anyone has experience on these kind of things I would really appreciate some help! Thanks!
If you want to fetch Google Analytics configuration details e.g. Accounts, Web properties, Profiles, Filters, Goals, etc you can do that using Google Analytics Management API V3
If you want to fetch data of certain dimension and metrics from a Google Analytics view (aka profile), you can do that using either Core Reporting API V3 or Analytics Reporting API V4.
I think you will find the python api examples in their respective Guides.
I am creating a Django Project(which has a lot of Django apps in it) and I need some help.
I only need to add a small feature.
The admin will decide a date upto which the app will be shown to all.
I want the app to automatically redirect all users to a specific page after the mentioned date.
How should I proceed ?
A simple middleware (https://docs.djangoproject.com/en/1.7/topics/http/middleware/) will resolve your requirement. Something like this:
import datetime
from django.conf import settings
from django.http import HttpResponseRedirect
class OnOffMiddleware(object,):
def process_request(request):
if datetime.datetime.now() > settings.SHOW_DATE:
# Should redirect people
return HttpResponseRedirect('redirect to a specifc page')
else:
# Continue as usual
return None
Put the above in a module somewhere in your project and add it to the top of your MIDDLEWARE_CLASSES setting (https://docs.djangoproject.com/en/1.7/topics/http/middleware/#activating-middleware).
Why? I want multiple models on the first level of the path :)
Using: Django 1.4.1
Code setup urls:
PAGE_SLUGS = '|'.join(Page.objects.values_list('slug', flat=True))
BRAND_SLUGS = ... same concept
(r'^(?P<brand_slug>%s)/$' % BRAND_SLUGS, 'novomore.apps.catalog.views.product_showcase_list'),
url(r'^%s/$' % PAGE_SLUGS, 'prefab.apps.pages.views.page_detail', name='page'),
In the save method of model Page:
if self.pk is None:
clear_url_caches()
I don't want to run a query on each request so thats why i use this aproach, when i add a instance the PAGE_SLUGS need to be updated.
clear_url_caches() doesnt seem to work
Any suggestions?
This doesn't do the trick:
if settings.ROOT_URLCONF in sys.modules:
reload(sys.modules[settings.ROOT_URLCONF])
reload(importlib.import_module(settings.ROOT_URLCONF))
From How to reload Django's URL config:
import sys
from django.conf import settings
def reload_urlconf(self):
if settings.ROOT_URLCONF in sys.modules:
reload(sys.modules[settings.ROOT_URLCONF])
return import_module(settings.ROOT_URLCONF)
I don't think what you're trying to do is a good idea. Why not simply allow any slug pattern in the URL regex, but return a 404 if you can't find the Page in question? That would have the same effect and be much simpler.
url(r'^(?P<slug>\w+)/$', 'prefab.apps.pages.views.page_detail', name='page'),
then your view code can do something like
from django import shortcuts
def page_detail(request, slug):
page = shortcuts.get_object_or_404(Page, slug=slug)
...