如何将值转换为模板中循环内的字符串

时间:2017-03-24 02:13:22

标签: python django django-models django-templates django-views

我想要做以下事情: 在tamplate candidate_list 中,我列出了所有注册的候选人,我必须在他旁边显示候选人的平均值,但是候选人的平均值会保存在另一个模型中(评估)。所以我尝试了一个循环for循环内部显示候选者(候选者),在第二个循环中,他搜索具有候选人属性的评估(它是一个ForeignKey)和与 candidate.name 进行比较,在extern循环中进行,但是 candidate.name 是一个字符串,而evaluate.candidate是一个ForeignKey,我想将此属性转换为字符串并进行比较,但我真的不知道如何做到这一点,我尝试了以下内容:

模板:candidate_list.html

 {% load staticfiles %}
<!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><a href="/"> Lista de candidatos: </a></h1>
    {% block content %}
        {% for cand in candidates %}
            <p>
            <div><a href="{% url 'candidate_detail' pk=cand.pk %}">Nome:{{ cand.name }}</a></div>
            <!--<div id="average">Média:{{cand.average}}</div>-->
            </p>
            {% for e in eva %}
                {% if e.candidate |stringformat:" "  == cand.name %}
                    <p>{{ e.score }}</p>
                {% endif %} 
            {% endfor %}        
        {% endfor %}
    {% endblock content %}

</body>
</html>

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 django.shortcuts import redirect


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

    eva = Evaluation.objects.all()
    eval_cand_list = []                                     #aqui guarda uma lista com os FK candidates convertidos p/ str

    context = {
        'candidates': candidates,
        'eva': eva
    }
    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]

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

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

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



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

def evaluation(request):
    if request.method == "POST":
        form2 = EvalForm(request.POST)

        if form2.is_valid():    
            post = form2.save(commit=False)
            post.save()
            return redirect('canditate_list') 

    else:
        form2 = EvalForm()
        return render(request, 'app/evaluation.html', {'criterions': form2,})


def register(request):
    if request.method == "POST":
        form = CandForm(request.POST)
        if form.is_valid():
            post = form.save(commit=False)
            post.save()
            return redirect('candidate_detail', pk=post.pk)
    else:
        form = CandForm()
    return render(request, 'app/register.html', {'form': form})

models.py

from django.db import models
from jsonfield import JSONField
from site_.settings import MEDIA_ROOT
from django.core.validators import MaxValueValidator

class Criterion(models.Model):
    label = models.CharField(max_length=100)

    def  __str__(self):
        return self.label

class Candidate(models.Model):
    name = models.CharField(max_length=100)
    e_mail = models.EmailField(max_length=100, default = '')
    github = models.URLField(default = '')
    linkedin = models.URLField(max_length=100, default = '')
    cover_letter = models.TextField(default = '')
    higher_education = models.BooleanField(default = False)
    average = models.IntegerField(default = 0)
    #############################################################score = models.ForeignKey()
    docfile = models.FileField(upload_to='/home/douglas/Documentos/Django/my-second-blog/site_/media', null=True, blank=True)

    def  __str__(self):
        return self.name


class Evaluation(models.Model):
    candidate = models.ForeignKey(Candidate, unique=True)
    criterion = models.ForeignKey(Criterion, default='')
    score = models.PositiveIntegerField(default = 0, validators=[MaxValueValidator(10)])
    appraiser = models.ForeignKey('auth.User')

    def  __str__(self):
        return str(self.candidate)

1 个答案:

答案 0 :(得分:0)

无需更改为字符串格式即可从评估中获取详细信息,因为Candidate中的名称是外键。我相信下面的代码应该可以正常工作。

{% for e in candidate.evaluation_set.all %}
    <p>{{ e.score }}</p>
{% endfor %}