settings.py
最终效果如图
一.context_processors.py
Django因此提供对全局 context处理器的支持。TEMPLATE_CONTEXT_PROCESSORS指定了总是使用哪些contextprocessors。这样就省去了每次使用RequestContext都指定processors的麻烦
from demo.apps.home.models import userProfile import django def user_image(request): try: imagen = None user = request.user up = userProfile.objects.get(user=user) imagen = "/media/%s"%up.photo except: imagen = "/media/images/user.jpg" return imagen def my_processor(request): context = {"django_version":django.get_version(), "get_image_profile":user_image(request), } return context
二.base.html
<!DOCTYPE html> <html lang="es"> <head> <meta charset="utf-8"> <title>Proyecto Demo</title> <!-- Le styles --> <link href="/media/bootstrap/css/bootstrap.css" rel="stylesheet"> <link href="/media/bootstrap/css/bootstrap-responsive.css" rel="stylesheet"> <script src="/media/js/jquery.js"></script> <script src="/media/bootstrap/js/bootstrap.js"></script> <style type="text/css"> body { padding-top: 60px; padding-bottom: 40px; } .sidebar-nav { padding: 9px 0; } </style> <script type="text/javascript"> $(document).on('ready',function(){ $.ajax({ type:"GET", contentType:"application/json; charset=utf-8", dateType:"json", url:"/ws/productos/", success:function(response){ var i = (response.length-1)-2; for(i;i<=(response.length-1);i++){ $('#ProductosNuevos').append("<li>"+response[i].fields.nombre+"</li>"); } } }); }); </script> </head> <body> <div class="navbar navbar-inverse navbar-fixed-top"> <div class="navbar-inner"> <div class="container-fluid"> <a class="brand" href="{% url "vista_principal" %}">Proyecto Ventas </a> {% if user.is_authenticated %} <p class="navbar-text pull-right"> Logged in as {{ user.username }} </p> {% endif %} <ul class="nav"> <li><a href="/productos/page/1/">Productos</a></li> <li><a href="{% url "vista_contacto" %}">Contacto</a></li> <li><a href="{% url "vista_about" %}">Acerca de ...</a></li> {% if user.is_authenticated %} <li><a href="{% url "vista_logout" %}"> Cerrar Sesion </a></li> {% else %} <li><a href="{% url "vista_login" %}"> Login </a></li> {% endif %} </div> </div> </div> <div class="container-fluid"> <div class="row-fluid"> <div class="span9"> <div class="hero-unit"> {% block content %} {% endblock%} </div> </div><!--/span--> <div class="span3"> <div class="well sidebar-nav"> <ul class="nav nav-list"> <li class="nav-header">Mi perfil</li> <br><p align="justify"> {%if user.is_authenticated %} <p>Bienvenido {{ user }} </p> <img src="{{get_image_profile}}" width="50px" heigth="50px"/> {% else %} <a href="/login/" class="btn btn-primary">Login<a> {% endif %} </p> </ul> </div><!--/.well --> <div class="well sidebar-nav"> <ul class="nav nav-list"> <li class="nav-header">Mi Carrito</li> <br><p align="justify"> Carrito de Super </p> </ul> </div><!--/.well --> <div class="well sidebar-nav"> <ul class="nav nav-list" id="ProductosNuevos"> <li class="nav-header">Nuevos Productos</li> </ul> </div><!--/.well --> <img src="/media/images/django.gif"/> </div><!--/span--> </div><!--/row--> <hr> <footer> <p>© Open Project 2013. Versión Django: {{django_version}}</p> </footer> </div><!--/.fluid-container--> <!-- Le javascript ================================================== --> <!-- Placed at the end of the document so the pages load faster --> </body> </html>
三.settings.py
# Django settings for demo project. import os DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', '[email protected]'), ) MANAGERS = ADMINS MOTOR_DB = 'sqlite' # Configuracion del motor principal de nuestro proyecto. if MOTOR_DB == 'mysql': DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'demo', # Or path to database file if using sqlite3. 'USER': 'root', # Not used with sqlite3. 'PASSWORD': 'root', # 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. } } if MOTOR_DB == 'sqlite': DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': os.path.join(os.path.dirname(__file__),'demo.db'), # Or path to database file if using sqlite3. 'USER': 'root', # Not used with sqlite3. 'PASSWORD': 'root', # 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/Merida' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'es-MX' 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.normpath(os.path.join(os.path.dirname(__file__),'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 = '' # 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 = '(hd2u539_pwq2l7q+on-&c=qkewn78ukjm68*mp@rq(g(2eah!' # 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.contrib.auth.context_processors.auth", "django.core.context_processors.debug", "django.core.context_processors.i18n", "django.core.context_processors.media", "django.core.context_processors.static", "django.core.context_processors.tz", "django.contrib.messages.context_processors.messages", "demo.apps.context_processors.my_processor", ) 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 = 'demo.urls' #Identificar o definir el perfil de los usuarios AUTH_PROFILE_MODULE = 'home.userProfile' # Python dotted path to the WSGI application used by Django's runserver. WSGI_APPLICATION = 'demo.wsgi.application' TEMPLATE_DIRS = ( os.path.join(os.path.dirname(__file__),'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', 'demo.apps.ventas', 'demo.apps.home', 'demo.apps.webServices.wsProductos', # 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, }, } } # Configuracion del correo EMAIL_HOST = "smtp.gmail.com" EMAIL_PORT = 587 EMAIL_HOST_USER = '[email protected]' EMAIL_HOST_PASSWORD = '*****' EMAIL_USE_TLS = True