我得到一个错误,说类别匹配查询不存在

2024-06-28 10:55:39 发布

您现在位置:Python中文网/ 问答频道 /正文

此代码的投票过程运行良好。只有在投票后重新定向选项时才会出现问题。
例外Type: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%}

Tags: divreturnobjectstitlerequesthtmlclassoptions