Форум сайта python.su
Всем привет. начал изучать джанго steb by step, все отлично, но столкнулся с проблемой. Когда дошел черед разбираться с админкой, вылез косяк - не отдается статика для админки. Загружается без css, js etc. в setting.py все по дефолту, кроме:
1. Добавил свои настройки баз данных
2. Разкомментировал\добавил нужные строки для включения админки, все как в туториале, в том числе и в urls.py
ОС Windows 7 x64, все нужные пути добавлены в PATH. все по туториалу :)
Проект находиться в C:\djcode
Сервер использую который идет в комплекте с django :)
Сменить ОС не выход. холивары не нужны.
Прошу помощи :) гугл не помог =\
Офлайн
У меня статика начала глючить после того, как залил на сервер. Локально было норм. Вообщем потом проблему решил, но в дальнейшем предпочёл следующее:
Скопировал статику админки в отдельный каталог (MEDIA_ADMIN)
#setting.py
PROJECT_ROOT = os.path.join( os.path.dirname(__file__), '../../')
WWW_ROOT = PROJECT_ROOT + 'www/'
MEDIA_ADMIN = WWW_ROOT+'admin/media/' #там статика лежит
ADMIN_MEDIA_PREFIX = '/admin/media/'
#urls.py
(r'^admin/media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': MEDIA_ADMIN, 'show_indexes': True}),
Отредактировано (Июль 21, 2011 16:46:21)
Офлайн
django.views.static.serve нафиг не нужен если у тебя django 1.3 и /static/admin указан в статике для админки, при включённом дебаге всё должно работать
аля
STATIC_ROOT = 'static/'
STATIC_URL = '/static/'
ADMIN_MEDIA_PREFIX = '/static/admin/'
Офлайн
я уже все перерыл. просто не отдает статику на dev сервере и все тут =\ я огорчен. кто-то еще что-то подскажет ? :)
Офлайн
перечитал еще раз всю документацию. все решения проблем и т.д. ну ничего не помагает, как уже не пробовал. очень понравился джанго, после пхп как глоток свежего воздуха. и такой облом в самом начале. какие еще идеи ? Django 1.3. Создаю проект и с консоли и с PyCharm все одно =\
Отредактировано (Июль 21, 2011 21:26:46)
Офлайн
конфиг выложи
или выложи архив проекта
Офлайн
settings.py
# Django settings for djcode project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'test', # Or path to database file if using sqlite3.
'USER': 'root', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/Chicago'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale
USE_L10N = True
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = ''
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = ''
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'
# URL prefix for admin static files -- CSS, JavaScript and images.
# Make sure to use a trailing slash.
# Examples: "http://foo.com/static/admin/", "/static/admin/".
ADMIN_MEDIA_PREFIX = '/static/admin/'
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
# Make this unique, and don't share it with anybody.
SECRET_KEY = 'rrv$8$mms338zjbjc)8sv(d%(n6@)le)v68y@!r_la!lsox2#n'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
ROOT_URLCONF = 'djcode.urls'
TEMPLATE_DIRS = ('C:/djcode/templates',)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# Uncomment the next line to enable the admin:
'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
'djcode.djapp',
)
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'mail_admins': {
'level': 'ERROR',
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
from django.conf.urls.defaults import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'djcode.views.home', name='home'),
# url(r'^djcode/', include('djcode.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
)
Офлайн
syncdb надеюсь делал? конфиг у тебя дефолтный, админка в линуксе работает нормально)
что тебе http://localhost:8000/static/admin/css/login.css говорит?
попробуй ещё
./manage.py findstatic admin/css/login.css
Found 'admin/css/login.css' here:
/usr/share/pyshared/django/contrib/admin/media/css/login.css
Офлайн
конечно syncdb делал :)
http://localhost:8000/static/admin/css/login.css говорит:
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\django\core\servers\basehttp.py", line 283, in run
self.result = application(self.environ, self.start_response)
File "C:\Python27\lib\site-packages\django\contrib\staticfiles\handlers.py", line 69, in __call__
return super(StaticFilesHandler, self).__call__(environ, start_response)
File "C:\Python27\lib\site-packages\django\core\handlers\wsgi.py", line 273, in __call__
response = self.get_response(request)
File "C:\Python27\lib\site-packages\django\contrib\staticfiles\handlers.py", line 59, in get_response
return self.serve(request)
File "C:\Python27\lib\site-packages\django\contrib\staticfiles\handlers.py", line 52, in serve
return serve(request, self.file_path(request.path), insecure=True)
File "C:\Python27\lib\site-packages\django\contrib\staticfiles\views.py", line 39, in serve
return static.serve(request, path, document_root=document_root, **kwargs)
File "C:\Python27\lib\site-packages\django\views\static.py", line 54, in serve
mimetype, encoding = mimetypes.guess_type(fullpath)
File "C:\Python27\lib\mimetypes.py", line 294, in guess_type
init()
File "C:\Python27\lib\mimetypes.py", line 355, in init
db.read_windows_registry()
File "C:\Python27\lib\mimetypes.py", line 259, in read_windows_registry
for ctype in enum_types(mimedb):
File "C:\Python27\lib\mimetypes.py", line 249, in enum_types
ctype = ctype.encode(default_encoding) # omit in 3.x!
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe0 in position 0: ordinal not in range(128)
Офлайн
лезь в реестр и удаляй мусор в HKEY_CLASSES_ROOT\MIME\Database\Content Type (только я не виноват если что-то отвалится В))
скорей всего там есть что-то не ascii
ps: http://bugs.python.org/issue9291
виндовс кал же, будь мужиком - поставь Linux ёпт !)
Офлайн