[python:django]属性错误

zengzsys  于 2021-09-08  发布在  Java
关注(0)|答案(1)|浏览(247)

我正在学习django教程,但我被困在第4部分。当我尝试运行服务器时,我得到错误“attributeerror:module'polls.views'没有属性'resultsview'”
我的代码:polls/views.py

from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from .models import Question, Choice
from django.template import loader
from django.urls import reverse

def index(request):
    latest_question_list = Question.objects.order_by('-pub_date')[:5]
    template = loader.get_template('polls/index.html')
    context = {
        'latest_question_list': latest_question_list
    }
    return render(request, 'polls/index.html', context)

def detail(request, question_id):
    question =get_object_or_404(Question, pk=question_id)
    return render(request, "polls/detail.html", {'question':question})

def results(request, question_id):
    response = "You are looking at results of question %s"
    return HttpResponse(response % question_id)
    #render(request, 'polls/results', {"question_id": question_id})
    #HttpResponse(response % question_id)

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):

        return render(request, 'polls/detail.html', {
            'question' : question,
            "error_message" : "You didn't select a choice'",
    })
    else:
        selected_choice.votes += 1
        selected_choice.save()
        return HttpResponseRedirect(reverse('polls:results', args=[question.id]))

# Create your views here.

轮询/url.py

from django.urls import path
from . import views

app_name = 'polls'

urlpatterns=[
    path("", views.index, name="index"),
    path("<int:question_id>/", views.detail, name="detail"),
    path("<int:pk>/results/", views.ResultsView.as_view(), name="results"),
    path("<int:question_id>/vote/", views.vote, name="vote"),
]

polls/results.html

<h1>{{ question.question_text }}</h1>
<ul>
{% for choice in question.choice_set.all %}
    <li>{{ choice.choice_text}} -- {{ choice.votes }} vote{{ choice.votes|pluralize}}</li>
{% endfor %}
<ul/>

</ul>

<a href = '{% polls:detail question.id %}'>Vote again?</a>

对不起,如果我犯了什么错误。这是我的第一个问题。

gzszwxb4

gzszwxb41#

你应该把 views.results 而不是 views.ResultView.as_viewset() . 您只编写了一个函数,而不是一个视图集。

urlpatterns=[
    path("", views.index, name="index"),
    path("<int:question_id>/", views.detail, name="detail"),
    path("<int:question_id>/results/", views.results, name="results"),
    path("<int:question_id>/vote/", views.vote, name="vote"),
]

相关问题