Медиа контент работает - PullRequest
1 голос
/ 07 августа 2011

Так что я пытаюсь составить портфолио и пытаюсь просто проверить что-то локально, но это НЕ использует мой медиа-контент ... Я действительно перепробовал МНОГО материала ... и у меня нет идей.

Сгенерированный HTML-код правильный, поскольку я использовал для этого валидатор W3C. И src, на который он ссылается, также корректен: /media/css/foo.css

И я вполне уверен, что мой media_URL в файле settings.py также имеет значение:

/media/

Теперь вот мой файл настроек, HTML, CSS, представления, URL-адреса и файловая структура

НАСТРОЙКИ:

# Django settings for portfolio project.
import os 
gettext = lambda s: s
PROJECT_PATH = os.path.abspath(os.path.dirname(__file__))


DEBUG = True
TEMPLATE_DEBUG = DEBUG

ADMINS = (
    # ('Your Name', 'your_email@domain.com'),
)

MANAGERS = ADMINS

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': os.path.join(PROJECT_PATH, 'database.db'),                      # Or path to database file if using sqlite3.
        'USER': '',                      # 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_ROOT = os.path.join(PROJECT_PATH, "media")

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = "/media/"

# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
# trailing slash.
# Examples: "http://foo.com/media/", "/media/".
ADMIN_MEDIA_PREFIX = '/media/admin/'

# Make this unique, and don't share it with anybody.
SECRET_KEY = 'blabla'

# 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',
)

TEMPLATE_CONTEXT_PROCESSORS= (
    'django.core.context_processors.auth', 
    'django.core.context_processors.i18n', 
    'django.core.context_processors.request',
    'django.core.context_processors.media',
)

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 = 'portfolio_svn.urls'

LANGUAGES = [
    ('en', 'English'),
]

TEMPLATE_DIRS = (
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
    os.path.join(PROJECT_PATH, "templates"),
)

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    # Uncomment the next line to enable the admin:
    'django.contrib.admin',
    'portfolio',
    # Uncomment the next line to enable admin documentation:
    # 'django.contrib.admindocs',
)

HTML: base.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />

    <title>{% block page_title %}{% endblock %}</title>
    <link rel="stylesheet" href="{{ MEDIA_URL }}base.css" />

    {% block head_extra %} {% endblock %}
    <!-- Enabling HTML5 tags for older IE browsers -->
    <!--[if lt IE 9]>
        <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
</head>

<body>
<header>
<h1>My portfolio</h1>
</header>

{% block nav %}
<nav id = "navigation">

</nav>
{% endblock %}


<section id = "content">

{% block content %}

{% endblock %}
</section>



<footer>

</footer>

{% block includes %}{% endblock %}

</body>
</html>

HTML index.html

{% extends "portfolio/base.html" %}

{% block page_title %}
Lime Design | Best web dev and design online
{% endblock %}

{% block head_extra %}
    <link rel="stylesheet" href="{{ MEDIA_URL }}css/nav_port.css" />
{% endblock %}



{% block content %}

<nav id = "filter">

</nav>

<section id="container">
    <ul id="stage">
        {% for project in projecten %}
            <li data-tags="{{ project.disciplines }}">
                <img src="{{ project.overview_image }}" alt="{{ project.name }}" />
            </li>

        {% endfor %}
    </ul>    
</section>
{% endblock %}


{% block includes %}
<script src = "http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script src = "{{ MEDIA_URL }}js/jquery.quicksand.js"></script>
<script src = "{{ MEDIA_URL }}js/script.js"></script>
{% endblock %}

CSS

body{
background-color: #151515;
}

вид

from django.shortcuts import get_object_or_404, render_to_response
from django.template.context import RequestContext
from django.http import HttpResponseRedirect, HttpResponse, Http404
from models import Medium, Client, Project


def index(request):
    projecten = Project.objects.all()  
    context = {'projecten': projecten}
    return render_to_response('portfolio/index.html', context_instance=RequestContext(request, context))

URLS:

from django.conf.urls.defaults import *
from portfolio_svn.portfolio.models import Project
from portfolio_svn.portfolio.views import index
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    (r'^index', index),
    (r'^', index),
    (r'^admin/doc/', include('django.contrib.admindocs.urls')),
    (r'^admin/', include(admin.site.urls)),
)

структура файла

portfolio_svn
├── database.db
├── __init__.py
├── __init__.pyc
├── local_settings.py
├── local_settings.pyc
├── manage.py
├── media
│   ├── css
│   │   └── nav_port.css
│   ├── images
│   │   └── thumbmails
│   │       ├── 1.png
│   │       ├── 2.png
│   │       ├── 3.png
│   │       └── 4.png
│   └── js
│       ├── jquery.quicksand.js
│       └── script.js
├── portfolio
│   ├── admin.py
│   ├── admin.pyc
│   ├── __init__.py
│   ├── __init__.pyc
│   ├── models.py
│   ├── models.pyc
│   ├── tests.py
│   ├── views.py
│   └── views.pyc
├── settings_backup_local.py
├── settings_backup_real.py
├── settings.py
├── settings.pyc
├── templates
│   └── portfolio
│       ├── base.html
│       └── index.html
├── urls.py
└── urls.pyc

Я надеюсь, что кто-то может помочь мне определить проблему ..

1 Ответ

3 голосов
/ 07 августа 2011

Вы, похоже, используете носитель для того, для чего предназначен статический сигнал, отметьте здесь

В резюме папка мультимедиа создана для людей, загружающих фотографии, файлы и т. Д.

статическая папка для css, js, изображений, которые вы используете на своем сайте.

если вы не загружаете статическую папку на отдельный сервер, вы можете добавить эти строки в ваш urls.py

from django.contrib.staticfiles.urls import staticfiles_urlpatterns

urlpatters = patterns ......#do your patterns here

urlpatterns += staticfiles_urlpatterns()

таким образом Django сразу монтирует статические файлы.

чтобы django мог найти эти статические файлы, вы должны добавить их в settings.py следующие значения: import os

PROJECT_ROOT = os.path.dirname(__file__)

STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static/')

STATIC_URL = '/static/'

STATICFILES_DIR = (
    "portfolio/static/",
)

STATICFILES_FINDERS = ( 
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
#'django.contrib.staticfiles.finders.DefaultStorageFinder',
)

TEMPLATE_CONTEXT_PROCESSORS = (
    'django.core.context_processors.static',
     #... other context processors
)

INSTALLED_APPS = (
    ....#other apps
    'django.contrib.staticfiles',
)

переместите эту статическую папку в приложение вашего приложения (в нашем случае портфолио) и выполните команду

./manage.py collectstatic.

, чтобы убедиться, что она работает.(вы должны изменить 'django.core.context_processors.media' на 'django.core.context_processors.static' btw)

PD: если вы хотите передать запрос на ваш render_to_response, вы можете использовать рендер (запрос, вместо этого: "portfolio / index.html":)

...