尝试添加类别时,在/category/news.html“请求”处出现KeyError

时间:2019-04-14 15:22:08

标签: django django-models django-views

因此,我尝试为文章添加类别,但出现KeyError。这是我的模型:

class Category(models.Model):
    title       = models.CharField(max_length=100, db_index=True, null=True, blank=True)
    slug        = models.SlugField(max_length=100, db_index=True)

    def __str__(self):
        return self.title

    @permalink
    def get_absolute_url(self):
        return ('view_blog_category', None, { 'slug': self.slug })

这是我的视图和网址:

def view_category(request, slug):
    category = get_object_or_404(Category, slug=slug)
    return render_to_response('news/view_category.html', {'category': category,'posts': Article.objects.filter(category=category)[:5]})
urlpatterns = [
    url(r'^news/(?P<slug>[^\.]+)', ArticleView.as_view() , name='view_blog_post'),
    url(r'^category/(?P<slug>[^\.]+).html', view_category, name='view_blog_category'),
]

当我进入通过django admin添加的类别时,我得到一个KeyError at /category/news.html 'request',并且在呈现包含标记时显​​示错误。 (边栏)如果我删除此包含标记,则KeyError消失。但是在其他所有页面上,included标签也可以正常工作。仅在此类别页面上没有。有什么问题吗?

我认为我的网址有问题,但似乎找不到问题。

回溯:

Environment:


Request Method: GET
Request URL: http://localhost:8000/category/news.html

Django Version: 1.11
Python Version: 3.6.8
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.sites',
 'home',
 'news',
 'dynamic_scraper',
 'taggit']
Installed 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.contrib.sites.middleware.CurrentSiteMiddleware']


Template error:
In template /Users/rafrasenberg/cryptoupdate/src/cryptoupdate/home/templates/header.html, error at line 41
   request   31 :       <i class="close-icn ion-close"></i>
   32 :     </a>
   33 :     <div class="src-form">
   34 :       <form>
   35 :         <input type="text" placeholder="Search here">
   36 :         <button type="submit"><i class="ion-search"></i></a></button>
   37 :       </form>
   38 :     </div><!-- src-form -->
   39 : 
   40 :     <a class="menu-nav-icon" data-menu="#main-menu" href="#"><i class="ion-navicon"></i></a>
   41 :      {% header_menu %} 
   42 :     <div class="clearfix"></div>
   43 :   </div><!-- container -->
   44 : </header>
   45 : 

Traceback:

File "/Users/rafrasenberg/cryptoupdate/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
  41.             response = get_response(request)

File "/Users/rafrasenberg/cryptoupdate/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "/Users/rafrasenberg/cryptoupdate/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/Users/rafrasenberg/cryptoupdate/src/cryptoupdate/news/views.py" in view_category
  20.     return render_to_response('news/view_category.html', {'category': category,'posts': Article.objects.all()})

File "/Users/rafrasenberg/cryptoupdate/lib/python3.6/site-packages/django/shortcuts.py" in render_to_response
  21.     content = loader.render_to_string(template_name, context, using=using)

File "/Users/rafrasenberg/cryptoupdate/lib/python3.6/site-packages/django/template/loader.py" in render_to_string
  68.     return template.render(context, request)

File "/Users/rafrasenberg/cryptoupdate/lib/python3.6/site-packages/django/template/backends/django.py" in render
  66.             return self.template.render(context)

File "/Users/rafrasenberg/cryptoupdate/lib/python3.6/site-packages/django/template/base.py" in render
  207.                     return self._render(context)

File "/Users/rafrasenberg/cryptoupdate/lib/python3.6/site-packages/django/template/base.py" in _render
  199.         return self.nodelist.render(context)

File "/Users/rafrasenberg/cryptoupdate/lib/python3.6/site-packages/django/template/base.py" in render
  990.                 bit = node.render_annotated(context)

File "/Users/rafrasenberg/cryptoupdate/lib/python3.6/site-packages/django/template/base.py" in render_annotated
  957.             return self.render(context)

File "/Users/rafrasenberg/cryptoupdate/lib/python3.6/site-packages/django/template/loader_tags.py" in render
  177.             return compiled_parent._render(context)

File "/Users/rafrasenberg/cryptoupdate/lib/python3.6/site-packages/django/template/base.py" in _render
  199.         return self.nodelist.render(context)

File "/Users/rafrasenberg/cryptoupdate/lib/python3.6/site-packages/django/template/base.py" in render
  990.                 bit = node.render_annotated(context)

File "/Users/rafrasenberg/cryptoupdate/lib/python3.6/site-packages/django/template/base.py" in render_annotated
  957.             return self.render(context)

File "/Users/rafrasenberg/cryptoupdate/lib/python3.6/site-packages/django/template/loader_tags.py" in render
  216.                 return template.render(context)

File "/Users/rafrasenberg/cryptoupdate/lib/python3.6/site-packages/django/template/base.py" in render
  209.                 return self._render(context)

File "/Users/rafrasenberg/cryptoupdate/lib/python3.6/site-packages/django/template/base.py" in _render
  199.         return self.nodelist.render(context)

File "/Users/rafrasenberg/cryptoupdate/lib/python3.6/site-packages/django/template/base.py" in render
  990.                 bit = node.render_annotated(context)

File "/Users/rafrasenberg/cryptoupdate/lib/python3.6/site-packages/django/template/base.py" in render_annotated
  957.             return self.render(context)

File "/Users/rafrasenberg/cryptoupdate/lib/python3.6/site-packages/django/template/library.py" in render
  225.         _dict = self.func(*resolved_args, **resolved_kwargs)

File "/Users/rafrasenberg/cryptoupdate/src/cryptoupdate/home/templatetags/header_menu.py" in header_menu
  11.         'request': context['request'],

File "/Users/rafrasenberg/cryptoupdate/lib/python3.6/site-packages/django/template/context.py" in __getitem__
  87.         raise KeyError(key)

Exception Type: KeyError at /category/news.html
Exception Value: 'request'

编辑后的模板标签

@register.simple_tag(takes_context=True)
def header_menu(context):
    return {
        'header_menu': MenuItem.objects.all(),
        'request': context['request'],
    }

2 个答案:

答案 0 :(得分:1)

render_to_response未通过请求。您应该改用render

return render(request, 'news/view_category.html', ...)

但是尚不清楚为什么您仍要在标记代码中引用该请求。您不在那里使用它,是从上下文中仅将其直接传递回来的意义何在?

答案 1 :(得分:0)

错误在这里:

'request': context['request']

在您的header_menu模板标记中。您应该将模板标签装饰器更改为:

@register.simple_tag(takes_context=True)
def header_menu(context):
   # your template tag code

以便它可以使用视图传递的上下文