,可以通过以下步骤完成:
from django.db import models
class Rating(models.Model):
score = models.IntegerField()
object = models.ForeignKey('YourObjectModel', on_delete=models.CASCADE)
from django import forms
class RatingForm(forms.Form):
score = forms.ChoiceField(choices=[(1, '1 star'), (2, '2 stars'), (3, '3 stars'), (4, '4 stars'), (5, '5 stars')])
from django.views.generic.edit import FormView
class RatingView(FormView):
template_name = 'rating.html'
form_class = RatingForm
success_url = '/thank-you/'
def form_valid(self, form):
score = form.cleaned_data['score']
object_id = self.kwargs['object_id'] # 从URL参数中获取对象的ID
object = YourObjectModel.objects.get(id=object_id)
Rating.objects.create(score=score, object=object)
return super().form_valid(form)
<!-- rating.html -->
<form method="post">
{% csrf_token %}
{{ form }}
<button type="submit">Submit</button>
</form>
from django.urls import path
urlpatterns = [
path('rating/<int:object_id>/', RatingView.as_view(), name='rating'),
]
这样,用户就可以通过访问/rating/<object_id>/
来进行评级了。在评级系统中,可以根据具体的业务需求进行扩展,例如添加用户认证、显示平均评分等功能。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云