我面临一个问题。我是django和python的新手。当我运行我的APP时,我收到以下错误。
__import__(name)
File "/opt/lampp/htdocs/mysite/polls/urls.py", line 2, in <module>
from . import views
File "/opt/lampp/htdocs/mysite/polls/views.py", line 40
^
SyntaxError: invalid syntax
我正在解释下面的代码。
view.py:
from __future__ import unicode_literals
from django.shortcuts import get_object_or_404, render
from django.shortcuts import render
from .models import Choice, Question
from django.http import HttpResponseRedirect, HttpResponse
from django.urls import reverse
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
context = {'latest_question_list': latest_question_list}
return render(request, 'polls/index.html', context)
def detail(request, question_id):
try:
question = Question.objects.get(pk=question_id)
except Question.DoesNotExist:
raise Http404("Question does not exist")
return render(request, 'polls/detail.html', {'question': question})
def results(request, question_id):
question = get_object_or_404(Question, pk=question_id)
return render(request, 'polls/results.html', {'question': question})
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,))
我的另一个文件url.py
如下所示。
from django.conf.urls import url
from . import views
app_name = 'polls'
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'),
url(r'^(?P<question_id>[0-9]+)/results/$', views.results, name='results'),
url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'),
]
这里我需要知道语法错误的确切位置,请帮我解决此错误。
答案 0 :(得分:1)
你只是在view.py
的最后一行中错过了一个右括号return HttpResponseRedirect(reverse('polls:results', args=(question.id,))
应该是,
return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))