简体   繁体   中英

NoReverseMatch in 'a href' HTML link

I'm trying to make a link that redirects to another page in my django application, I have the view, I have the url and I have the template, all are ok in my eyes, but when I try to 'href' the page to do the link I get the Following error:

Reverse for 'views.candidate_detail' with arguments '()' and keyword arguments '{'pk': ''}' not found. 0 pattern(s) tried: []

views.py

from django.shortcuts import render, get_object_or_404
from .models import Candidate, Criterion, Evaluation
from django import forms
from .forms import CandForm
from .forms import EvalForm
from .forms import TestForm
from django.shortcuts import redirect
from django.db import IntegrityError

def canditate_list(request):
    candidates = Candidate.objects.all()
    evaluation = Evaluation.objects.all()

    ######################## Ponho todos os candidatos e suas respectivas médias em um array em formato dict({Candidato:N})
    sum = 0
    cont = 1
    med = 0
    lista = []
    for cand in candidates:
        cont = 0
        sum = 0
        med = 0
        for e in evaluation:
            if cand == e.candidate:
                sum += e.score
                cont += 1
        if cont > 0:
            med = sum / cont  

        data = {str(cand):med}              ## a Key recebe o candidato no formato string
        lista += [data]

    ##### passo os dicionários contidos na lista anterior para outra lista convertendo-os em string
    lista2 = []
    for l in lista:
        lista2 += [str(l)]

    lista2 = [re.sub(r'[^\w\d.:]+',"",e) for e in lista2]

    eval_cand_list = []                                     #aqui guarda uma lista com os FK candidates convertidos p/ str
    context = {
        'candidates': candidates,
        'evaluation': evaluation,
        'lista2':lista2
    }
    return render(request, 'app/candidate_list.html',context)

def candidate_detail(request, pk):
    candidate = get_object_or_404(Candidate, pk=pk)
    c_name = candidate.name                                 #pega o nome (string) do candidato
    c1 = Evaluation.objects.all()                           #guarda tds Evaluation na variavel  
    scores = []                                             #declara a array que vai receber as notas
    for c in c1:                                            
        cand = str(c.candidate)                             #guarda o nome do candidato do Evaluation atual
        if cand == c_name:                                  #confere se o Evaluation atual corresponde ao candidate atual(pk)
            scores += [c.score]

    soma = 0                                                #variavel que guardara a soma declarada
    for s in scores:
        soma += s                                           #faz a soma dos scores

    average = 0 
    if len(scores) > 0:
        average = soma/len(scores)                              #tira a média

    context = {
        'candidate': candidate,
        'average': average,
    }

    return render(request, 'app/candidate_detail.html', context)

urls.py

from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^$', views.canditate_list, name='canditate_list'),
    url(r'^candidato/(?P<pk>[0-9]+)/$', views.candidate_detail, name='candidate_detail'),
    url(r'^cadastrar/$', views.register, name='register'),  # <--! o cadastro fica num link independete
    url(r'^grid/$', views.grid, name='grid'),
    url(r'^candidato/[0-9]+/avaliacao/$', views.evaluation, name='evaluate'), 

]

template html:

{% load staticfiles %}
{% load mathfilters %}
<!DOCTYPE html>
<html>
<head>
    <title>Lista de candidatos</title>
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
    <link href="https://fonts.googleapis.com/css?family=Lobster&subset=latin,latin-ext" rel="stylesheet" type="text/css"> 
    <link href="{% static 'css/app.css' %}" rel="stylesheet">   
</head>
<body>
    <h1 class="h1t">Lista de Candidatos</h1>
    {% for l in lista2 %}
        <p class="tr"><a href="{% url 'views.candidate_detail' pk=post.pk %}">{{l}}</a></p>
    {% endfor %}

</body>
</html>

You should iterate over the candidates QuerySet instead of the lista2 list. Then you can do it like this:

{% for candidate in candidates %}
    <p class="tr">
        <a href="{% url 'candidate_detail' candidate.pk %}">{{ candidate }}</a>
    </p>
{% endfor %}

Replace href to the following:

{% load staticfiles %}
{% load mathfilters %}
<!DOCTYPE html>
<html>
<head>
    <title>Lista de candidatos</title>
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
    <link href="https://fonts.googleapis.com/css?family=Lobster&subset=latin,latin-ext" rel="stylesheet" type="text/css"> 
    <link href="{% static 'css/app.css' %}" rel="stylesheet">   
</head>
<body>
    <h1 class="h1t">Lista de Candidatos</h1>
    {% for l in lista2 %}
        <p class="tr"><a href="{% url 'candidate_detail' post.pk %}">{{l}}</a></p>
    {% endfor %}

</body>
</html>

In Django, when referencing a view using url , you need to use the name attribute that you have defined for it in the urls.py

Screenshot from OP: file 在此处输入图片说明

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