python - Django,测试应用程序的行为

标签 python django

文件/Django-apps/poolApp/polls/urls.py 定义如下:

from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^$', views.IndexView.as_view(), name='index'),
    url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'),
    url(r'^(?P<pk>[0-9]+)/results/$', views.ResultsView.as_view(), name='results'),
    url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'),
]

文件views.py如下:

from django.http      import Http404
from django.shortcuts import render
from django.shortcuts import get_object_or_404, render
from django.http      import HttpResponse

from .models import Question

class IndexView(generic.ListView):
    template_name = 'polls/index.html'
    context_object_name = 'latest_question_list'

    def get_queryset(self):
        """Return the last five published questions."""
        return Question.objects.order_by('-pub_date')[:5]

class DetailView(generic.DetailView):
    model = Question
    template_name = 'polls/detail.html'

class ResultsView(generic.DetailView):
    model = Question
    template_name = 'polls/results.html'

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

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 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):
    p = get_object_or_404(Question, pk=question_id)
    try:
        selected_choice = p.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        # Redisplay the question voting form.
        return render(request, 'polls/detail.html', {
            'question': p,
            '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=(p.id,)))

我正在尝试测试应用程序的行为:

>>> from django.test import Client
>>> client = Client()
>>> response = client.get('/')

现在我从该地址提取了 404,但我得到了这个错误:

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/Django-1.8.3-py2.7.egg/django/test/client.py", line 500, in get
    **extra)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.8.3-py2.7.egg/django/test/client.py", line 303, in get
    return self.generic('GET', path, secure=secure, **r)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.8.3-py2.7.egg/django/test/client.py", line 379, in generic
    return self.request(**r)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.8.3-py2.7.egg/django/test/client.py", line 466, in request
    six.reraise(*exc_info)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.8.3-py2.7.egg/django/core/handlers/base.py", line 119, in get_response
    resolver_match = resolver.resolve(request.path_info)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.8.3-py2.7.egg/django/core/urlresolvers.py", line 366, in resolve
    for pattern in self.url_patterns:
  File "/usr/local/lib/python2.7/dist-packages/Django-1.8.3-py2.7.egg/django/core/urlresolvers.py", line 402, in url_patterns
    patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.8.3-py2.7.egg/django/core/urlresolvers.py", line 396, in urlconf_module
    self._urlconf_module = import_module(self.urlconf_name)
  File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "/home/devuser/Django-apps/poolApp/poolApp/urls.py", line 20, in <module>
    url(r'^polls/', include('polls.urls', namespace="polls")),
  File "/usr/local/lib/python2.7/dist-packages/Django-1.8.3-py2.7.egg/django/conf/urls/__init__.py", line 33, in include
    urlconf_module = import_module(urlconf_module)
  File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "/home/devuser/Django-apps/poolApp/polls/urls.py", line 3, in <module>
    from . import views
  File "/home/devuser/Django-apps/poolApp/polls/views.py", line 8, in <module>
    class IndexView(generic.ListView):
NameError: name 'generic' is not defined

最佳答案

您必须在 views.py 中导入 django.views.generic,如下所示:

from django.views import generic

关于python - Django,测试应用程序的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31683691/

相关文章:

python - 根据python中训练和测试集的时间戳为每个用户拆分数据集

python - 为什么 find_all 会报错,即使 just find 没有报错? ( python 美汤)

Pythonic 相当于 unshift 或 redo?

Django 模型中的多态性

python - Django Userena 更改 url 监护人错误

django - 反转 'edit_user',参数 '(2L,)' 和关键字参数 '{}' 未找到。 0 种模式已尝试 : []

python - Pandas :groupby 相邻的相同元素

python - Django 无法在模板中计算票数

Django Rest框架更新Put不允许

python - 1049, "Unknown database ' 数据库' "django mysql can' t 连接