想要在django中显示评级星

时间:2016-06-06 05:26:04

标签: python django rating

我是django的新人,我有一个模型“专辑”,它有3个文件标题,流派和评级,我正在显示它们,我想显示数字“0”和专辑一样多的时间。我正在使用从0到album.rating的循环,但它只显示一次,即如果album.rating是2,那么“0”应该只显示2次,但在我的情况下,它只显示1次。请帮助我。提前谢谢。

以下是html的代码 -

   {% if albums %}
   {% for album in albums %}
   <tbody>
     <tr>
     <td>{{ album.album_title }}</td>
     <td>{{ album.genre }}</td>

      <!-- rating stars -->
      <td>
      {% for i in album.rating %}
      <option value={{i}}>0</option>
     {% endfor %}
      </td>


      <td>  
      <a href="{% url 'music:edit' album.id %}" class="btn btn-primary btn-sm" role="button">Edit</a>
      </td>
   <td>  

        </td>
        </tr>
       </tbody>

以下是view.py的代码

    def index(request):
    if not request.user.is_authenticated():
    return render(request, 'music/login.html')
else:
    albums = Album.objects.filter(user=request.user)
    paginator = Paginator(albums, 2) # Show 25 contacts per
    page = request.GET.get('page')
    try:
          albums = paginator.page(page)
    except PageNotAnInteger:
           # If page is not an integer, deliver first page.
           albums = paginator.page(1)
    except EmptyPage:
           # If page is out of range (e.g. 9999), deliver last page of results.
           albums = paginator.page(paginator.num_pages)
    song_results = Song.objects.all()
    query = request.GET.get("q")
    if query:
        albums = albums.filter(
            Q(album_title__icontains=query) |
            Q(artist__icontains=query)
        ).distinct()
        song_results = song_results.filter(
            Q(song_title__icontains=query)
        ).distinct()
        return render(request, 'music/index.html', {
            'albums': albums,
            'songs': song_results,
        })
    else:
        return render(request, 'music/index.html', {'albums': albums})

1 个答案:

答案 0 :(得分:2)

在解释之后,你无法实现这一点:

在你的情况下,

{% for i in album.rating %}就像{% for i in 2 %},结果证明,对于一个数字,它会循环一次。使用范围过滤器等。

我可以通过答案建议最快捷的方法:Check this

{% if albums %}
    {% for album in albums %}
    <tbody>
        <tr>
            <td>{{ album.album_title }}</td>
            <td>{{ album.genre }}</td>
            <!-- rating stars -->
            <td>
            {% with ''|center:album.rating as range %}
                {% for i in range %}
                    <option value={{i}}>0</option>
                {% endfor %}
            {% endfor %}
            </td>
            <td><a href="{% url 'music:edit' album.id %}" class="btn btn-primary btn-sm" role="button">Edit</a></td>
            <td></td>
        </tr>
    </tbody>
{% endif %}

拙见,请查看DJango模板过滤器并尝试检查 this

P.S:尚未评估解决方案