Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

KeyError in Django

I'm creating a clone of fiverr.com as a project.

There's a header in my base.html with category titles that if I click, should filter out only the gigs in the relevant category for display.

What happens is that it always redirects to home regardless. I have done some testing and believe it should be because of the KeyError, and no link is passed to the function correctly.

Code below:

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 (where the links are - tried another way of getting the same link for Graphics & Design, but results were similar)

<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'), 
like image 572
Jim Tay Avatar asked Mar 13 '23 03:03

Jim Tay


2 Answers

The view is receiving a slug value in link parameter. So, you should redefine the categories dictionary:

def category(request, link):

  categories = {
    "graphics-design": "GD",
    "digital-marketing": "DM",
    "video-animation": "VA",
    "music-audio": "MA",
    "programming-tech": "PT"
  }
  ...
like image 98
Cartucho Avatar answered Mar 24 '23 19:03

Cartucho


What is the URL that you are entering? It must be because the 'link' parameter did not find any key from your 'categories' dictionary.

Something like this(try it on your python command line):

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

By the way an advise for you when you are trying to catch. Use this syntax to see the error

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))
like image 30
Dean Christian Armada Avatar answered Mar 24 '23 20:03

Dean Christian Armada