Выпадает ошибка при запуске сервера Django. Вроде пишет, что ошибка в кодировке, но я не знаю как её исправить.
System check identified no issues (0 silenced).
June 06, 2019 - 17:33:13
Django version 2.2.2, using settings 'blogglav.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
Exception in thread django-main-thread:
Traceback (most recent call last):
File "c:python37-32Libthreading.py", line 917, in _bootstrap_inner
self.run()
File "c:python37-32Libthreading.py", line 865, in run
self._target(*self._args, **self._kwargs)
File "D:CODEpy-ruDjangoenvlibsite-packagesdjangoutilsautoreload.py", line 54, in wrapper
fn(*args, **kwargs)
File "D:CODEpy-ruDjangoenvlibsite-packagesdjangocoremanagementcommandsrunserver.py", line 139, in inner_run
ipv6=self.use_ipv6, threading=threading, server_cls=self.server_cls)
File "D:CODEpy-ruDjangoenvlibsite-packagesdjangocoreserversbasehttp.py", line 203, in run
httpd = httpd_cls(server_address, WSGIRequestHandler, ipv6=ipv6)
File "D:CODEpy-ruDjangoenvlibsite-packagesdjangocoreserversbasehttp.py", line 67, in __init__
super().__init__(*args, **kwargs)
File "c:python37-32Libsocketserver.py", line 452, in __init__
self.server_bind()
File "c:python37-32Libwsgirefsimple_server.py", line 50, in server_bind
HTTPServer.server_bind(self)
File "c:python37-32Libhttpserver.py", line 139, in server_bind
self.server_name = socket.getfqdn(host)
File "c:python37-32Libsocket.py", line 676, in getfqdn
hostname, aliases, ipaddrs = gethostbyaddr(name)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xcf in position 5: invalid continuation byte
I have installed python 2.7.10 in windows. I installed django in path c:python27/scripts/
with a command pip install django
and created project with command django-admin startproject mysite
from the same path.
Now to run server i cd to path c:python27/scripts/mysite
and ran a command manage.py runserver
/ manage.py runserver 0.0.0.0:8000
And this has no any effect.
where did i go wrong, and also i couldn’t run with python console. and i couldn’t redirect to my project from python CMD. all i did is from windows console.
Edit:
Screenshot of execution
xyres
20.3k3 gold badges55 silver badges84 bronze badges
asked Jan 9, 2016 at 9:40
12
First step was to set the environment variable.
windows key
+pause
orControl PanelSystem and SecuritySystem
- Advance system settings (this will open system property)
- navigate to
Advanced tab
>Environment variable
- Edit path — append
;c:python27
in variable value field - Restart CMD
then /python manage.py runserver
should work
answered Jan 11, 2016 at 2:43
Suman KCSuman KC
3,4584 gold badges30 silver badges42 bronze badges
0
Trying setting up a virtualenv for your project.
This same issue happened to me when trying to launch the test server
python .manage.py runserver
from PowerShell on Windows 10. According to the Django site, there might be an issue with the type of arguments being passed from PowerShell.
My workaround was to use a virtualenv. Once that was setup with django installed via pip, the runserver command worked.
answered Aug 22, 2017 at 1:35
The best solution is to install Python from Microsoft Store. In this case, you won’t have to worry about the Environmental Variables and Path. Windows will detect all that automatically.
answered Jun 8, 2020 at 13:25
Try this fix guys:
1. Right click on the windows icon/start on the bottom left and run Windows Powershell as admin.
2. Than type cd ~/
and later change the path again to the project folder.
3. type python manage.py runserver
and press enter.
answered Aug 10, 2019 at 9:24
1
had the same problem. fixed it by checking python and django version compatibility. If you’re still battling with this update one or the other or ensure they’re both compatible with each other in the virtual’env’ you’re setting up.
good luck.
answered Jul 27, 2019 at 8:27
I think you forgot to add python to environment variables. So, During the installation, click the checkbox named «Add Python 3.9 to PATH» to add in environment variables. or you can simply add the path later.
answered Oct 6, 2020 at 6:41
Yumick GhartiYumick Gharti
1,1281 gold badge7 silver badges7 bronze badges
When you open the command prompt on windows, the default directory might be C:WINDOWSSystem32>
Here, you have to change the directory by just adding cd to the default directory. Then copy the directory of where your project is and paste with one space. So it will be:
C:yourfolderyourproject>
Next, use the comman which is, python manage.py runserver
That’s all 😅
answered Oct 17, 2022 at 0:13
After setting C:Python
in the environment variables, issuing the following command helped:
py manage.py runserver
answered Jul 4, 2018 at 7:19
0
Providing some more code or examples of your directory structure might help.
First, the command is generally manage.py runserver 8000
, so try that, and that make might a difference.
Second, in Django 1.4, the location of the settings.py
file was moved. In previous versions of Django, the directory structure looked like this:
myproject/
settings.py
views.py
urls.py
myapp/
models.py
...
...
However, in Django 1.4, the main project settings and files were moved to a different directory:
myproject/
myproject/
settings.py
views.py
urls.py
myapp/
models.py
urls.py
...
...
So if you’re using Django 1.4 but going off of previous examples, your settings.py
might be in the wrong place. Additionally, I’ve found that when running django-admin.py startproject
, it sometimes incorrectly creates two settings.py
files, once in the old location and one in the new, which could be additionally confusing you. The only one that manage.py
would pay attention to is the one in the project’s directory.
If it turns out that your settings.py
is in the wrong place but you don’t want to move it, as your error suggests, you could set an environmental variable called DJANGO_SETTINGS_MODULE
as the path to the Django settings.py
you’d like to use for your project. I definitely don’t recommend doing this.
DJANGO – это удобный и мощный фреймворк для создания веб-приложений на Python. Однако, при запуске сервера на Django могут возникнуть некоторые проблемы. В этой статье мы рассмотрим частые ошибки и как их решить.
Ошибка «ModuleNotFoundError: No module named ‘django'»
Такая ошибка возникает, если Django не установлен на компьютере. Чтобы решить эту проблему, необходимо установить Django с помощью pip:
pip install Django
Ошибка «Error: Target WSGI script not found or unable to stat»
Такая ошибка указывает на проблему с файлом WSGI. Для ее решения необходимо проверить, указан ли правильный путь к файлу WSGI в конфигурационном файле. Также следует убедиться, что файл WSGI находится в нужной директории.
Ошибка «Port 8000 is already in use»
Если вы видите такое сообщение, значит порт 8000 уже используется другим приложением. Чтобы решить эту проблему, можно изменить порт для запуска сервера. Для этого нужно указать другой номер порта, например 8080:
python manage.py runserver 8080
Ошибка «no module named ‘myapp'»
Если вы создали приложение с именем «myapp», а Django не может найти его, то нужно проверить, правильно ли указано имя приложения в конфигурационном файле настроек.
Ошибка «TypeError: ‘xxx’ object is not callable»
Такая ошибка возникает, когда используется несуществующий метод или пропущен аргумент. Необходимо проверить код и убедиться, что все методы используются правильно и все аргументы передаются в нужном порядке.
Ошибка «SyntaxError: invalid syntax»
Такая ошибка возникает, если код содержит синтаксические ошибки. Чтобы решить эту проблему, нужно внимательно проверить код и исправить все ошибки.
Заключение
В данной статье мы рассмотрели частые ошибки при запуске сервера на Django и как их решить. Важно помнить, что большинство проблем можно решить, внимательно следуя инструкциям и проверяя код.
Начал изучать django, создал проект, попытался запустить сервер с помощью команды python manage.py runserver, но выдает ошибку. Подскажите, пожалуйста, в чем проблема. Ошибка:
C:Usersданя>cd C:Django
C:Django>cd myfirst
C:Djangomyfirst>python manage.py runserver
Watching for file changes with StatReloader
Performing system checks...
Exception in thread django-main-thread:
Traceback (most recent call last):
File "C:anacondalibthreading.py", line 917, in _bootstrap_inner
self.run()
File "C:anacondalibthreading.py", line 865, in run
self._target(*self._args, **self._kwargs)
File "C:anacondalibsite-packagesdjangoutilsautoreload.py", line 53, in w
rapper
fn(*args, **kwargs)
File "C:anacondalibsite-packagesdjangocoremanagementcommandsrunserver.
py", line 117, in inner_run
self.check(display_num_errors=True)
File "C:anacondalibsite-packagesdjangocoremanagementbase.py", line 395,
in check
include_deployment_checks=include_deployment_checks,
File "C:anacondalibsite-packagesdjangocoremanagementbase.py", line 382,
in _run_checks
return checks.run_checks(**kwargs)
File "C:anacondalibsite-packagesdjangocorechecksregistry.py", line 72,
in run_checks
new_errors = check(app_configs=app_configs)
File "C:anacondalibsite-packagesdjangocorechecksurls.py", line 40, in c
heck_url_namespaces_unique
all_namespaces = _load_all_namespaces(resolver)
File "C:anacondalibsite-packagesdjangocorechecksurls.py", line 57, in _
load_all_namespaces
url_patterns = getattr(resolver, 'url_patterns', [])
File "C:anacondalibsite-packagesdjangoutilsfunctional.py", line 48, in _
_get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:anacondalibsite-packagesdjangourlsresolvers.py", line 588, in ur
l_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "C:anacondalibsite-packagesdjangoutilsfunctional.py", line 48, in _
_get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:anacondalibsite-packagesdjangourlsresolvers.py", line 581, in ur
lconf_module
return import_module(self.urlconf_name)
File "C:anacondalibimportlib__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:Djangomyfirstmyfirsturls.py", line 20, in <module>
path('articles/', include('articles.urls')),
File "C:anacondalibsite-packagesdjangourlsconf.py", line 34, in include
urlconf_module = import_module(urlconf_module)
File "C:anacondalibimportlib__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'articles'
Traceback (most recent call last):
File "manage.py", line 21, in <module>
main()
File "manage.py", line 17, in main
execute_from_command_line(sys.argv)
File "C:anacondalibsite-packagesdjangocoremanagement__init__.py", line
401, in execute_from_command_line
utility.execute()
File "C:anacondalibsite-packagesdjangocoremanagement__init__.py", line
395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:anacondalibsite-packagesdjangocoremanagementbase.py", line 328,
in run_from_argv
self.execute(*args, **cmd_options)
File "C:anacondalibsite-packagesdjangocoremanagementcommandsrunserver.
py", line 60, in execute
super().execute(*args, **options)
File "C:anacondalibsite-packagesdjangocoremanagementbase.py", line 369,
in execute
output = self.handle(*args, **options)
File "C:anacondalibsite-packagesdjangocoremanagementcommandsrunserver.
py", line 95, in handle
self.run(**options)
File "C:anacondalibsite-packagesdjangocoremanagementcommandsrunserver.
py", line 102, in run
autoreload.run_with_reloader(self.inner_run, **options)
File "C:anacondalibsite-packagesdjangoutilsautoreload.py", line 599, in
run_with_reloader
start_django(reloader, main_func, *args, **kwargs)
File "C:anacondalibsite-packagesdjangoutilsautoreload.py", line 584, in
start_django
reloader.run(django_main_thread)
File "C:anacondalibsite-packagesdjangoutilsautoreload.py", line 299, in
run
self.run_loop()
File "C:anacondalibsite-packagesdjangoutilsautoreload.py", line 305, in
run_loop
next(ticker)
File "C:anacondalibsite-packagesdjangoutilsautoreload.py", line 345, in
tick
for filepath, mtime in self.snapshot_files():
File "C:anacondalibsite-packagesdjangoutilsautoreload.py", line 361, in
snapshot_files
for file in self.watched_files():
File "C:anacondalibsite-packagesdjangoutilsautoreload.py", line 260, in
watched_files
yield from iter_all_python_module_files()
File "C:anacondalibsite-packagesdjangoutilsautoreload.py", line 105, in
iter_all_python_module_files
return iter_modules_and_files(modules, frozenset(_error_files))
File "C:anacondalibsite-packagesdjangoutilsautoreload.py", line 141, in
iter_modules_and_files
resolved_path = path.resolve(strict=True).absolute()
File "C:anacondalibpathlib.py", line 1144, in resolve
s = self._flavour.resolve(self, strict=strict)
File "C:anacondalibpathlib.py", line 196, in resolve
return self._ext_to_normal(_getfinalpathname(s))
OSError: [WinError 123] Синтаксическая ошибка в имени файла, имени папки или метке тома: '<frozen importlib._bootstrap>'
Файлы проекта:
manage
import os
import sys
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myfirst.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()
asgi
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myfirst.settings')
application = get_asgi_application()
settings
import os,sys
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PROJECT_ROOT = os.path.dirname(__file__)
sys.path.insert(0, os.path.join(PROJECT_ROOT, 'apps'))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'gc*ar4(-%j00mj(9*imu)cq^3%klcpb4h-i71zn3r&l9(j$x2p'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
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 = 'myfirst.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 = 'myfirst.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/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/3.0/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/3.0/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/3.0/howto/static-files/
STATIC_URL = '/static/'
urls
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('articles/', include('articles.urls')),
path('admin/', admin.site.urls)
]
wsgi
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myfirst.settings')
application = get_wsgi_application()
admin
from django.contrib import admin
apps
from django.apps import AppConfig
class ArticlesConfig(AppConfig):
name = 'articles'
models
from django.db import models
tests
from django.test import TestCase
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name = 'index')
]
views
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, world!")