Job Search Engine


1013 浏览 5 years, 8 months

2.9 面包屑导航

版权声明: 转载请注明出处 http://www.codingsoho.com/

面包屑导航

安装

pip install django-breadcrumbs==1.1.3

设置

添加下面两个app到INSTALLED_APP

    'django.contrib.sites',
    'django.contrib.flatpages',

他们是breadcrumb的依赖,添加sites之后,记得添加

SITE_ID = 1

中间件

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.locale.LocaleMiddleware',
    'breadcrumbs.middleware.BreadcrumbsMiddleware',  # (1) 添加
]

这儿碰到了一个问题: middleware报错

    mw_instance = middleware(handler)
TypeError: object() takes no parameters

主要原因是:Django1.10 引入了一种新的中间件,可以使用 MiddlewareMixin 进行兼容。

https://stackoverflow.com/questions/42232606/django-exception-middleware-typeerror-object-takes-no-parameters

我手动进库做了修改,这个目前暂时workaround过去

视图

在视图里添加path信息

class JobEntryListView(ListView):
    model = JobEntry
    def dispatch(self, request, *args, **kwargs):
        request.breadcrumbs([
            (_("Home"),reverse("home", kwargs={})),
            (_('Job Entry List'),request.path_info),
        ])
        return super(JobEntryListView, self).dispatch(request,args,kwargs)    

class JobEntryDetailView(DetailView):
    model = JobEntry
    def dispatch(self, request, *args, **kwargs):
        request.breadcrumbs([
            (_("Home"),reverse("home", kwargs={})),
            (_('Job Entry List'),reverse("job_entry_list", kwargs={})),
            (self.get_object(),request.path_info),
        ])
        return super(JobEntryDetailView, self).dispatch(request,args,kwargs)  

模板

模板添加代码

  <div class=container> 
    {% block breadcrumb %}
      {% for breadcrumb in request.breadcrumbs %}
      <a href="{{ breadcrumb.url }}">{{ breadcrumb.name }}</a>{% if not forloop.last %} &raquo; {% endif %}
      {% endfor %}    
    {% endblock %}
  </div>

最终效果图如下