python - KeyError in Django -
newbie django here, i'm creating clone of fiverr.com project.
there's header in base.html category titles if click, should filter out gigs in relevant category display.
what happens redirects home regardless. have done testing , believe should because of keyerror, , no link passed function correctly.
thanks in advance!
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 links - tried way of getting same link graphics & design, results 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'),
the view receiving slug value in link
parameter. so, should redefine categories
dictionary:
def category(request, link): categories = { "graphics-design": "gd", "digital-marketing": "dm", "video-animation": "va", "music-audio": "ma", "programming-tech": "pt" } ...