5/23/2013 - 6:59 AM

django virtualenv uwsgi nginx configuration

django virtualenv uwsgi nginx configuration

python use 'except' to catch a exception, print the traceback


import traceback

    1 + 1
    1 + 2

The default time zone is the time zone defined by the TIME_ZONE setting.

The current time zone is the time zone that’s used for rendering.

You should set the current time zone to the end user’s actual time zone with activate(). Otherwise, the default time zone is used.

  • change default time zone

TIME_ZONE in settings.py

Default: 'America/Chicago'

change TIME_ZONE 'Asia/Shanghai' to set GMT+8 time

in your template

{{ each.date|date:"Y年n月j日 G:i" }}

check souce code : django/utils/dateformat.py

  • use tz

      class GMT8(datetime.tzinfo):
           def utcoffset(self, dt):
                 return datetime.timedelta(hours=8)
           def dst(self, dt):
                 return datetime.timedelta(0)
           def tzname(self, dt):
                 return "GMT+8"

Sets the current time zone. The timezone argument must be an instance of a tzinfo subclass or, if pytz is available, a time zone name.

time_str = datetime.datetime.now(GMT8()).strftime('%Y-%m-%d %H:%M:%S')
query something happend before today

    today_min = datetime.datetime.combine(date.today(), datetime.time.min)
    get_meetings = ( Meeting
                    .filter(created_by = user_id.id,
                            meeting_datetime__lt =  today_min
$ cd ~
$ mkdir djanog_test
$ cd djanog_test
$ sudo install -y python-pip python-dev gcc nginx
$ sudo pip install virtualenv
$ virtualenv env 
$ . env/bin/activate
$ pip install django
$ django-admin.py startproject mysite
$ pip install uwsgi

$ cat uwsgi.xml


$ cat /etc/nginx/conf.d/django_test.conf

upstream django {                                                               
server {                                                                        
    listen 80;                                                                  
    server_name your.domain;                                                      
    location / {                                                                
        include uwsgi_params;                                                   
        uwsgi_pass django;                                                      
        uwsgi_param UWSGI_PYHOME /home/your_username/django_test/env;         
        uwsgi_param UWSGI_SCRIPT mysite.wsgi;                                   
        uwsgi_param UWSGI_CHDIR /home/your_username/django_test/mysite;          

$ uwsgi --uid `whoami` -x uwsgi.xml --vhost

My suggestions:

Use django 1.3+ (and ADMIN_MEDIA_PREFIX is deprecated now)

Set both STATIC_URL and STATIC_ROOT in your settings.py

Define just a single static entry in your nginx conf (with trailing slashes). No need for a second one that addresses static/admin/:

location /static/  {
        alias /path/to/static/;
Use collectstatic which should collect admin -> static/admin. It will live under the same location as all the rest of your collected static media.

python manage.py collectstatic
class Applicant(models.Model):

    now = datetime.datetime.now()
    file = models.FileField(verbose_name='简历', upload_to='upload/%s/%s/%s' % (
    # other fields

chdir in uwsgi.ini set current dir, I set it to project dir

in settings.py, 'MEDIA_ROOT'=''

make a directory named upload under project dir

in views.py to handle file upload

from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.core.files.base import ContentFile

def handle_upload(request):
    if request.method == 'GET':
        return render(request, 'page_has_upload_form.html', {})
    if request.method == 'POST':
        o = request.FILES['file']
        filename = o.name           
        otherfield = request.POST.get('otherfield', '')
        data = o.read() # can also read using chunks
        f = ContentFile(data)
        a = Applicant.create(otherfield=otherfield)
        a.file.save(filename, f)
        return HttpResponseRedirect('/') #always using 302 redirect after post

in your template

<form action="" method="post" enctype="multipart/form-data">
    <input type="file" name="file" value="" placeholder="" />    

If you’re getting 413 Request Entity Too Large errors, check your nginx config (server)

client_max_body_size 4M;

python -m trace -t manage.py runserver --noreload 

ues safe

def view(request) :
    msg = '<img src="http://example.com/pretty.jpg" />This picture is very pretty'

and in your template

  {{ msg|safe }}

The context you pass within you view is also available in the templates(parent template) you're extending.

Adding a 'menu_class': 'selected' in the context, you could set

<div id="menu" class="{{ menu_class }}">
in the base template.

###template cache

in settings

    ('django.template.loaders.cached.Loader', (

###django cache

in settings

set cache backends, here use filebased cache, cach_dir should use abs path

    'default': {
        'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
        'LOCATION': cache_dir,

per-site cache

set middleware


add required settings

CACHE_MIDDLEWARE_SECONDS = 3600       #seconds
CACHE_MIDDLEWARE_KEY_PREFIX = 'your_site_name_or_something'

CACHE_MIDDLEWARE_ALIAS : entry of cache above use 'default', see more

per-view cache

from django.views.decorators.cache import cache_control

for example, don't want to use cache on this page

@cache_control(no_cache=True, max_age=0)
def nerver_cache_view(request):

define handler404 in your root URLconf(urls.py) (ROOT_URLCONF in settings)

and in root urs.py:

from django.conf.urls.defaults handler404

handler404 = 'src.main.views.my_custom_404_view'

in views.py

def my_custom_404_view(request):
    return HttpResponseRedirect('/')

src(project) folder, main is app folder

├── __init__.py
├── main
│   ├── admin.py
│   ├── __init__.py
│   ├── models.py
│   ├── templates
│   │   ├── admin
│   │   │   └── base_site.html
│   ├── tests.py
│   ├── urls.py
│   └── views.py
├── manage.py
├── settings
│   ├── debug.py
│   ├── __init__.py
│   ├── production.py
│   └── staging.py
└── urls.py


get_response fucntion:

urlconf = settings.ROOT_URLCONF
resolver = urlresolvers.RegexURLResolver(r'^/', urlconf)


resolve404 function:

 self._urlconf_module = import_module(self.urlconf_name)

 callback = getattr(self.urlconf_module, 'handler%s' % view_type, None)
You need to create your own admin base_site.html template to do this. The easiest way is to create the file:

This should be a copy of http://code.djangoproject.com/svn/django/branches/releases/1.2.X/django/contrib/admin/templates/admin/base_site.html - except putting in your custom title:

{% block branding %}
<h1 id="site-name">{% trans 'my cool admin console' %}</h1>
{% endblock %}
For this to work, you need to have the correct settings for your project, namely in settings.py:

Make sure '/projectdir/templates/' is added as a TEMPLATE_DIR
Make sure 'django.template.loaders.filesystem.Loader' is added as a TEMPLATE_LOADER
See http://docs.djangoproject.com/en/dev/ref/settings/ for more information on settings.py