Django:从django.urls导入反向; ImportError:没有名为urls的模块 - python

我正在使用民意调查应用程序完成DjangoProject教程。如本教程第4部分所述,我正在尝试导入“reverse”:from django.urls import reverse但出现错误:

从django.urls导入反向
ImportError:没有名为urls的模块

我已将ROOT_URLCONF更改为仅“urls”,但是,它也不起作用。

任何帮助表示赞赏,谢谢。

settings.py

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '3jyaq2i8aii-0m=fqm#7h&ri2+!7x3-x2t(yv1jutwa9kc)t!e'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'polls.apps.PollsConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

MIDDLEWARE_CLASSES = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'mysite.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'mysite.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/1.9/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/

STATIC_URL = '/static/'

urls.py

from django.conf.urls import url, include
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^polls/', include('polls.urls')),

]

民意调查/views.py

from django.http import HttpResponse, HttpResponseRedirect
from .models import Question, Choice
from django.shortcuts import get_object_or_404, render
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):
    question = get_object_or_404(Question, pk=question_id)
    return render(request, 'polls/results.html', {'question' : question})


def results(request, questioin_id):
    response = "you are looking at the results of question %s"
    return HttpResponse(response % question_id)

def vote(request, question_id):
    question = get_object_or_404(Question, pk=questioin_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 didnt select a choice",
                                                      })
    else:
        selected_choice.votes += 1
        selected_choice.save()
        return HttpResponseRedirect(reverse('polls:results', args=
                                            (question.id,)))

民意调查/urls.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'), 
]

参考方案

您使用的是Django 1.9,应该执行以下操作:

from django.core.urlresolvers import reverse

从版本1.10(包括Django 2.0)开始,您可以开始 from django.urls import reverse

django-getlist() - python

我刚刚发布了这个问题jQuery - passing arrays in post request,在发布请求中我不发送数组,但是jQuery代码没有问题。问题在于在django中接收到POST请求。我确实喜欢这个def portfolio_add(request): ukeys = request.POST.getlist('ukeys'…

django-simple-history,在admin中显示更改的字段 - python

当我从admin.ModelAdmin继承时,在管理页面的历史记录中,我可以看到哪些字段已更改。但是,现在我需要使用django-simple-history来跟踪所有模型更改。现在,对于管理员,我继承了simple_history.SimpleHistoryAdmin。我可以看到所有模型更改并还原它们,但看不到更改了哪些字段。是否可以在SimpleHist…

Django Python如何在给定两个时间字符串的情况下计算时差 - python

在Django Python中,我有2个HH:mm时间字符串,如何获取持续时间(差异)?例如:15:30 and 11:00 ---> difference is 04:30 19:28 and 12:25 ---> difference is 07:03 参考方案 我们可以首先使用以下命令将字符串解析为datetime对象:from datet…

django-compressor未与django-shop一起安装 - python

我无法使用django-shop安装django-compressor。出现这样的错误。Failed building wheel for rcssmin ================================= Failed building wheel for rjsmin -----------------------------------…

如何从Django模型生成文档? - python

目前,我们将Sphinx用于项目文档和Django模型字段描述。主要问题是:更改模型后,我们手动更新了Sphinx文档,有时会忘记/错过文档中的某些字段。有一些用于基于Django模型生成文档的工具吗? 参考方案 documentation说: Django的文件使用Sphinx文件系统, 转是基于docutils的。基本思想是格式化 纯文本文档已转换为HT…