files estaticos carga archivos python css django rendering django-views

python - estaticos - CSS no se carga en Django mientras se visualiza



django styles (2)

Me sumerjo en Django haciendo blog. El problema es que, después de la vista de representación, solo hay contenido de texto sin estilos CSS en la página. Otros tipos de páginas se procesan correctamente.

Esta es mi configuración:

mysite / blog / views.py

from django.shortcuts import render_to_response, get_object_or_404 from blog.models import Post,Cat def view_cat(request, slug): cat = get_object_or_404(Cat, slug=slug) return render_to_response(''cats.html'', { ''cat'': cat, ''posts'': Post.objects.filter(cat=cat)[:5] })

mysite / blog / urls.py

from django.conf.urls.defaults import * from django.views.generic import DetailView, ListView from blog.models import Post, Cat urlpatterns = patterns('''', url(r''^$'', ListView.as_view( queryset=Post.objects.order_by(''-pub_date'')[:10], template_name=''index.html'' ) ), url(r''^(?P<pk>/d+)/$'', DetailView.as_view( model=Post, template_name=''detail.html'' ) ), url(r''^cat/(?P<slug>/w+)/$'', ''blog.views.view_cat'', ), )

mysite / urls.py

from django.conf.urls.defaults import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('''', url(r'''',include(''blog.urls'')), url(r''^admin/'', include(admin.site.urls)), url(r''^about/$'', ''django.views.generic.simple.direct_to_template'', {''template'': ''about.html''}), url(r''^contact/$'', ''django.views.generic.simple.direct_to_template'', {''template'': ''contact.html''}), )

mysite / settings.py

# Django settings for mysite project. DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # (''Your Name'', ''[email protected]''), ) MANAGERS = ADMINS DATABASES = { ''default'': { ''ENGINE'': ''django.db.backends.sqlite3'', # Add ''postgresql_psycopg2'', ''postgresql'',''mysql'', ''sqlite3'' or ''oracle''. ''NAME'': ''/home/user/www/mysite/sqlite3.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/" MEDIA_ROOT = ''/home/user/www/mysite/media/'' # 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 = ''/media/'' # 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/user/www/mysite/static/'' # 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 = ''26m-1=h8m+a+s3y@tv!!3pagdcjt)0(bz)lr79%yiy8e8&0=c-'' # 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 = ''mysite.urls'' TEMPLATE_DIRS = ( ''/home/user/www/mysite/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'', ''django.contrib.comments'', # Uncomment the next line to enable the admin: ''django.contrib.admin'', # Uncomment the next line to enable admin documentation: # ''django.contrib.admindocs'', ''blog'', ) # 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, }, } }

mysite / templates / cats.html (indicado en mysite / blog / views.py), CSS no se carga aquí

<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Mysite.com</title> <meta name="description" content=""> <meta name="author" content=""> <!-- Le HTML5 shim, for IE6-8 support of HTML elements --> <!--[if lt IE 9]> <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <!-- Le styles --> <link href="{{ STATIC_URL }}css/bootstrap.css" rel="stylesheet"> <style> body { padding-top: 60px; /* 60px to make the container go all the way to the bottom of the topbar */ } </style> <!-- Le fav and touch icons --> <link rel="shortcut icon" href="{{ STATIC_URL }}images/favicon.ico"> <link rel="apple-touch-icon" href="{{ STATIC_URL }}images/apple-touch-icon.png"> <link rel="apple-touch-icon" sizes="72x72" href="{{ STATIC_URL }}images/apple-touch-icon-72x72.png"> <link rel="apple-touch-icon" sizes="114x114" href="{{ STATIC_URL }}images/apple-touch-icon-114x114.png"> </head> <body> <div class="navbar navbar-fixed-top"> <div class="navbar-inner"> <div class="container"> <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </a> <a class="brand" href="/">Mysite.com</a> <div class="nav-collapse"> <ul class="nav"> <li class="active"><a href="/">Blog</a></li> <li><a href="/about">About</a></li> <li><a href="/contact">Contact</a></li> </ul> </div><!--/.nav-collapse --> </div> </div> </div> <div class="container"> <div class="row"> <div class="span9"> <ul class="breadcrumb"> <li> <a href="/">Home</a> <span class="divider">/</span> </li> <li> <strong><a href="">{{ cat.name }}</a></strong> </li> </ul> </div> <div class="span3"> <h3>Construction progress...</h3> <span class="label label-info">Functionality</span></p> <div class="progress progress-info progress-striped active"> <div class="bar" style="width: 50%;"></div> </div> <span class="label label-info">Design</span></p> <div class="progress progress-info progress-striped active"> <div class="bar" style="width: 30%;"></div> </div> <span class="label label-info">Usability</span></p> <div class="progress progress-info progress-striped active"> <div class="bar" style="width: 5%;"></div> </div> </div> </div> </div> <!-- /container --> <!-- Le javascript ================================================== --> <!-- Placed at the end of the document so the pages load faster --> <script src="{{ STATIC_URL }}js/jquery.js"></script> <script src="{{ STATIC_URL }}js/bootstrap.js"></script> <script src="{{ STATIC_URL }}js/bootstrap-alert.js"></script> </body> </html>

mysite / templates / index.html (por ejemplo), CSS carga aquí pero hay pocas diferencias entre cats.html e index.html

<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Mysite.com</title> <meta name="description" content=""> <meta name="author" content=""> <!-- Le HTML5 shim, for IE6-8 support of HTML elements --> <!--[if lt IE 9]> <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <!-- Le styles --> <link href="{{ STATIC_URL }}css/bootstrap.css" rel="stylesheet"> <style> body { padding-top: 60px; /* 60px to make the container go all the way to the bottom of the topbar */ } </style> <!-- Le fav and touch icons --> <link rel="shortcut icon" href="{{ STATIC_URL }}images/favicon.ico"> <link rel="apple-touch-icon" href="{{ STATIC_URL }}images/apple-touch-icon.png"> <link rel="apple-touch-icon" sizes="72x72" href="{{ STATIC_URL }}images/apple-touch-icon-72x72.png"> <link rel="apple-touch-icon" sizes="114x114" href="{{ STATIC_URL }}images/apple-touch-icon-114x114.png"> </head> <body> <div class="navbar navbar-fixed-top"> <div class="navbar-inner"> <div class="container"> <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </a> <a class="brand" href="/">Mysite.com</a> <div class="nav-collapse"> <ul class="nav"> <li class="active"><a href="/">Blog</a></li> <li><a href=''/about''>About</a></li> <li><a href="/contact">Contact</a></li> </ul> </div><!--/.nav-collapse --> </div> </div> </div> <div class="container"> <div class="row"> <div class="span9"> {% if post_list %} {% for post in post_list %} <strong><a href="/{{ post.id }}/">{{ post.title }}</a></strong> at <a href="/cat/{{post.cat.slug}}/">{{post.cat}}</a></p> <p>{{ post.body }} <a href="/{{ post.id }}/">read more</a></p> <hr> {% endfor %} {% else %} <p>No posts are available.</p> {% endif %} </div> <div class="span3"> <h3>Construction progress...</h3> <span class="label label-info">Functionality</span></p> <div class="progress progress-info progress-striped active"> <div class="bar" style="width: 50%;"></div> </div> <span class="label label-info">Design</span></p> <div class="progress progress-info progress-striped active"> <div class="bar" style="width: 30%;"></div> </div> <span class="label label-info">Usability</span></p> <div class="progress progress-info progress-striped active"> <div class="bar" style="width: 5%;"></div> </div> </div> </div> </div> <!-- /container --> <!-- Le javascript ================================================== --> <!-- Placed at the end of the document so the pages load faster --> <script src="{{ STATIC_URL }}js/jquery.js"></script> <script src="{{ STATIC_URL }}js/bootstrap.js"></script> <script src="{{ STATIC_URL }}js/bootstrap-alert.js"></script> </body> </html>

Creo que hay un error en blog / views.py y / y blog / urls.py, porque cuando elimino el código de django de cats.html, la situación sigue siendo la misma: solo aparece texto sin estilos cuando voy a www.misitio.com/cat/asfas/

(Sí, asfas es una verdadera babosa de categoría)


Tenga en cuenta que también necesita pasar el objeto de solicitud al acceso directo de procesamiento.

from django.shortcuts import render ... return render(request, ''cats.html'', { ''cat'': cat, ''posts'': Post.objects.filter(cat=cat)[:5] })


Para que la etiqueta {{ STATIC_URL }} funcione en sus plantillas, debe representar sus plantillas con RequestContext . Sus vistas genéricas se encargan de esto automáticamente.

Cuando utiliza el render_to_response directo render_to_response en su vista view_cat , debe incluir la instancia de contexto manualmente. Por el momento no está utilizando RequestContext , por lo que la etiqueta {{ static_url }} no funciona. Esto rompe los enlaces a sus hojas de estilo, por lo que no ve el estilo correcto.

A continuación, le mostramos cómo incluir RequestContext en su vista:

return render_to_response(''cats.html'', { ''cat'': cat, ''posts'': Post.objects.filter(cat=cat)[:5] }, context_instance=RequestContext(request))

Alternativamente, si está utilizando Django 1.3 o posterior, puede usar el acceso directo de render lugar:

from django.shortcuts import render ... return render(request, ''cats.html'', { ''cat'': cat, ''posts'': Post.objects.filter(cat=cat)[:5] })