简体   繁体   中英

Reverse for 'ques_detail' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['ques_detail/(?P<pk>[0-9]+)/$']

I am getting the following error:

Reverse for 'ques_detail' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['ques_detail/(?P[0-9]+)/$']

Does anyone know how to solve it?

I tried solutions posted on many sites but nothing worked. Someone kindly help.

urls.py

from django.urls import path
from . import views
urlpatterns = [
    path('logout', views.logout, name='test_logout'),
    path('register', views.register, name = 'register'),
    path('', views.welcome, name='welcome'),
    path('instructions', views.instructions, name = 'instructions'),
    path('ques_detail/<int:pk>/',views.ques_detail,name='ques_detail')
]

views.py

def instructions(request):
    return render(request,'events/instructions.html')

def ques_detail(request, pk):
    ques = get_object_or_404(Questionm, pk=pk)
    return render(request, 'events/ques_detail.html', {'ques': ques})

instructions.html

{% extends 'base.html' %}
{% block content %}
    <div  class="register">
     <h1>Instructions</h1>
    </div>
    <br><br><hr><hr>
    <ul class="list-group">
      <li class="list-group-item">Lorem ipsum dolor sit amet, consectetur...</li>
    </ul>

    <div class="start">
        <button type="button" class="btn btn-success" style="width: 350px; 
height: 80px;font-size : 500px;"><a href="{% url 'ques_detail' pk=ques.pk %}"> 
<h4>Start Test</h4></a></button>
    </div>
{% endblock %}

Something is missing in the view instructions to call the Start Test page properly.

In the template you define the button with an url to call a question :

<button type="button" class="btn btn-success" style="width: 350px; 
    height: 80px;font-size : 500px;">
    <a href="{% url 'ques_detail' pk=ques.pk %}"> 
    <h4>Start Test</h4></a>
</button>

{% url 'ques_detail' pk=ques.pk %} will call the view ques_detail and try to pass the question ID with the parameter pk , OK, but you never define ques.pk here, that's why you got an empty string and the reverse error.

When instructions.html is rendered, you have to define a ques object in the context of the template, like you do with render(request, 'events/ques_detail.html', {'ques': ques}) .

So you could have a view like the following :

def instructions(request):
    ques = Questionm.objects.first()
    context = {'ques': ques}
    return render(request,'events/instructions.html', context)

(I query a question randomly ( Questionm.objects.first() ) you will have to replace this to query the question you need.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM