I’ve made a "paginator" app, that add such SEO optimisation for all my pages.
So I need to pass all visible page url through paginator.view
But, I want to keep my apps as structured as possible.
For an example here is a view for my gallery app:
gallery.views
from django.shortcuts import render
from gallery.models import GalleryItem
def home(request):
img_to_display = GalleryItem.objects.filter(published=True
).order_by('-date')
return render(request, 'gallery/all.html', locals())
...
Now I’m doing like that form my view in paginator :
My current paginator.views
from django.shortcuts import render, get_object_or_404, redirect
from gallery.models import GalleryItem
from paginator.models import Page
import gallery
def custom_page(request, url):
current_page = url
# just for the gallery page :
if url == 'gallery':
img_to_display = GalleryItem.objects.filter(published=True
).order_by('-date')
# for all my page
page_to_load = get_object_or_404(Page, name=url)
template_to_load = "paginator/" + page_to_load.template_name
return render(request, template_to_load, locals())
So I copy/paste my view and all dependencies, but that is really ugly, and not at all DRY, worth it’s not maintainable. I try something like that but it doesn’t work :
paginator.views : option1
from django.shortcuts import render
import gallery
def custom_page(request, url):
if url == 'gallery':
gallery.views.home(request)
if url == 'anotherpage':
anotherapp.views.home(request)
...
Or something like that :
paginator.views : option 2
from django.shortcuts import render
def custom_page(request, url):
if url == 'gallery':
include("gallery.views.py")
if url == 'anotherpage':
include("anotherapp.views.py")
...
Note: I prefer the last style option because it minimize the import at the start of the paginator.views file.
Thanks a lot for helping ! 🙂
2
Answers
Firstly I want to thanks Gocht to have sended me on a good way. So that's what I've done :
paginator.views
gallery.views
But yes, now, I understand that something like simP will be more clean. Thanks !
If you need a mechanism which is executed before the request is dispatched to a view, I would recommend using a middleware class. You can read more about it in the Django docs.
Another option is to use class based views to create a SEOView which can be inherited by every custom page view of yours. Some example of how it could look like:
To come back to your own options:
If you want to make #1 work, I guess you have to return the result of the view: