Django中的KeyError

时间:2016-06-02 02:16:55

标签: python django keyerror

我正在创建一个fiverr.com的克隆项目。

我的base.html中有一个带有类别标题的标题,如果我点击该标题,则应仅过滤相关类别中的演出以供显示。

无论如何,它总会重定向到家中。我做了一些测试,并认为它应该是因为KeyError,并且没有正确的链接传递给函数。

以下代码:

views.py

def category(request, link):

  categories = {
      "Graphics & Design": "GD",
      "Digital & Marketing": "DM",
      "Video & Animation": "VA",
      "Music & Audio": "MA",
      "Programming & Tech": "PT"
  }
  try:
      gigs = Gig.objects.filter(category=categories[link])
      return render(request, 'home.html', {"gigs": gigs})
  except KeyError:
      return redirect('home')

models.py

class Gig(models.Model):
  CATEGORY_CHOICES = (
      ("GD", "Graphics & Design"),
      ("DM", "Digital & Marketing"),
      ("VA", "Video & Animation"),
      ("MA", "Music & Audio"),
      ("PT", "Programming & Tech")
  )
  title = models.CharField(max_length=500)
  category = models.CharField(max_length = 2, choices=CATEGORY_CHOICES)
  description = models.CharField(max_length=1000)
  price = models.IntegerField(default=6)
  photo = models.FileField(upload_to='gigs')
  status = models.BooleanField(default=True)
  user = models.ForeignKey(User)
  create_time = models.DateTimeField(default=timezone.now)

  def get_absolute_url(self):
      return reverse('my_gigs') 

  def __str__(self):
      return self.title

base.html (链接在哪里 - 尝试获取图形和设计相同链接的其他方式,但结果类似)

<nav class="navbar navbar-light bg-faded">
    <div class="container">
      <ul class="nav navbar-nav">
        <li class="nav-item active">
          <a class="nav-link" href='category/graphics-design'>Graphics &       Design <span class="sr-only">(current)</span></a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="{% url 'category' 'digital-marketing' %}">Digital Marketing</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="{% url 'category' 'video-animation' %}">Video & Animation</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="{% url 'category' 'music-audio' %}">Music & Audio</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="{% url 'category' 'programming-tech' %}">Programming & Tech</a>
        </li>
      </ul>
    </div>
  </nav>

urls.py

url(r'^category/(?P<link>[\w|-]+)/$', views.category, name='category'), 

2 个答案:

答案 0 :(得分:4)

视图在link参数中收到 slug值。因此,您应该重新定义categories字典:

def category(request, link):

  categories = {
    "graphics-design": "GD",
    "digital-marketing": "DM",
    "video-animation": "VA",
    "music-audio": "MA",
    "programming-tech": "PT"
  }
  ...

答案 1 :(得分:1)

您输入的网址是多少?必须是因为'link'参数没有找到'categories'字典中的任何键。

像这样(在你的python命令行上试试):

>>> x = {'name': 'dean'}
>>> x['xx']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'xx'
>>> 

顺便提一下,当你想抓住时给你一个建议。使用此语法查看错误

import sys

try:
    # Code here
except:
    # Prints the error and the line that causes the error
    print ("%s - %s at line: %s" % (sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2].tb_lineno))