I am working through the DjangoProject tutorial with the polls app. As the tutorial states in part 4 I am trying to import 'reverse':
from django.urls import reverse
but getting the error:from django.urls import reverse ImportError: No module named urls
I have changed the
ROOT_URLCONF
to just 'urls
', however, it did not work either.Any help is appreciated, Thank you.
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')), ]
polls/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,)))
polls/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'), ]
score:84
Accepted answer
You're on Django 1.9, you should do:
from django.core.urlresolvers import reverse
Starting with version 1.10 (including Django 2.0) is where you get to do from django.urls import reverse
Credit To: stackoverflow.com
Related Query
- Django: from django.urls import reverse; ImportError: No module named urls
- Django - ImportError at /blog. No module named urls
- Django Import Error at / No module named urls
- django import error - No module named core.management
- Django import error - no module named django.conf.urls.defaults
- Import Error: No module named django
- Django Import Error: No module named apps
- Django storages: Import Error - no module named storages
- Django + mod_wsgi + apache: ImportError at / No module named djproj.urls
- django - import error: no module named views
- ImportError at / No module named quickstart in django rest framework
- Django - Import Error: No module named *.urls
- Django import error: No module named models
- Help with "Error: No module named polls" from the Django Project Tutorial 1
- Django + uwsgi + nginx . Import error: No module named py
- ImportError No module named localflavor.us.forms in Django 1.7
- Import Error: No module named django - for specific project
- django url reverse not working for named urls (re-edited) found the cause but now stuck!
- django celery: Import error - no module named task
- "ImportError: No module named cv2" when running Django project from PyCharm IDE
- Not able to import from `gensim.summarization` module in Django
- django : ImportError No module named myapp.views.hometest
- ImportError at / No module named urls
- heroku django import error no module named _collections
- Django ImportError: Could not import settings 'mysite.settings.local' (Is it on sys.path?): No module named settings.local
- from django.utils.importlib import import_module ImportError: No module named importlib
- from Google import Create_Service ModuleNotFoundError: No module named 'Google'
- google app engine (python): ImportError no module named django
- Python-Django : ImportError at / : No module named urls
- Import Error: No module named http django
More Query from same tag
- Using django to run python scripts with password arguments
- Django - Inline (has no ForeignKey to)
- S3BotoStorage and Unit Testing
- Meaning of "NoReverseMatch" in Django
- Django: Cannot resolve keyword '' into field. Choices are:
- django get latest for each group, group by foreign key
- Django - how to tell if a template fragment is already cached?
- Sign up View in Django with Bootsrap
- PIP Install Failing
- django-shop vs Satchless?
- Execute script after `python manage.py shell` is up
- CSS, Bootstrap and Javascript is not working with Django
- Cannot save record from Django Model
- csrf token Follow up
- Asynchronous signals with asyncio