Форум сайта python.su
Привет всем! Никак не могу подключить статику в Django. Делаю простой сайт на готовом шаблоне, пока что хочу подключить только css и картинки. Читал документацию, и не один раз, но так и не понял, в чем дело( Использую Django 1.3, Python 2.7 и Ubuntu 12.04
views.py:
from django.template.loader import get_template from django.template import Context from django.http import HttpResponse def render_tpl(request): t = get_template('html/index.html') html = t.render(Context()) return HttpResponse(html)
from django.conf.urls.defaults import patterns, include, url from itchallenges.views import render_tpl from django.contrib.staticfiles.urls import staticfiles_urlpatterns # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover() urlpatterns = patterns('', ('^$', render_tpl), ) urlpatterns += staticfiles_urlpatterns()
MEDIA_ROOT = '' MEDIA_URL = '' STATIC_ROOT = "/home/oleg-admin/django/itchallenges/static/" STATIC_URL = "/static/" ADMIN_MEDIA_PREFIX = "/static/admin/" STATICFILES_DIRS = ( "/home/oleg-admin/django/itchallenges/static/", ) STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # 'django.contrib.staticfiles.finders.DefaultStorageFinder', ) TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', # 'django.template.loaders.eggs.Loader', ) TEMPLATE_DIRS = ( os.path.join(os.path.dirname(__file__), 'tpl/beadysite').replace('\\','/'), ) 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', )
Офлайн
The included context processor is the easy way. Simply make sure ‘django.core.context_processors.static’ is in your TEMPLATE_CONTEXT_PROCESSORS. It's there by default, and if you're editing that setting by hand it should look something like:
TEMPLATE_CONTEXT_PROCESSORS = (
‘django.core.context_processors.debug’,
‘django.core.context_processors.i18n’,
‘django.core.context_processors.media’,
'django.core.context_processors.static',
‘django.contrib.auth.context_processors.auth’,
‘django.contrib.messages.context_processors.messages’,
)
Once that's done, you can refer to STATIC_URL in your templates:
<img src=“{{ STATIC_URL }}images/hi.jpg” alt=“Hi!” />
If {{ STATIC_URL }} isn't working in your template, you're probably not using RequestContext when rendering the template.
As a brief refresher, context processors add variables into the contexts of every template. However, context processors require that you use RequestContext when rendering templates. This happens automatically if you're using a generic view, but in views written by hand you'll need to explicitly use RequestContext
Офлайн
FishHook
How exactly I should use RequestContext in my case?
Офлайн
Как то так
from django.template.context import RequestContext from django.shortcuts import render_to_response def view(request): .... .... return render_to_response( "template.html", {"context":context}, RequestContext(request))
Офлайн
{“context”:context} - эта строка обязательна? Мне пока что в шаблон нечего подставлять, кроме путей до css и картинок
Офлайн
Если в среде разработки, то надо просто создать в папке приложения подпапку static и скопировать статический контент туда. соответственно не забыть в settings.py:
STATIC_URL = '/static/'
Bandicoot
Привет всем! Никак не могу подключить статику в Django. Делаю простой сайт на готовом шаблоне, пока что хочу подключить только css и картинки. Читал документацию, и не один раз, но так и не понял, в чем дело( Использую Django 1.3, Python 2.7 и Ubuntu 12.04
views.py:from django.template.loader import get_template from django.template import Context from django.http import HttpResponse def render_tpl(request): t = get_template('html/index.html') html = t.render(Context()) return HttpResponse(html)
urls.py:from django.conf.urls.defaults import patterns, include, url from itchallenges.views import render_tpl from django.contrib.staticfiles.urls import staticfiles_urlpatterns # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover() urlpatterns = patterns('', ('^$', render_tpl), ) urlpatterns += staticfiles_urlpatterns()
settings.py (выборочно):MEDIA_ROOT = '' MEDIA_URL = '' STATIC_ROOT = "/home/oleg-admin/django/itchallenges/static/" STATIC_URL = "/static/" ADMIN_MEDIA_PREFIX = "/static/admin/" STATICFILES_DIRS = ( "/home/oleg-admin/django/itchallenges/static/", ) STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # 'django.contrib.staticfiles.finders.DefaultStorageFinder', ) TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', # 'django.template.loaders.eggs.Loader', ) TEMPLATE_DIRS = ( os.path.join(os.path.dirname(__file__), 'tpl/beadysite').replace('\\','/'), ) 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', )
Пытаюсь подключить CSS так: <link href=“{{ STATIC_URL }}css/style.css” rel=“stylesheet” type=“text/css” media=“screen” />
Вся статика собрана в папке static (там находятся папки соответственно css и images), которая находится в корневой папке проекта. Что же я делаю не так?
Офлайн
Bandicoot
{“context”:context} - эта строка обязательна? Мне пока что в шаблон нечего подставлять, кроме путей до css и картинок
def render_to_response(*args, **kwargs): """ Returns a HttpResponse whose content is filled with the result of calling django.template.loader.render_to_string() with the passed arguments. """ httpresponse_kwargs = {'mimetype': kwargs.pop('mimetype', None)} return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs) def render_to_string(template_name, dictionary=None, context_instance=None): """ Loads the given template_name and renders it with the given dictionary as context. The template_name may be a string to load a single template using get_template, or it may be a tuple to use select_template to find one of the templates in the list. Returns a string. """ dictionary = dictionary or {} if isinstance(template_name, (list, tuple)): t = select_template(template_name) else: t = get_template(template_name) if not context_instance: return t.render(Context(dictionary)) # Add the dictionary to the context stack, ensuring it gets removed again # to keep the context_instance in the same state it started in. context_instance.update(dictionary) try: return t.render(context_instance) finally: context_instance.pop()
Офлайн
Andrejus
Я так понимаю, есть проект и приложение к нему. Папка static находится в директории проекта. Мне нужно переместить статику в папку с приложением? Выходит ошибка 500 (Internal Server Error) в консоли Хрома. Приложение я пока не трогал, только создать командой startapp успел. Сайт достаточно простой, делаю его исключительно в учебных целях и мне не совсем понятно, зачем вообще в моем случае создавать приложение в дополнение к главному проекту? Да, возможно Джанго не самый подходящий вариант для простосайтов, но в том то и дело, что хочу научиться. Путаница в голове, извините. Apache не использую, только manage.py runserver
Офлайн
FishHookС глазами порядок, вот только скилл еще не прокачал) Как этот код соотнести с тем, что вытворяю я на данном этапе? Может код каких-либо еще файлов выложить из своего проекта?
Имеющий глаза да увидит
Офлайн
BandicootКороче, контекст передавать не обязательно.FishHookС глазами порядок, вот только скилл еще не прокачал) Как этот код соотнести с тем, что вытворяю я на данном этапе? Может код каких-либо еще файлов выложить из своего проекта?
Имеющий глаза да увидит
Офлайн