我制作了一个“paginator”应用,为我的所有网页添加了这样的SEO优化。 所以我需要通过paginator.view传递所有可见的页面URL 但是,我希望尽可能保持我的应用程序结构化。
这里的示例是我的图库应用的视图:
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())
...
现在,我正在这样做,形成我在分页器中的观点:
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())
所以我复制/粘贴我的视图和所有依赖项,但这真的很难看,而且根本不是DRY,值得它不可维护。我尝试过类似的东西,但它不起作用:
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)
...
或类似的东西:
from django.shortcuts import render
def custom_page(request, url):
if url == 'gallery':
include("gallery.views.py")
if url == 'anotherpage':
include("anotherapp.views.py")
...
注意:我更喜欢最后一个样式选项,因为它最小化了 paginator.views 文件开头的导入。
非常感谢您的帮助! :)
答案 0 :(得分:1)
如果您需要在将请求分派给视图之前执行的机制,我建议使用中间件类。您可以在Django docs中阅读更多相关信息。
另一种选择是使用基于类的视图来创建一个SEOView,它可以被你的每个自定义页面视图继承。它的一些例子如下:
from django.views.generic.base import View
class MySeoView(View):
def dispatch(self, request, *args, **kwargs):
# some logic for SEO
return super().dispatch(request, *args, **kwargs)
class CustomView1(MySeoView):
def get(self, request, *args, **kwargs):
# do normal stuff for this page
return HttpResponse(...)
def post(self, request, *args, **kwargs):
# maybe some other logic for posts
return HttpResponse(...)
回到你自己的选择:
如果你想让#1工作,我想你必须返回视图的结果:
...
if url == 'someUrl':
return gallery.views.home(request)
...
答案 1 :(得分:0)
首先,我要感谢Gocht以良好的方式向我发送信息。这就是我所做的:
def custom_page(request, url):
"""
Vue d'une page statique.
"""
if url == 'gallery':
import gallery
gal = gallery.views.render_gallery(request)
gal.render()
gallery_html = gal.rendered_content
if url == 'xxx':
...
page_to_load = get_object_or_404(Page, url=url)
template_to_load = "paginator/" + page_to_load.template_name
return render(request, template_to_load, locals())
from django.template.response import TemplateResponse
from gallery.models import GalleryItem
def render_gallery(request):
img_to_display = GalleryItem.objects.filter(published=True
).order_by('-date')
return TemplateResponse(request, 'gallery/gallery.html', locals())
但是,是的,现在,我明白像simP这样的东西会更干净。谢谢!