“a href”HTML链接中的NoReverseMatch

时间:2017-04-03 07:02:35

标签: python html django django-views

我正在尝试创建一个链接,重定向到我的django应用程序中的另一个页面,我有视图,我有网址,我有模板,一切都在我的眼里,但是当我尝试'href '链接的页面我得到以下错误:

  

使用参数'()'和关键字反转'views.candidate_detail'   参数'{​​'pk':''}'找不到。尝试了0种模式:[]

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'), 

]

模板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>

2 个答案:

答案 0 :(得分:1)

您应该遍历candidates QuerySet而不是lista2列表。然后你就可以这样做:

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

答案 1 :(得分:0)

href替换为以下内容:

{% 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>

在Django中,当使用url引用视图时,您需要使用name

中为其定义的urls.py属性

OP:文件enter image description here

的屏幕截图