在Django模板中转换星级评分

时间:2019-04-01 04:43:31

标签: python django python-3.x django-2.1

我正在使用Python(3.7)和Django(2.1)开发一个项目,在其中我想显示Django模板内部视图的平均评级回报。

这是到目前为止我尝试过的:

来自models.py

class Gig(models.Model):
    CATEGORY_CHOICES = (
        ('GD', 'Graphic & Design'),
        ('DM', 'Digital Marketing'),
        ('WT', 'Writing & Translation'),
        ('VA', 'Video & Animation'),
        ('MA', 'Music & Audio'),
        ('PT', 'Programming & Tech'),
        ('FL', 'Fun & Lifestyle'),
    )

    title = models.CharField(max_length=500)
    category = models.CharField(max_length=255, choices=CATEGORY_CHOICES)
    description = models.CharField(max_length=1000)
    price = models.IntegerField(blank=False)
    photo = models.FileField(upload_to='gigs')
    status = models.BooleanField(default=True)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    created_at = models.DateTimeField(default=timezone.now)

    def __str__(self):
        return self.title

class GigReview(models.Model):
    RATING_RANGE = (
        ('1', '1'),
        ('2', '2'),
        ('3', '3'),
        ('4', '4'),
        ('5', '5')
    )
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    gig = models.ForeignKey(Gig, on_delete=models.CASCADE, related_name='rates')
    order = models.ForeignKey(Order, on_delete=models.CASCADE, null=True)
    rating = models.IntegerField(choices=RATING_RANGE,)
    content = models.CharField(max_length=500)

    def __str__(self):
        return self.content

来自views.py

def home(request):
    gigs = Gig.objects.filter(status=True).annotate(avg_review=Avg('rates__rating'))
    return render(request, 'home.html', {'gigs': gigs})

因此,现在每个gig都有一个平均评分,我想在模板中显示星星作为评分。

来自home.html

{% for gig in gigs %}
   <div data-marker-id="59c0c8e33b1527bfe2abaf92" class="col-sm-6 col-xl-4 mb-5">
        <div class="card h-100 border-0 shadow">
             <div style="background-image: url(/media/{{ gig.photo }}); min-height: 200px;"
                                 class="card-img-top overflow-hidden dark-overlay bg-cover">
                   <a href="{% url 'gig-detail' gig.id %}" class="tile-link"></a>
                    <div class="card-img-overlay-bottom z-index-20"></div>
                    <div class="card-img-overlay-top d-flex justify-content-between align-items-center">
                    <div class="badge badge-transparent badge-pill px-3 py-2">{{ git.category }}</div>
                     <a href="javascript: void();" class="card-fav-icon position-relative z-index-40">
                      <svg class="svg-icon text-white">
                                            <use xlink:href="#heart-1"></use>
                                        </svg>
                                    </a>
                   </div>
                </div>
                <div class="card-body">
                     <h6 class="text-shadow"><a href="{% url 'gig-detail' gig.id %}"
                                                           style="text-decoration: none; color: black">
                                    {{ gig.title }}</a></h6>
                                <p class="mb-2 text-xs" id="stars">
                                    {{ gig.avg_review }}
                                    {% if gig.avg_review is not None %}
                                        {{ gig.avg_review }}
                                    {% endif %}
                                    <i class="fa fa-star text-warning"></i>
                                    <i class="fa fa-star text-warning"></i>
                                    <i class="fa fa-star text-warning"></i>
                                    <i class="fa fa-star text-warning"></i>
                                    <i class="fa fa-star text-gray-300"></i>
                                </p>
                                <p class="text-sm text-muted mb-3">{{ gig.description|slice:"20" }}...</p>
                                <p class="text-sm text-muted text-uppercase mb-1">
                                    <span>By <a href="{% url 'profile' gig.user.username %}"
                                                class="text-dark">{{ gig.user }}</a></span>
                                    <span class="float-right"><b class="text-shadow text-lg"
                                                                 style="color: black;">${{ gig.price }}</b></span>
                                </p>
                            </div>
                        </div>
                    </div>
                {% endfor %}

那么,如何将每个gig的平均评分显示为由评分填充的星星?

谢谢!

1 个答案:

答案 0 :(得分:1)

您可以使用django-star-rating等多种选择,也可以将多个JS库用作star-ratingstarability

我将使用可扩展性提供解决方案,尽管它可能主要是基于观点。

在您的模板中:

head标签中添加样式

<link rel="stylesheet" type="text/css" href="css/starability-all.min.css"/>

并使用以下内容:

<fieldset class="starability-result mx-auto" data-rating="{{ gig.avg_review }}">
    Rated: {{ gig.avg_review }} stars
</fieldset>

您可能需要将gig.avg_review转换为整数,我建议您在视图中进行转换。

适用性的主要问题是它不支持半颗星,但是如果您对此不太在意,则可以使用以下内容来取整平均值

from django.db.models import Func

class Round(Func):
    function = 'ROUND'
    template='%(function)s(%(expressions)s, 0)'

现在将其应用于您的查询:

gigs = Gig.objects.filter(status=True).annotate(avg_review=Round(Avg('rates__rating')))

有关更多信息,如果您决定使用它,建议您检查可追溯性的documentation