Bilder werden im Browser nicht angezeigt

Django, Flask, Bottle, WSGI, CGI…
erdmulch
User
Beiträge: 230
Registriert: Samstag 17. Juli 2010, 19:50

Hallo zusammen,

ich will mir mit Django einen Webserver aufsetzen was auch sehr gut funktioniert. Leider werden meine Bilder nicht angezeigt. das verzeichnis in dem die Bilder liegen ist /home/peter/tmp/djangoprojs/Wetterstation/Wetterstation/templates/articles/Bilder
kann mir jemand sagen wie ich meine settings.py konfigurieren muss?

Code: Alles auswählen

# 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 = ''
meine django startapp habe ich unter djangoprojs ausgeführt
gibt es sonst noch eine Einstellung die ich machen muss damit auch bilder auf meiner website angezeigt werden?
Sirius3
User
Beiträge: 17711
Registriert: Sonntag 21. Oktober 2012, 17:20

Bilder sollten nich in
../templates
sondern in
../static
abgelegt werden.

In einem Template kann dann über
<img src="{{STATIC_URL}}bild.jpg">
verwiesen werden.
erdmulch
User
Beiträge: 230
Registriert: Samstag 17. Juli 2010, 19:50

Naja, nachdem ich folgendes eingegeben habe:



<html>
<head>

<img src="{{Wetterstation/static/}}Bild.jpg">

</head>
</html>



erscheint folgende Fehlermeldung:

TemplateSyntaxError at /articles/

Could not parse the remainder: '/static/' from 'Wetterstation/static/'

Request Method: GET
Request URL: http://192.168.0.110:9090/articles/
Django Version: 1.4.2
Exception Type: TemplateSyntaxError
Exception Value:

Could not parse the remainder: '/static/' from 'Wetterstation/static/'

Exception Location: /usr/local/lib/python2.6/dist-packages/Django-1.4.2-py2.6.egg/django/template/base.py in __init__, line 563
Python Executable: /usr/bin/python
Python Version: 2.6.5
Python Path:

['/home/peter/tmp/djangoprojs/Wetterstation',
'/usr/local/lib/python2.6/dist-packages/pymodbus-0.5.1-py2.6.egg',
'/usr/local/lib/python2.6/dist-packages/pyserial-2.6-py2.6.egg',
'/usr/local/lib/python2.6/dist-packages/nose-1.1.2-py2.6.egg',
'/usr/local/lib/python2.6/dist-packages/Django-1.4.2-py2.6.egg',
'/usr/lib/python2.6',
'/usr/lib/python2.6/plat-linux2',
'/usr/lib/python2.6/lib-tk',
'/usr/lib/python2.6/lib-old',
'/usr/lib/python2.6/lib-dynload',
'/usr/lib/python2.6/dist-packages',
'/usr/lib/python2.6/dist-packages/PIL',
'/usr/lib/python2.6/dist-packages/gst-0.10',
'/usr/lib/pymodules/python2.6',
'/usr/lib/python2.6/dist-packages/gtk-2.0',
'/usr/lib/pymodules/python2.6/gtk-2.0',
'/usr/lib/python2.6/dist-packages/wx-2.8-gtk2-unicode',
'/usr/local/lib/python2.6/dist-packages']

Server time: Wed, 5 Dec 2012 23:06:28 +0100
BlackJack

@erdmulch: Du hast ja auch nicht das angegeben was Sirius3 vorgeschlagen hat. Und Du hast anscheinend nicht verstanden was ``{{`` und ``}}`` in der Templatesprache bedeuten.
erdmulch
User
Beiträge: 230
Registriert: Samstag 17. Juli 2010, 19:50

eigentlich hab ich schon das eingegeben was sirus gesagt hat, ich kann kein Fehler feststellen. Aber ich gebe zu, dass ich noch nicht genau weiß was {{}} die Klammern zu bedeuten haben! wäre für Hilfe sehr dankbar, hab meine Erfahrungen nur aus einem Buch heruass
Benutzeravatar
/me
User
Beiträge: 3554
Registriert: Donnerstag 25. Juni 2009, 14:40
Wohnort: Bonn

erdmulch hat geschrieben:Aber ich gebe zu, dass ich noch nicht genau weiß was {{}} die Klammern zu bedeuten haben!
Das wird das erste Mal in Teil 3 des Django-Tutorials erwähnt. Detailliert findest du es in der Erläuterung zur Django Template Language.

Im Prinzip definiert der Inhalt nichts anderes als einen Platzhalter für Text der aus der View übergeben wird. STATIC_URL ist ein spezieller Text der durch einen Template Context Prozessor (django.core.context_processors.static) automatisch übergeben wird wenn er in der settings.py aktiviert wurde.

Du hast jetzt Wetterstation/static/ als Text angegeben. Das ist nicht das, was dorthin gehört. Dahin gehört tatsächlich einfach der Text STATIC_URL. Den Wert dafür definierst du in der settings.py als ... Überraschung ... STATIC_URL.

Solltest du jemals mit dem statischen Pfad umziehen, dann konfigurierst du das nur einmal in den Settings und nicht in jedem einzelnen Template.
erdmulch
User
Beiträge: 230
Registriert: Samstag 17. Juli 2010, 19:50

hallo zusammen,

ich würde gerne in meine Website ein Bild hinzufügen. dachte eigentlich immer nur ich müsste den Pfas zum Bild angeben. Allerdings erscheint kein Bild auf meiner html Seite.

weiter unten ist meine settings.py kann mir jemand sage, ob ich was falsch mache oder ob ich was falsches konfiguriert habe? muss ich überhaupt etwas konfigurieren?

vielen Dank im voraus

Code: Alles auswählen


DEBUG = True
TEMPLATE_DEBUG = DEBUG

ADMINS = ()

MANAGERS = ADMINS

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'pybookdb',                      # Or path to database file if using sqlite3.
        'USER': 'pythonbook',                      # Not used with sqlite3.
        'PASSWORD': 'geheim',                  # Not used with sqlite3.
        'HOST': '127.0.0.1',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '5432',                      # 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.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'Europe/Berlin'

# 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 = False

# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True

# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = False

# 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 = '/templates/'

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


# 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',
    # Uncomment the next line for simple clickjacking protection:
    # 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

ROOT_URLCONF = 'Wetterstation.urls'

# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'Wetterstation.wsgi.application'

TEMPLATE_DIRS = (
    '/home/peter/tmp/djangoprojs/Wetterstation/Wetterstation/templates/articles',
    # 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.
)

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

# 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 when DEBUG=False.
# 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,
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        }
    },
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler'
        }
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
    }
}
Sirius3
User
Beiträge: 17711
Registriert: Sonntag 21. Oktober 2012, 17:20

1. Bilder sind keine Templates:
STATIC_URL = '/static/'

2. Du hast Deine Wetterstation gar nicht in INSTALLED_APPS stehen.
Wie kann Dein Webserver da überhaupt funktionieren?

3. jede App hat normalerweise ein Verzeichnis:
path_to_your_app/static
in dem z.B. Bilder liegen.
Ansprechen kann man sie im html-Code so:
<img src="{{STATIC_URL}}bild.jpg">
Benutzeravatar
kbr
User
Beiträge: 1487
Registriert: Mittwoch 15. Oktober 2008, 09:27

Oh je. Ich verstehe Dich ja - aber warum nimmst Du Dir nicht die Zeit, das Django-Tutorial einmal in Ruhe durchzugehen? (Wir haben ja über Weihnachten immerhin ein paar ruhige Tage.)
Also: in setting.STATIC_ROOT gehört der absolute Pfad zu dem Verzeichnis, in dem Du die statischen Dateien, wie z.B. Bilder, vorhältst. Wie z.B.
'/home/peter/tmp/djangoprojs/Wetterstation/Wetterstation/templates/articles/Bilder'.
Statt 'templates/articles/Bilder' solltest Du allerdingst 'static' wählen, da statische Dateien nicht zu den zu rendernden Templates sondern zu extern zugänglichen Resourcen zählen und dementsprechend auch getrennt gespeichert werden sollten.
In settings.STATIC_URL solltest Du '/static/' eintragen.
Mit dem Tag '<img src="{{STATIC_URL}}bild.jpg">' verweist Du dann auf die Datei 'bild.jpg' die sich in dem Verzeichnis 'settings.STATIC_ROOT' befindet.
Das kann auf den ersten Blick verwirrend erscheinen, ist aber logisch angelegt.
Bitte nochmals: nimm Dir die Zeit, das Django-Tutorial in Ruhe durchzugehen. Und anschließend die Doku erstmal querlesen. Das ist Arbeit, aber hilft - wirklich.
erdmulch
User
Beiträge: 230
Registriert: Samstag 17. Juli 2010, 19:50

Hallo nochmals,

habe das script schon gelesen, doch leider weicht Theorie und Praxis voneinander ab.
ich hatte auch schon die Pfade angepasst, allerdings hat es nicht den gewünschten Erfolg, sodass ich mir dann nicht mehr sicher war

das ist mein html code:

Code: Alles auswählen

<img src="{{STATIC_URL}}Test.gif">
und das war meine settings.py

Code: Alles auswählen

# Django settings for Wetterstation project.

DEBUG = True
TEMPLATE_DEBUG = DEBUG

ADMINS = ()

MANAGERS = ADMINS

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'pybookdb',                      # Or path to database file if using sqlite3.
        'USER': 'pythonbook',                      # Not used with sqlite3.
        'PASSWORD': 'geheim',                  # Not used with sqlite3.
        'HOST': '127.0.0.1',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '5432',                      # 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.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'Europe/Berlin'

# 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 = False

# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True

# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = False

# 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 = '/home/peter/tmp/djangoprojs/Wetterstation/Wetterstation/templates/'

# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/Wetterstation/articles/Bilder/'

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



# 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',
    # Uncomment the next line for simple clickjacking protection:
    # 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

ROOT_URLCONF = 'Wetterstation.urls'

# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'Wetterstation.wsgi.application'

TEMPLATE_DIRS = (
    '/home/peter/tmp/djangoprojs/Wetterstation/Wetterstation/templates/articles',
    # 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.
)

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

    # optional Apps
    'Wetterstation',



)

# 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 when DEBUG=False.
# 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,
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        }
    },
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler'
        }
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
    }
}
hier ist noch ein auszug von meiner konsole:
meine Bilder liegen unter /home/peter/tmp/djangoprojs/Wetterstation/Wetterstation/articles/Bilder
der Pfad passt definitiv

Code: Alles auswählen

[27/Dec/2012 10:47:25] "GET /articles/ HTTP/1.1" 200 1253
[27/Dec/2012 10:47:25] "GET /articles/style.css HTTP/1.1" 404 2052
[27/Dec/2012 10:47:25] "GET /Wetterstation/articles/Bilder/Test.gif HTTP/1.1" 404 1699
Peter@peter-desktop:~/tmp/djangoprojs/Wetterstation$ 

Zuletzt geändert von erdmulch am Donnerstag 27. Dezember 2012, 11:59, insgesamt 1-mal geändert.
Sirius3
User
Beiträge: 17711
Registriert: Sonntag 21. Oktober 2012, 17:20

Nach Deinen kreativen Benennungen zufolge, muß Test.gif genau da liegen:
/home/peter/tmp/djangoprojs/Wetterstation/Wetterstation/templates/
und nicht da:
/home/peter/tmp/djangoprojs/Wetterstation/Wetterstation/articles/Bilder.
Da wird nämlich nicht gesucht.

Aber trotzdem der Hinweis:
Bitte gewöhn Dir an, Dinge so zu nennen, wie sie logischerweise jeder nennt.
STATIC_URL = '/static/'
und von mir aus
STATIC_ROOT = '/home/peter/tmp/djangoprojs/Wetterstation/Wetterstation/static/'
obwohl das völlig unnötig ist, weil django automatisch in diesem Verzeichnis sucht.
Dein style.css sollte auch irgendwo im static-Verzeichnis liegen.
Genauso gibt es für templates eine Standardsuchreihenfolge. Nutze diese Möglichkeiten
auch und vermeide absolute Pfade wo immer es geht (also fast überall).
erdmulch
User
Beiträge: 230
Registriert: Samstag 17. Juli 2010, 19:50

Hallo, ich bins nochmals,

hab es nun nach dem obigen Beispiel versucht, allerdings ohne Erfolg.
kann es sein, damit ich in der urls.py etwas eintragen muss? dass die Bilder gerendert werden können?

vielen Dank im voraus
Benutzeravatar
sparrow
User
Beiträge: 4164
Registriert: Freitag 17. April 2009, 10:28

Zeig bitte von welcher URL die Bilder geladen werden, wo sie in deinem Pfad liegen und welche Einstellungen du in der settings.py vorgenommen hast.
erdmulch
User
Beiträge: 230
Registriert: Samstag 17. Juli 2010, 19:50

Hier ist meine settings.py
die Bilder habe ich unter: /home/peter/tmp/djangoprojs/Wetterstation/Wetterstation/templates/articles/Bilder
abgelegt. Das Bild heißt: Test.gif

Code: Alles auswählen

# Django settings for Wetterstation project.

DEBUG = True
TEMPLATE_DEBUG = DEBUG

ADMINS = ()

MANAGERS = ADMINS

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'pybookdb',                      # Or path to database file if using sqlite3.
        'USER': 'pythonbook',                      # Not used with sqlite3.
        'PASSWORD': 'geheim',                  # Not used with sqlite3.
        'HOST': '127.0.0.1',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '5432',                      # Set to empty string for default. Not used with sqlite3.
    }
}

# Local time zone for this installation. Choices can be found here:
# <!-- m --><a class="postlink" href="http://en.wikipedia.org/wiki/List_of_tz_zones_by_name">http://en.wikipedia.org/wiki/List_of_tz_zones_by_name</a><!-- m -->
# although not all choices may be available on all operating systems.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'Europe/Berlin'

# Language code for this installation. All choices can be found here:
# <!-- m --><a class="postlink" href="http://www.i18nguy.com/unicode/language-identifiers.html">http://www.i18nguy.com/unicode/language ... fiers.html</a><!-- m -->
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 = False

# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True

# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = False

# 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 = '/home/peter/tmp/djangoprojs/Wetterstation/Wetterstation/templates/articles/Bilder'

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



# 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',
    # Uncomment the next line for simple clickjacking protection:
    # 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

ROOT_URLCONF = 'Wetterstation.urls'

# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'Wetterstation.wsgi.application'

TEMPLATE_DIRS = (
    '/home/peter/tmp/djangoprojs/Wetterstation/Wetterstation/templates/articles',
    # 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.
)

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

    # optional Apps
    'Wetterstation',



)

# 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 when DEBUG=False.
# See <!-- m --><a class="postlink" href="http://docs.djangoproject.com/en/dev/topics/logging">http://docs.djangoproject.com/en/dev/topics/logging</a><!-- m --> for
# more details on how to customize your logging configuration.
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        }
    },
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler'
        }
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
    }
}
 
meine html Seite sieht wie folgt aus:

Code: Alles auswählen

{% block content %}
<html>
<img src="{{STATIC_URL}}Test.gif"</img>	
<body>
{% for article in latest_articles_list %}
<div id="myContent">{{ article.title }}</div>	
{%endfor%}
</body>
</html>
{% endblock %}
die urls.py sieht wie folgt aus:

Code: Alles auswählen

from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
    url(r'^articles/$', 'Wetterstation.articles.views.index',
        name='/home/peter/tmp/djangoprojs/Wetterstation/Wetterstation/articles.views.index'
    ),
)
ich habe auch mal die Zeile " #'django.contrib.staticfiles'," in der Settings.py auskommentiert um den Pfad direkt einzugeben. bin mir aber nicht sicher ob dies richtig ist.
Außerdem weiß ich nicht ob ich was an der urls.py eintragen muss. Aus der Django Doku war meiner Ansicht nach nichts erkenntliches zu lesen
Sirius3
User
Beiträge: 17711
Registriert: Sonntag 21. Oktober 2012, 17:20

@erdmulch: mach Dir bitte endlich klar, was der Unterschied zwischen einem lokalen Pfad und einer URL ist!!!

lokaler Pfad:
/home/peter/tmp/djangoprojs/Wetterstation/Wetterstation/templates/articles/Bilder/Test.gif

URL:
http://localhost:8000/static/Test.gif

Irgendwie muß django die URL in den lokalen Pfad umwandeln.
Deshalb:
STATIC_URL = '/static/'
und
STATIC_ROOT = '/home/peter/tmp/djangoprojs/Wetterstation/Wetterstation/templates/articles/Bilder/'

Das ist jetzt zwar eine Lösung, die funktioniert, sinnvoll, gut und schön ist sie aber nicht.

Programmieren ist kein Geduldsspiel, wo man alle Möglichkeiten ausprobiert, bis eine tut.
Man muß schon verstehen, warum etwas funktioniert, wie ein Rädchen ins andere greift.

Also bitte ich Dich, in einer ruhigen Stunde nochmals die ganzen Antworten auf Deine Fragen
hier durchzulesen bis Du begreifst warum was wo steht.
erdmulch
User
Beiträge: 230
Registriert: Samstag 17. Juli 2010, 19:50

Hallo nochmals,

habe mein Django nach folgender Anleitung neu eingerichtet:
http://stefanimhoff.de/notiz/django-webdesigner/
allerdings wieder das gleiche Problem mit den Bilder.

so langsam glaube ich dass ich etwas anderes falsch mache
hat dies http://stefanimhoff.de/notiz/django-webdesigner/ schon jemand getestet?

danke im voraus
BlackJack

@erdmulch: Ich sehe da keine Anleitung hinter dieser URL‽ Aber eine Textstelle möchte ich mal zitieren: „Das URL-Design ist bei Django ein integraler Bestandteil. Es ist sogar nötig, sich damit zu beschäftigen.”
erdmulch
User
Beiträge: 230
Registriert: Samstag 17. Juli 2010, 19:50

hallo nochmals,

ich setzte mich ja mit der Thematik auseinander. Aber ich kann nirgends raus lesen was zu tun ist, wenn ich ein Bild in meine Homepage mit einbinden will.
wenn ich ein Bild einbinden will, ich aber schon eine Seite mit Textstellen habe die auch funktionieren, muss ich dann was an der urls.py anpassen?
ich glaube ein einfaches ja oder nein würde mich an dieser Stelle schon weiter bringen
apollo13
User
Beiträge: 827
Registriert: Samstag 5. Februar 2005, 17:53

Nein musst du nicht, du solltest allerdings aufhören Tutorials aus dem Jahr 2009 zu lesen, Django hat sich seit 2009 stark verändert, auch was das Handling von Bildern betrifft. Also: Sieh zu dass du ein aktuelles Django hast und lies die englische Originaldokumentation auf der Djangoseite (Oder wenn es deutsch sein muss: http://www.django-workshop.de/ ).
Benutzeravatar
sparrow
User
Beiträge: 4164
Registriert: Freitag 17. April 2009, 10:28

In der urls.py definierst du welche URL-Aufrufe auf wie auf welche Python-Methoden (views) gemappt werden. Deine Bilder sind keine Python-Methoden, also haben die nichts mit der urls.py zu tun.

Leg in deiner Django-Applikation (nicht dem Projekt) einen Unterordner namens "static" an und leg die Bilder hinein. Der Django-Development-Webserver wird dafür sorgen, dass sie mit dem URL-Prefix, das in der settings.py konfiguriert ist, abgerufen werden kann. Standardmäßig ist das /static.
Wenn du das in deinen Templates gleich per Variable abrufst, brauchst du das noch nicht einmal angeben. {{ STATIC_URL }} in einem RequestContext hilft dort sehr weiter.

Wenn dein Projekt irgendwann auf einem richtigen Webserver läuft, separiert man die statischen Dateien von den Python-Dateien und lässt sie über einen speziellen Webserver oder zumindest eine separate Konfiguration ausliefern, damit sie nicht durch den Interpreter müssen.
Antworten