To use Django need to know some basic things.
- What is Django, where you take and how to install?
- How it works Django and how it tested.
- What additional software and settings you should do to work properly.
What is Django, where you take and how to install?
Django is an open source web application framework. It is written in Python.
Django is available open-source under the BSD license and you can get from here.
Installation is simple, download the archive, unpack and execute the command:
1 | python setup.py install |
How it works Django and how it tested.
Django follows the model-template-view architectural pattern.
Django focuses on automating. You can define your data models. Also, you can use Django without a database, because it comes with an object-relational mapper in which you describe your database layout in Python code.
Django has a template system, models system, system for processing requests, automatic admin interface, web templating system and more.
After installing the module can test if the module works. See picture below:
What additional software and settings you should do to work properly.
To work, Django requires Python and Web server. You’ll need also setooptools and flup modules.
The web server can be Apache or Nginx, or other web servers.
Setting up Django with Nginx.
Web server installation and configuration.
Installing Nginx is simple, just download and unpack it on disk. I use version 1.0.5 without any problems taken from here.
The operating system was Windows XP.
After extraction of Nginx, three folders are significant: conf, HTML and logs.
In the HTML folder, we find an index file. I preferred to put here a Django project.
In the conf folder, we find the configuration files. I used the only nginx.conf file.
In the logs folder, we find the data created by the Web server.
Here are the contents of the nginx folder:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | C:\nginx-1.0.5>dir Volume in drive C has no label. Volume Serial Number is 0091-A457 Directory of C:\nginx-1.0.5 07/26/2011 04:16 PM < DIR > . 07/26/2011 04:16 PM < DIR > .. 07/19/2011 05:40 PM < DIR > conf 07/19/2011 05:40 PM < DIR > contrib 07/19/2011 05:40 PM < DIR > docs 07/19/2011 05:40 PM < DIR > html 07/26/2011 04:16 PM < DIR > logs 07/19/2011 05:04 PM 1,445,888 nginx.exe 07/26/2011 04:16 PM < DIR > scgi_temp 07/19/2011 05:40 PM < DIR > temp 07/26/2011 04:16 PM < DIR > uwsgi_temp 1 File(s) 1,445,888 bytes 10 Dir(s) 34,737,188,864 bytes free C:\nginx-1.0.5> |
The commands to use nginx as shown below:
You will use these commands to start, stop and restart nginx web server.
1 2 3 4 | nginx -s stop quick exit nginx -s quit graceful quit nginx -s reload changing configuration, starting a new worker, quitting an old worker gracefully nginx -s reopen reopening log files |
You will use these commands to start, stop and restart nginx web server.
Nginx has only a few command-line parameters.
1 2 3 4 | -c <path_to_config>: the use of specified profile rather than the conf directory nginx.conf. -t: test configuration file is correct, the need to re-load the run-time configuration, this command is very important to detect the revised profile of whether there is a syntax error. -v: show nginx version number. -V: show nginx version of its compiler, as well as environmental information, as well as compile-time parameters. |
The HTML folder has two files: 50x and index.
50x file displays something like this:
1 2 | The page you are looking for is temporarily unavailable. Please try again later. |
Here is the content of nginx.conf my configuration file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | worker_processes 1; pid logs/nginx.pid; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; upstream djangoserv { server 127.0.0.1:8801; } server { listen 80; server_name localhost; server_name localhost; root C:/nginx-1.0.5/html/mysite; location / { # host and port to fastcgi server fastcgi_pass 127.0.0.1:8801; fastcgi_pass_header Authorization; fastcgi_hide_header X-Accel-Redirect; fastcgi_hide_header X-Sendfile; fastcgi_pass_header Authorization; fastcgi_intercept_errors off; fastcgi_param CONTENT_LENGTH $content_length; fastcgi_param CONTENT_TYPE $content_type; fastcgi_param PATH_INFO $fastcgi_script_name; fastcgi_param QUERY_STRING $query_string; fastcgi_param REMOTE_ADDR $remote_addr; fastcgi_param REQUEST_METHOD $request_method; fastcgi_param REQUEST_URI $request_uri; fastcgi_param SERVER_NAME $server_name; fastcgi_param SERVER_PORT $server_port; fastcgi_param SERVER_PROTOCOL $server_protocol; } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } location ~* ^.+\.(jpg|jpeg|gif|png|ico|css|zip|tgz|gz|rar|bz2|doc|xls|exe|pdf|ppt|txt|tar|mid| midi|wav|bmp|rtf|js|mov) { access_log off; expires 30d; } location ~* ^.*\.py$ { if (!-f $request_filename) { return 404; }} } } |
Installing and configuring Django framework.
After I installed Python 2.7 (this version of python I will use in this tutorial).
We will proceed with installing modules in this order: Django, setuptools and flup.
Installation went without any problems in Python 2.7 with the following modules: django – version 1.3.0 , sqlite3, setuptools-0.6c11.win32-py2.7 and flup – version 1.0.2.
Using Django involves creating a project and an application.
Django project is a collection of settings for an instance of Django
Also, Django auto-generate code to create project and applications.
Use the following command to generate the project:
1 | python c:\Python27\Scripts\django-admin.py startproject mysite |
Here in the picture below, the necessary elements:
The Scripts folder path where is django-admin.py, then the option to create a project – startproject and finally the project name – mysite.
This command generates the following files:
1 2 3 4 5 | mysite/ __init__.py manage.py settings.py urls.py |
The official site says that you should put Django-admin.py script in the variable system.
I did but did not work. I had to use way to them when I run.
See, I added the system variable PYTHONPATH, these paths
I executed the following command:
1 | python manage.py runserver 8080 |
Here the picture below that worked well.
I tested to see if I installed python SQLite module.
I modify the settings.py file to work with SQLite and I added a database test.
I run the following command to set and synchronize with the database.
1 | python manage.py syncdb |
This command looks at the INSTALLED_APPS setting and creates any necessary database tables according to the database settings in your settings.py file.
I verified the SQLite to connect to the database.
I create my application, make sure you’re in the mysite directory and type this command:
1 | python manage.py startapp testapp |
This command creates a directory testapp, which is laid out like in the image below.
I added my application in the file settings.py
To invoke the Python shell, use this command:
1 | python manage.py shell |
Next you need to activate the admin site for your installation uncomment the lines from settings.py and urls.py. See image…
Run this command to log in on admin.
1 | python manage.py runserver 127.0.0.1:8080 |
This is the admin web interface. Login with the password and username created in the first part of this tutorial.
After you login you will see the following interface:
You can create another superuser with the command:
1 | python manage.py createsuperuser |
Here is finally content of settings.py configuration file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 | # Django settings for mysite project. DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@example.com'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'C:/nginx-1.0.5/html/mysite/test', # 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 = '' # 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 = 'C:/nginx-1.0.5/html/mysite/static/' # URL prefix for static files. # Example: "http://media.lawrence.com/static/" #STATIC_URL = '/static/' STATIC_URL = 'C:/nginx-1.0.5/html/mysite/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 = 'udtxu^39q!ysdvjqvy)fiefcdzufi$sazef@o3%uk2l1&hiprz' # 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 = ( # 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', 'mysite.testapp', # Uncomment the next line to enable the admin: 'django.contrib.admin', #'django.contrib.auth', # 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. # 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, }, } } |
As you can see we made changes in the settings.py file.
Beware any settings in settings.py, also read the documentation. For example:
“When specifying the path, always use forward slashes, even on Windows.”
There are changes to the static directory, a directory that keeps images and other files.
Run the command shown below:
1 | python manage.py collectstatic |
Finally you see the files copied in the folder. Look …
Otherwise, You can see something like this:
When you run the following command with nginx.conf and setting.py settings presented, you will see that everything works correctly as a web site.
Run the command:
1 | python manage.py runfcgi method=threaded host=127.0.0.1 port=8801 |
You should see something like the image below:
Because we have not created anything in addition, any HTML content. You will see something like at 127.0.0.1:
With this tutorial, I tried to present the main steps for setting up Django with nginx in Windows XP.
Since this tutorial was written experiencing may not be too accurate.
However, this tutorial contains all the information you need to do something functional.