Foros del Web » Programando para Internet » Python »

Mostrar imagenes estaticas django en formulario

Estas en el tema de Mostrar imagenes estaticas django en formulario en el foro de Python en Foros del Web. Hola me he leido el tutorial de django: [URL="https://docs.djangoproject.com/en/dev/howto/static-files/#referring-to-static-files-in-templates"]https://docs.djangoproject.com/en/dev/howto/static-files/#referring-to-static-files-in-templates[/URL] y aún asi no me ve las imagenes me sale un error: Código: [23/Aug/2012 02:51:33] "GET ...
  #1 (permalink)  
Antiguo 23/08/2012, 02:21
 
Fecha de Ingreso: agosto-2012
Mensajes: 23
Antigüedad: 12 años, 3 meses
Puntos: 0
Mostrar imagenes estaticas django en formulario

Hola me he leido el tutorial de django:

[URL="https://docs.djangoproject.com/en/dev/howto/static-files/#referring-to-static-files-in-templates"]https://docs.djangoproject.com/en/dev/howto/static-files/#referring-to-static-files-in-templates[/URL]

y aún asi no me ve las imagenes me sale un error:

Código:
[23/Aug/2012 02:51:33] "GET /Archivos/Incidencias.png HTTP/1.1" 404 1959
y prometo que tengo ahi el archivo y que la ruta es la correcta.

pongo mi codigo:

URL.PY
Código:
from django.conf.urls import patterns, include, url
from django.conf import settings
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'TSOL.views.home', name='home'),
    # url(r'^TSOL/', include('TSOL.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)),
    url(r'^$', 'Contenido.views.PaginaPrincipal'),
)

if settings.DEBUG:
    urlpatterns += patterns('',
        url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
            'document_root': settings.MEDIA_ROOT,
        }),
   )

SETTINGS.PY
Código:
# Django settings for TSOL project.

DEBUG = True
TEMPLATE_DEBUG = DEBUG

ADMINS = (
    # ('Your Name', '[email protected]'),
)

MANAGERS = ADMINS

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'BaseDatos',                        # 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

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

# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = '/home/sergio/Escritorio/TSOL/Archivos/'

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

# 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/sergio/Escritorio/TSOL/ArchivosEstaticos/'

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

# 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 = '-t_otrxep#nrabp=6^)&amp;ut^ki7lbjv=rh31-rqm97#a)x5((me'

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

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

TEMPLATE_DIRS = (
    '/home/sergio/Escritorio/TSOL/templates',
    # 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',
    'Contenido',
)

# 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,
        },
    }
}
HTML
Código:
<html>
    <head>
		<meta charset="utf-8">
		<title>Resumen CSV</title>
    </head>

    <body>
        {{datos|safe}}
        <img src="{{ MEDIA_URL }}Incidencias.png" alt="Incidencias" />
        <form method="get" action=/>
                {% csrf_token %}
                <div align="center">
                    <p><input type=submit value=VolverPaginaPrincipal></input></p>
                </div>
        </form>
    </body>

<html>
PARTE DE VIEWS.PY
Código:
def PaginaPrincipal(request):
    if request.method == 'POST':
        #print request.POST.getlist('numerodia') con esto saco lo que contiene numero dia
        FechaSeleccionada = request.POST['fechaSeleccionar']
        NumeroDias = request.POST['numerodia']
        ListaDeDias = CalcularDiasAnteriores(NumeroDias,FechaSeleccionada)
        form = Documentos(request.POST, request.FILES)
        
        if form.is_valid():
            Fichero=request.FILES['fichero']
            Datos = RecorrerCSV(Fichero,ListaDeDias)
            return render_to_response('ResumenCSV.html',{'datos':Datos},context_instance=RequestContext(request))

    #Uso este else en lugar de request.method == 'GET':  por si me lo quieren tirar abajo 
    else:
        form = Documentos() 
        return render_to_response('PaginaInicial.html',{'form': form},
        context_instance=RequestContext(request)
        )
El fichero se tiene que ver al hacer el post, en ResumenCSV que es el html que muestro.
Las imagenes las saco asi:

Código:
        ListaEjeYIA = ListaResumenIncidenciasAbiertas
        ListaEjeYIR = ListaResumenIncidenciasResueltas
        ListaEjeYIP = ListaResumenIncidenciasPendientes
        ListaEjeYII = ListaResumenIncidenciasIncumplidas
        plt.figure(1)
        plt.xlabel('fecha')
        plt.ylabel('datos')
        plt.title('Grafica Incidencia')
        plt.plot(ListaEjeX,ListaEjeYIA,"b",label='Incidencia Abiertas')
        plt.plot(ListaEjeX,ListaEjeYIR,"r",label='Incidencia Resueltas')
        plt.plot(ListaEjeX,ListaEjeYIP,"k",label='Incidencia Pendientes')
        plt.plot(ListaEjeX,ListaEjeYII,"g",label='Incidencia Incumplidas')
        leg = plt.legend ()
        #Uso get_frame().set_alpha(0.5) para hacer el cuadro de la leyenda transparente si pusiera leg.get_frame().set_visible(False) se
        #quitaria el cuadro
        leg.get_frame().set_alpha(0.5) 
        plt.xticks(ListaEjeX, listaDias, rotation=45)
        plt.savefig('/home/sergio/Escritorio/TSOL/Archivos/Incidencias.png')
y el path donde esta mis archivos es:
Código:
/home/sergio/Escritorio/TSOL/Archivos

Sería de gran ayuda si me pudierais hechar una mano.Un saludo y gracias!!

Última edición por supersergio; 23/08/2012 a las 02:41
  #2 (permalink)  
Antiguo 23/08/2012, 05:24
 
Fecha de Ingreso: agosto-2012
Mensajes: 23
Antigüedad: 12 años, 3 meses
Puntos: 0
Respuesta: Mostrar imagenes estaticas django en formulario

Hola me cnt a mi mismo ya esta solucionado.

Código:
ESQUEMA:

       TSOL
               TSOL
                     ARCHIVOS
                     STATIC
                     TEMPLATES
                     SETTINGS.PY
                     URLS.PY
               CONTENIDO
                     MODELS.PY
                     FORMS.PY
                     VIEWS.PY
               MANAGE.PY
SETTINGS.PY
Código:
# Django settings for TSOL project.

DEBUG = True
TEMPLATE_DEBUG = DEBUG

import os
PROJECT_ROOT = os.path.realpath(os.path.dirname(__file__))

ADMINS = (
    # ('Your Name', '[email protected]'),
)

MANAGERS = ADMINS

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'BaseDatosPF',                       # 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

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

# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'Archivos')

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

# 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 = os.path.join(PROJECT_ROOT, 'static')

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


# 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 = '-t_otrxep#nrabp=6^)&amp;ut^ki7lbjv=rh31-rqm97#a)x5((me'

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

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

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

# 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,
        },
    }
}
URLS.PY
Código:
from django.conf.urls import patterns, include, url
from django.conf import settings
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'TSOL.views.home', name='home'),
    # url(r'^TSOL/', include('TSOL.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)),
    url(r'^$', 'Contenido.views.PaginaPrincipal'),
)
urlpatterns += patterns('',
        (r'^Archivos/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.MEDIA_ROOT}),
        (r'^static/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.STATIC_ROOT}),
)

Mi fallo era en urls.py que no ponia bien el urlpatterns. Saludo y espero que os ayude si os da algun problema

Etiquetas: csv, django, formulario, imagenes
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 15:33.