【发布时间】:2020-02-23 08:30:38
【问题描述】:
我一直在尝试在 Django 中为一项任务创建一个电影调查,我目前正在研究该功能。我似乎无法理解为什么它不能识别我传递的 URL。
我尝试删除框架站点上的 Django 教程中所示的硬编码 URL,但这并没有使错误消失。
这是 urls.py 的摘录:
urlpatterns = [
url(r'^$', views.index, name="index"),
path('movie=<int:movie_id>&user=<int:user_id>/', views.movie, name='movie'),
path('ratings/', views.ratings, name='movie'),
path('rating/<int:movie_id>/', views.rating, name='movie'),
path('movie=<int:movie_id>&user=<int:user_id>/vote/', views.vote, name='vote'),
path('register/',views.register, name='register'),
]
这是我的电影视图(应该显示一部电影和一个星级广播,供用户对电影进行评分),其中构建了 URL 并将其传递给 HTML:
def movie(request,movie_id,user_id):
movie = get_object_or_404(Movie, pk=movie_id)
voteURL = '/polls/movie=' + str(movie_id) + '&user='+str(user_id)+'/vote/'
context = {
'mymoviecaption':movie.Title,
'moviePoster': 'https://image.tmdb.org/t/p/original'+tmdb.Movies(movie.TMDBID).images().get('posters')[0].get('file_path'),
'myrange': range(10,0,-1),
'myuserid':user_id,
'voteurl': voteURL,
'mymovieid':movie_id
}
#print(nextURL)
translation.activate('en')
return HttpResponse(render(request, 'movieview.html', context=context))
HTML 摘录,其中调用了投票视图:
<form action="{% url voteurl %}" method="post">
{% for i in myrange %}
<input id="star-{{i}}" type="radio" name="rating" value={{i}}>
<label for="star-{{i}}" title="{{i}} stars">
<i class="active fa fa-star" aria-hidden="true"></i>
</label>
{% endfor %}
<input type="submit">Vote!</input>
</form>
投票视图(应该保存到数据库并重定向到下一部电影,还没有保存到数据库,因为在我确定我的功能可以工作之前,我不想把它与记录混为一谈):
def vote(request, movie_id,user_id):
try:
nextmovie=get_object_or_404(Movie, pk=movie_id+1)
nextURL = '/polls/movie=' + str(movie_id + 1) + '&user='+str(user_id)+'/'
except Http404:
nextURL = '/polls/ratings'
try:
myrating = int(request.POST['rating'])
print(myrating)
except:
# Redisplay the question voting form.
return render(request, '/polls/movie=' + str(movie_id + 1) + '&user='+str(user_id)+'/', {
'error_message': "You didn't select a choice.",
})
return HttpResponseRedirect(nextURL)
无论我尝试什么,每当我尝试加载第一个电影页面时,我都会在 /polls/movie=1&user=9/ 处获得 NoReverseMatch,尽管在 urlpatterns 中定义了所述 URL。
【问题讨论】:
-
您混淆了将参数传递给视图的不同范例。正如您在
path('movie=<int:movie_id>&user=<int:user_id>/'中所做的那样,路径和查询字符串不可互换。我建议您从头到尾遵循 Django 教程并尝试了解发生了什么,而不是复制/粘贴来自不同教程的随机摘录。
标签: python html django python-3.x django-rest-framework