我是Django的新手,我在其他网站上发现了很多,但没有什么可以帮助我。我正在制作一个电影评级应用程序,它有一个滑块可以控制你想要制作电影的星数,然后取出这个数字并将其添加到星总数中,然后获得投票数并找到平均星数对于电影。现在我无法获得存储在服务器上的值,即使用提交按钮更新的总星数和总投票数。
目前这是我的模板表格
<form action="{% url 'polls:vote' %}" method="post">{% csrf_token %}
<input action="/vote/" name="myvote" related-image-id="votes{{movie.Movie_Title}}" type="range" min="1" max="5" value="0" oninput="mySlider(this)">
<input type="submit" value="Vote!"/>
</form>
这是我的网址文字
from django.conf.urls import url
from . import views
app_name ='polls'
urlpatterns = [
url(r'^', views.index, name='index'),
url(r'^', views.vote, name='vote'),
]
views.py
def index(request):
data=Movies.objects.order_by('-pub_date')
for movie in data:
if movie.Total_Number_of_Votes==0:
movie.avg="No one has voted for this yet be the first"
else:
movie.avg=movie.Total_Number_of_Stars/movie.Total_Number_of_Votes
return TemplateResponse(request, 'polls/index.html', {"data": data})
def vote(self, request):
movie=get_object_or_404(Movies)
thisVote=movie.choice_set.get(pk=request.POST['myvote'])
movie.Total_Number_of_Stars=movie.Total_Number_of_Stars+ thisVote
movie.Total_Number_of_Stars.save()
movie.Total_Number_of_Votes += 1
movie.Total_Number_of_Votes.save()
return HttpResponseRedirect(reverse(request, 'polls:index.html'))
我的印象是它与HttpResponse有关,但我不确定我对这一切都很新。任何帮助将不胜感激
答案 0 :(得分:0)
好吧,首先你的vote
视图有一个大问题。
movie=get_object_or_404(Movies)
行上,您调用Movies
类,而不是数据库中的实际电影实例。这就是您的观点应该是什么样子。
def vote(request, pk): # pk would be the Movie's primary key (id)
movie=get_object_or_404(Movies, pk=pk) # This makes the movie var an ACTUAL movie
thisVote=movie.choice_set.get(pk=request.POST['myvote'])
movie.Total_Number_of_Stars=movie.Total_Number_of_Stars+ thisVote
movie.Total_Number_of_Votes += 1
movie.save() # Need to save the movie object and only once
return HttpResponseRedirect(reverse(request, 'polls:index.html'))
由于您正在更改函数参数,因此您还需要更改urlconf。
url(r'^(?P<pk>[0-9]+)/vote/$', views.vote, name='vote'), # Needs to be explicit