我一直关注this Django tutorial,我正在尝试删除硬编码的网址,但我无法使反向功能正常工作。
这是我的详细信息:
CurrentDb.Execute "DELETE * FROM StaffAtMeeting" & _
"WHERE RoomID =& Me.field1 AND MeetingDate = Me.field2 AND MeetingTime = Me.field3;"
这是urls.py:
def detail(request, question_id):
try:
question = Question.objects.get(pk=question_id)
except Question.DoesNotExist:
raise Http404("Question does not exist")
# How it was before:
# return render(request, 'polls/detail.html', {'question': question})
return HttpResponse(reverse('polls:detail', kwargs={'question': question}))
path('<int:question_id>/', views.detail, name='detail')
这是详细视图的模板:
app_name = 'polls'
urlpatterns = [
# ex: /polls/
path('', views.index, name='index'),
# ex: /polls/5/
path('<int:question_id>/', views.detail, name='detail'),
# ex: /polls/5/results/
path('<int:question_id>/results/', views.results, name='results'),
# ex: /polls/5/vote/
path('<int:question_id>/vote/', views.vote, name='vote'),
]
有人可以帮我这个或给出任何提示吗? 提前谢谢。
答案 0 :(得分:0)
我认为您的原始代码很好。如果您在另一个视图(例如,投票视图)中并想要将用户重定向到详细视图,则可以执行以下操作:
return HttpResponseRedirect(reverse('polls:detail', args=(question.id,)))
从教程的第4部分复制:https://docs.djangoproject.com/en/2.0/intro/tutorial04/#write-a-simple-form:
def vote(request, question_id):
question = get_object_or_404(Question, pk=question_id)
try:
selected_choice = question.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
# Redisplay the question voting form.
return render(request, 'polls/detail.html', {
'question': question,
'error_message': "You didn't select a choice.",
})
else:
selected_choice.votes += 1
selected_choice.save()
# Always return an HttpResponseRedirect after successfully dealing
# with POST data. This prevents data from being posted twice if a
# user hits the Back button.
return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
最后一行将用户从投票视图重定向到结果视图,并使用reverse()来避免对网址进行硬编码。