user9615577
user9615577

Reputation:

i am getting an error saying category matching query does not exist

The voting proceess is working fine with this code. The problem is only when redirecting after voting the options.
Exception Type:DoesNotExist
Exception Value:
Category matching query does not exist.
category = Category.objects.get(slug=slug)

urls.py

path('<slug>/',views.options,name='options'),
path('<slug>/vote/', views.vote, name='vote'),

views.py

 def home(request):
        categories = Category.objects.filter(active=True)
        return render(request,'rank/base.html',{'categories': categories,'title':'TheRanker'})

 def options(request,slug):
        category = Category.objects.get(slug=slug)
        options = Option.objects.filter(category=category)
        return render(request,'rank/options.html',{'options':options,'title':'options'})

def vote(request,slug):
    option = Option.objects.get(slug=slug)
    if Vote.objects.filter(slug=slug,voter_id=request.user.id).exists():
        messages.error(request,'You Already Voted!')
        return redirect('rank:options',slug)
    else:
        option.votes += 1
        option.save()
        voter = Vote(voter=request.user,option=option)
        voter.save()
        messages.success(request,'Voted!')
        return redirect('rank:options',slug)

options.html

{% extends "rank/base.html" %}
 <title>{% block title %}{{title}}{% endblock title%}</title>
{% load bootstrap4 %}
{% block content %}
<center><br>
     <center>{% bootstrap_messages %}</center>
     <ol type="1">
    {% for option in options %}

     <div class="col-lg-6 col-md-6 mb-6">
              <div class="card h-100">
                <div class="card-body">
                    <b><li>
                  <img src="/media/{{option.image}}" width="200" height="100">
                 <h4>{{option.name}}
                  </h4>
                  <h5 class="card-text">{{ option.details}}</h5>
                      <h5>{{ option.votes }} votes</h5>
                       <form action="{% url 'rank:vote' option.slug %}" method="post">
                           {% csrf_token %}
                <input type="submit" class="btn btn-success" value="Vote" >
                       </form>
                 </li></b>
                </div>
                <div class="card-footer">
                  <small class="text-muted"></small>
                </div>
              </div>
                </div>

    {% endfor %}
     </ol>
</center>



{% endblock content%}

Upvotes: 0

Views: 65

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599628

You're confusing categories and options. The form sends the slug of the option, but then you redirect to the categories view using the same slug. But those are two different models.

Upvotes: 1

Related Questions