我收到一条错误消息,指出类别匹配查询不存在

时间:2019-03-11 18:37:20

标签: python django

此代码的投票程序运行良好。问题仅在表决选项后重定向时发生。
异常类型:DoesNotExist
异常值:
类别匹配查询不存在。
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%}

1 个答案:

答案 0 :(得分:1)

您混淆类别和选项。该表单发送该选项的段,但随后您使用相同的段重定向到类别视图。但这是两种不同的模型。