Django Installation Error

Sometimes, I am getting this error :
AttributeError: module ‘myproject.urls’ has no attribute ‘handler400’.

After I uninstall and reinstall Django. It is working properly. But I have to do it many times. Is there a permanent solution to this?

I have been using and switching between Python 3.12 and 3.9. Even when I do not switch, it still shows this, and after uninstalling and reinstalling, it works fine.

This would be the result of some code that you are running. This doesn’t “just happen” by itself.

To get started investigating this. we would need to see all of your url files, along with your ROOT_URLCONF, INSTALLED_APPS and MIDDLEWARE settings.

Also, please identify what version of Django you are using. (The output of a pip list for your virtual environment would be useful, too.)

django version is 5.2. I use virtual environment in 3.9 not in 3.12.

this is the settings.py file:

"""
Django settings for myproject project.

Generated by 'django-admin startproject' using Django 5.1.1.

For more information on this file, see
https://docs.djangoproject.com/en/5.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/5.1/ref/settings/
"""


from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-o4b_%20tuo^(_ou5pwy2^8f@=*(-i&4xbe9gh-#4a2_=2b(9%&'

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

ALLOWED_HOSTS = ['127.0.0.1', 'localhost']


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myapp',
]

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

ROOT_URLCONF = 'myproject.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 = 'myproject.wsgi.application'


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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}


# Password validation
# https://docs.djangoproject.com/en/5.1/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/5.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True


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

STATIC_URL = '/static/'
STATICFILES_DIRS = [
    BASE_DIR / "myapp" / "static",  # Path to your static files directory
]

# Default primary key field type
# https://docs.djangoproject.com/en/5.1/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

this is urls.py (my project):

# myproject/urls.py

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('myapp.urls')),
    
]

this is urls.py(myapp)

from django.urls import path
from .views import *

urlpatterns = [
    
    path('', student_selection_view, name='student_selection'),
]

1)

Maybe format your settings.py properly, it’s very hard to read.

Like,

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
path(‘admin/’, admin.site.urls),
path(‘’, include(‘myapp.urls’)),

]

this is urls.py(myapp)

from django.urls import path
from .views import *

urlpatterns = [

path('', student_selection_view, name='student_selection'),
] 

.

Use “```” at both ends of code segments.(three ` characters.

2)

Don’t need to link to django documentation. (my opinion, because people here know little bit about django)

3)

Post the actual error message that appear on the console. (format it also, when posting).

this is the error that is being displayed. I just copied the code as it is but the settings.py is coming with links. I don’t know why?

File "C:\Users\CITHP\AppData\Local\Programs\Python\Python312\Lib\threading.py", line 1052, in _bootstrap_inner
    self.run()
  File "C:\Users\CITHP\AppData\Local\Programs\Python\Python312\Lib\threading.py", line 989, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Users\CITHP\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\utils\autoreload.py", line 64, in wrapper
    fn(*args, **kwargs)
  File "C:\Users\CITHP\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\management\commands\runserver.py", line 134, in inner_run
    self.check(**check_kwargs)
  File "C:\Users\CITHP\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\management\base.py", line 492, in check
    all_issues = checks.run_checks(
                 ^^^^^^^^^^^^^^^^^^
  File "C:\Users\CITHP\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\checks\registry.py", line 89, in run_checks
    new_errors = check(app_configs=app_configs, databases=databases)
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\CITHP\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\checks\urls.py", line 138, in check_custom_error_handlers
    path = getattr(resolver.urlconf_module, "handler%s" % status_code)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: module 'myproject.urls' has no attribute 'handler400'

As @ChathuraGH said, you need to format your code correctly by putting three backticks - ``` - on separate lines before the start and end of your code.

A wild guess is that your current working directory is wrong, and your reinstallation doesn’t actually do anything. You just don’t realize you change directory when doing this and after doing it a bunch of times you change directory too and suddenly it works. Then you think it’s about reinstalling Django, but it’s not.

Side Note: When posting code, templates, error messages, or other preformatted text here, enclose the code between lines of three
backtick - ` characters. This means you’ll have a line of ```, then your code,
then another line of ```. This forces the forum software to keep your code
properly formatted. (I have taken the liberty of correcting your original posts.
Please remember to do this in the future.)

This error can be caused by Django being unable to import your urls.py file. Your root urls.py imports your myapp.urls file, which then imports your myapp.views file. Some errors in your views file can cause it to fail.

Please show the contents of your myapp.views file.

Also note:

Django 5.2 does not support being run under 3.9, it is possible that trying to do so will cause any number of odd errors.

Please post the pip list for your 3.12 environment.

altair 5.5.0
annotated-types 0.7.0
asgiref 3.8.1
attrs 25.1.0
blinker 1.8.2
blis 1.2.0
Brotli 1.1.0
cachetools 5.5.2
catalogue 2.0.10
certifi 2024.8.30
cffi 1.17.1
chardet 5.2.0
charset-normalizer 3.3.2
click 8.1.7
cloudpathlib 0.20.0
colorama 0.4.6
confection 0.1.5
cryptography 44.0.1
cssselect2 0.7.0
cymem 2.0.11
decorator 5.2.0
distro 1.9.0
Django 5.2
docx2txt 0.8
en_core_web_sm 3.8.0
et_xmlfile 2.0.0
Flask 3.0.3
Flask-SQLAlchemy 3.1.1
Flask-WTF 1.2.2
fonttools 4.55.3
future 1.0.0
geocoder 1.38.1
geographiclib 2.0
geopy 2.4.1
gitdb 4.0.12
GitPython 3.1.44
greenlet 3.1.1
idna 3.10
itsdangerous 2.2.0
Jinja2 3.1.4
joblib 1.4.2
jsonschema 4.23.0
jsonschema-specifications 2024.10.1
langcodes 3.5.0
language_data 1.3.0
lxml 5.3.0
marisa-trie 1.2.1
markdown-it-py 3.0.0
MarkupSafe 3.0.2
mdurl 0.1.2
murmurhash 1.0.12
mysql 0.0.3
mysqlclient 2.2.7
narwhals 1.27.1
nltk 3.9.1
numpy 2.1.1
openpyxl 3.1.5
packaging 24.2
pandas 2.2.2
pdfkit 1.0.0
pdfminer.six 20240706
pdfminer3 2018.12.3.0
pillow 11.0.0
pip 23.2.1
plotly 6.0.0
preshed 3.0.9
protobuf 5.29.3
pyarrow 19.0.1
pycparser 2.22
pycryptodome 3.21.0
pydantic 2.10.6
pydantic_core 2.27.2
pydeck 0.9.1
pydyf 0.11.0
Pygments 2.19.1
PyMySQL 1.1.1
pyphen 0.17.0
pyresparser 1.0.6
pyrsistent 0.20.0
python-dateutil 2.9.0.post0
pytz 2024.2
ratelim 0.1.6
referencing 0.36.2
regex 2024.11.6
requests 2.32.3
rich 13.9.4
rpds-py 0.23.1
setuptools 75.8.0
shellingham 1.5.4
six 1.16.0
smart-open 7.1.0
smmap 5.0.2
sortedcontainers 2.4.0
spacy 3.8.4
spacy-legacy 3.0.12
spacy-loggers 1.0.5
SQLAlchemy 2.0.36
sqlparse 0.5.3
srsly 2.5.1
streamlit 1.42.2
streamlit-tags 1.2.8
tabula-py 2.9.3
tenacity 9.0.0
thinc 8.3.4
tinycss2 1.4.0
tinyhtml5 2.0.0
toml 0.10.2
tornado 6.4.2
tqdm 4.67.1
typer 0.15.1
typing_extensions 4.12.2
tzdata 2025.2
urllib3 2.2.3
wasabi 1.1.3
watchdog 6.0.0
weasel 0.4.1
weasyprint 63.1
webencodings 0.5.1
Werkzeug 3.1.2
wrapt 1.17.2
WTForms 3.2.1
XlsxWriter 3.2.0
zopfli 0.2.3.post1
WARNING: There was an error checking the latest version of pip.

from django.shortcuts import render, redirect
from django.db.models import Count
from .forms import StudentSelectionForm
from .models import StudentSelection, MeetingTime, Instructor,Course
from django.contrib.auth.decorators import login_required
import json

@login_required
def student_selection_view(request):
    if request.method == "POST":
        form = StudentSelectionForm(request.POST)
        if form.is_valid():
            selection = form.save(commit=False)
            selection.student = request.user
            selection.save()
            return redirect('student_selection')
    else:
        form = StudentSelectionForm()

    # Get all selections with related data
    selections = StudentSelection.objects.select_related(
        'instructor', 'course', 'meeting_time'
    ).all()

    # Count selections (unchanged)
    selection_counts = selections.values(
        'instructor__name',
        'course__course_name',
        'meeting_time__day',
        'meeting_time__time'
    ).annotate(count=Count('id'))

    # Define days and times
    DAYS = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
    TIMES = ['9:30-10:45', '10:55-12:10', '12:20-1:00', 
             '1:00-1:45', '1:45-3:00', '3:10-4:25', '4:35-5:50']

    # Build timetable matrix with actual data
    timetable_matrix = {day: {time: [] for time in TIMES} for day in DAYS}
    
    for selection in selections:
        day = selection.meeting_time.day
        time = selection.meeting_time.time
        timetable_matrix[day][time].append({
            'course': selection.course.course_name,
            'instructor': selection.instructor.name,
            'count': StudentSelection.objects.filter(
                course=selection.course,
                meeting_time__day=day,
                meeting_time__time=time
            ).count()
        })
    instructors = Instructor.objects.all()
    # Build instructor-course mapping
    instructor_course_map = {}
    for instr in instructors:
        qs = Course.objects.filter(pk=instr.id).values('pk','course_name')
        instructor_course_map[instr.id] = list(qs)

    # Morning/evening logic (unchanged)
    morning_times = MeetingTime.objects.filter(time__in=['9:30-10:45', '10:55-12:10','12:20-1:00'])
    evening_times = MeetingTime.objects.filter(time__in=['1:00-1:45','1:45-3:00','3:10-4:25', '4:35-5:50'])
    instructors = Instructor.objects.all()
    instructor_mapping = {instr.id: instr.popularity for instr in instructors}

    context = {
        'form': form,
        'selection_counts': selection_counts,
        'morning_times': morning_times,
        'evening_times': evening_times,
        'instructor_mapping_json': json.dumps(instructor_mapping),
        'instructor_course_map_json': json.dumps(instructor_course_map),
        'timetable_matrix': timetable_matrix,
        'days': DAYS,
        'times': TIMES,
    }
    return render(request, 'student_selection.html', context)

How are you running your project? (Are you using runserver?) What is the command line you are using to run your project?

And to confirm the behavior you are reporting:

  • You can run it and it works.
  • At some point in time it stops working - even if you aren’t making any changes to the code.
  • Reinstalling Django makes it start working again

???

If this is not the sequence of events, please identify what is happening.

I am using runserver. I am using cmd to run the project. Once a day, that error comes. My guess is that different versions of Python are causing this error. This happened in another system too.

Please be more specific and provide more details.

What command are you running?

What are you doing, or what is happening when the error comes?

What is making you think that different Python versions are causing this? (The traceback is showing everything as being in Python312.)

1)

I wonder if date and time queries in your view cause some error that is dependant on the server clock time.

2)

But look here.

You just posted error message from python 312.

Please ask the question clearly and specifically. It’s better to stick to a specific python version when asking a question. Otherwise how someone can help?.

3)

Also consider this.

Django 5.2 does not support Python 3.9. Django 5.2 supports Python 3.10, 3.11, 3.12, and 3.13. Django 4.2.x was the last series to support Python 3.8 and 3.9.

Thanks.

Whenever I run python manage.py runserver in Python 3.12, it shows the error that I posted in one of the replies in this thread. This error is displayed irrespective of which Django project I am running in Python 3.12. This error has been coming since I installed 3.9 , and that is what makes me think that this is what is causing the error.

this are some of the requirements. txt I installed in Python 3.9 in virtual environment.:

altair==4.2.0
attrs==22.1.0
blinker==1.5
blis==0.7.8
cachetools==5.2.0
catalogue==1.0.0
certifi==2022.6.15
cffi==1.15.1
chardet==5.0.0
charset-normalizer==2.1.1
click==8.1.3
colorama==0.4.5
commonmark==0.9.1
cryptography==37.0.4
cycler==0.11.0
cymem==2.0.6
decorator==5.1.1
docx2txt==0.8
entrypoints==0.4
fonttools==4.37.2
future==0.18.2
geocoder==1.38.1
geographiclib==1.52
geopy==2.2.0
gitdb==4.0.9
GitPython==3.1.27
idna==3.3
importlib-metadata==4.12.0
Jinja2==3.1.2
joblib==1.1.0
jsonschema==4.15.0
kiwisolver==1.4.4
langcodes==3.3.0
MarkupSafe==2.1.1
matplotlib==3.5.3
murmurhash==1.0.8
nltk==3.7
numpy==1.23.2
packaging==21.3
pafy==0.5.5
pandas==1.4.4
pathy==0.6.2
pdfminer.six==20220524
pdfminer3==2018.12.3.0
Pillow==9.2.0
plac==1.1.3
plotly==5.10.0
preshed==3.0.7
protobuf==3.20.1
pyarrow==9.0.0
pycparser==2.21
pycryptodome==3.15.0
pydantic==1.9.2
pydeck==0.8.0b1
Pygments==2.13.0
Pympler==1.0.1
PyMySQL==1.0.2
pyparsing==3.0.9
pyresparser==1.0.6
pyrsistent==0.18.1
python-dateutil==2.8.2
pytz==2022.2.1
pytz-deprecation-shim==0.1.0.post0
ratelim==0.1.6
regex==2022.8.17
requests==2.28.1
rich==12.5.1
semver==2.13.0
six==1.16.0
smart-open==5.2.1
smmap==5.0.0
sortedcontainers==2.4.0
spacy==2.3.5
spacy-legacy==3.0.10
spacy-loggers==1.0.3
srsly==1.0.5
streamlit==1.12.2
streamlit-tags==1.2.8
tenacity==8.0.1
thinc==7.4.5
toml==0.10.2
toolz==0.12.0
tornado==6.2
tqdm==4.64.1
typer==0.4.2
typing_extensions==4.3.0
tzdata==2022.2
tzlocal==4.2
urllib3==1.26.12
validators==0.20.0
wasabi==0.10.1
watchdog==2.1.9
zipp==3.8.1

It looks like you are running DEBUG = False without handler404 url.

Are you sure you are running with

?

If not below methods should be considered.

Look at these info. They look old, but informative.

handler400

you should make DEBUG=False. It’s more of a production feature and won’t work in development environment(unless you have DEBUG=False in dev machine of course).



Question

urlpatterns = [
    ...
]

handler404 = 'myapp.views.handle_page_not_found'
def handle_page_not_found(request):
    return redirect('homepage')


More info.

from django.conf.urls import handler404, handler500, handler403, handler400
from your_app_name import views

handler404 = views.error_404
handler500 = views.error_500
def error_404(request, exception):
   context = {}
   return render(request,'admin/404.html', context)

def error_500(request):
   context = {}
   return render(request,'admin/500.html', context)
Note, 

Yes, I am running with debug = True.

Ok. I think making handler404 function and url will fix everything. Regardless of every other thing.

Try testing it and give feedback here.

Did you do it? Got fixed your error?