Django Journal: Override a Django Admin Template, Inline or Otherwise

to override a django admin template for a particular model:

  1. Locate the original template in “your_python_installation/site-packages/django/contrib/admin/templates.” For this tut we’ll assume you’re trying to override change_list.html.
  2. Copy what you need from that template and paste it into a blank .html file. Usually your best bet is to copy all of it and then whittle it down later.
  3. Save the new file into your project’s templates folder, using the following directory structure:
    templates/admin/your_app_name/your_model/change_list.html

The steps are a bit different for an Inline model.

  1. Do steps 1 & 2 above.
  2. Save the file in your templates folder. It doesn’t really matter where it goes, but for consistency’s sake you can place it using a dir structure similar to the above. Take note of the path.
  3. in the Inline class you’re targeting, set template = the path where you placed the file. so your Inline class may look like the following:
    class ImageInline(admin.StackedInline):
        model = ProductImage
        extra = 1
        template = "admin/products/productimage/edit_inline/stacked.html"
    


Robert Martin’s Clean Code series WILL make you the best programmer you can possibly be:
The Clean Coder: A Code of Conduct for Professional Programmers (Robert C. Martin Series)

Django Journal- Apache on Mac OS X does not recognize Aliases!

This one isn’t really django -related, but when doing local development work with django you may have to do some fancy folder aliasing to get your image-uploads working, for example.

Since Apache can’t read an OS X alias file, the solution is to create a symlink.

For some reason I’ve always found symlinks to be a bit tricky. I think they’re kind of finicky, needing to be just so in order to work.

  1. Open Terminal.
  2. cd into the directory where you want to create the alias.
  3. ln -s /Users/USERNAME/dir/to/link/to/ aliasDir

    It’s important that the first argument be an absolute path (i.e., don’t use “~”) and that it have a trailing “/” on the end. HOWEVER, make sure that “aliasDir” doesn’t have a trailing “/”.

  4. Good to go!
  5. Learn UNIX with the excellent Sams series: Sam’s Teach Yourself UNIX in 24 hours

2011 Installation Instructions for Django on Bluehost

Most of this was gleaned from squinting hard at the below:

http://helpdesk.bluehost.com/index.php/kb/article/000531
http://docs.djangoproject.com/en/dev/howto/deployment/fastcgi/#running-django-on-a-shared-hosting-provider-with-apache

But some stuff has changed due to Bluehost’s recent implementation of OpenSSH. So here goes!

This tutorial assumes you already have Python2.6 installed on Bluehost. (This should come with your hosting plan)

First things first– SSH into your account (using Putty, for instance). In order to do this you will have to enable SSH in your cPanel and send identification to Bluehost. Putty will prompt you for your password.

You are now in the home directory. Move into the directory where you would like to install Django from. Despite what the Bluehost instructions say, it doesn’t matter where this is. I just downloaded Django into my home directory.

cd ~
wget http://www.djangoproject.com/download/1.2.4/tarball/
tar xzvf Django-1.2.4.tar.gz
cd Django-1.2.4

Now you can try installing:

python2.6 setup.py install --user

The below may or may not affect anything. Bluehost seems to have disabled the .bashrc in your home directory (not the one in your etc folder, that one is read-only) But go ahead and do it anyway just in case.
—————————————————

Django installs some commands that you can use in your bash shell. To make sure
these work, add the following to the end of your .bashrc file:

export PATH=$HOME/.local/bin:$HOME/.local/usr/bin:$PATH

Log out and log back in to effect this change.

—————————————————

Now you’ll want to confirm that django can run in Python. From the official bluehost instructions:

Testing Your Installation

You can test your installation of Django to see if it worked by starting the
Python interpretor by typing python2.6 at the command prompt and hitting
enter. You’ll get the Python interactive interpretor, where you can type
import django and hit enter. If it gives an error, then there is a problem
with your installation. If no error is given, then you’ve successfully
installed Django to your Python path. Go ahead and exit the Python shell by
typing ctrl+d.

If you were unable to import Django, try re-logging in to your shell, and try
again. If it still doesn’t work, double check to make sure that your Python
path is correct, and that Django really resides in a directory on the Python
Path. To see what this list of directories is, start up the Python interpretor,
and type “import sys; sys.path“, and press enter. This should give you a
list of directories. This should include any directories you listed in your

.bashrc file for PYTHONPATH. Check for any typos in your .bashrc
file. As long as the django directory is in one of those directories
listed, then you should be able to do the import. If it isn’t in any of those
directories, try re-installing Django.

You’ll also want to test the django-admin.py command by trying to run it
from your shell. You should get a usage message with a list of management
commands that can be run. If you get “command not found”, then there was a
problem with the installation of Django
.
This will probably not work. When you call django-admin.py you will have to do it with an absolute path. Something like,

python2.6 ~/.local/bin/django-admin.py

If django-admin.py isn’t in that directory, try re-installing Django.

START THE PROJECT:

Decide where you want to put your django projects. You can put them anywhere, but for security’s sake, they should not be in public_html or any of its subdirectories.

Let’s say you decide on “django_projects”, and you want it to be in your home directory. And let’s say your bluehost username is DJANGONOOB. and let´s say your first project name will be “myFirstProject

cd ~

mkdir django_projects

cd django_projects

initialize your project:

python2.6 /home/DJANGONOOB/.local/bin/django-admin.py startproject myFirstProject

Once the project directory has been created, cd into it

cd myFirstProject

and then follow the tutorial part ONE here:

http://docs.djangoproject.com/en/dev/intro/tutorial01/ BUT keep the following in mind:

When you are creating the database, use sqlite3.

Remember that EVERYWHERE it says python, you must type python2.6 instead.

Everywhere you edit a file, use VIM editor, like so:

vi filename.py

This will bring up the editor. Press i to edit, and escape to exit editing mode.
After pressing escape, type :q! to quit without saving, and :wq to save and quit.

At the end of part one, you will have made a number of modifications. Make sure all your files match up with the below. You will have to change a few paths to make sure this works on Bluehost (changes are highlighted in red below)

settings.py:

# Django settings for testRun project.

DEBUG = True
TEMPLATE_DEBUG = DEBUG

ADMINS = (
    # ('Your Name', 'your_email@domain.com'),
)

MANAGERS = ADMINS

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': '/home/DJANGONOOB/django_projects/testRun/testRunDB', # Absolute 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_ROOT = ''

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = ''

# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
# trailing slash.
# Examples: "http://foo.com/media/", "/media/".
ADMIN_MEDIA_PREFIX = '/media/'

# Make this unique, and don't share it with anybody.
SECRET_KEY = 'a_i1wck_739wiot-ps995ua%g9*)i(z99)-uyz4sc$j3y)1_ja'

# 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 = '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',
    'codePosts',
    # Uncomment the next line to enable the admin:
    'django.contrib.admin',
    # Uncomment the next line to enable admin documentation:
    # 'django.contrib.admindocs',
)

urls.py

from django.conf.urls.defaults import *

# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    # Example:
    # (r'^mysite/', include('mysite.foo.urls')),

    # Uncomment the admin/doc line below to enable admin documentation:
    # (r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    (r'^admin/', include(admin.site.urls)),
    #(r'^polls/$', 'polls.views.index'),
    #(r'^polls/(?P
\d+)/$', 'polls.views.detail'),
    #(r'^polls/(?P
\d+)/results/$', 'polls.views.results'),
    #(r'^polls/(?P
\d+)/vote/$', 'polls.views.vote')
)

Now for the big guns. Obviously you won’t be able to run all this on your browser as if you are running all this from an installation on your home computer.
It’s a server for god’s sake. So you’ll have to get into some fun redirecting.

Decide where you want the project to be in your viewable directory structure. So, say you want your project to be accessible from:

http://djangoNoob.com/django/testProject

then you would go

mkdir ~/public_html/django/testProject

cd ~/public_html/django/testProject

and now you’ll have to make a Fast CGI file to run your django site.

vim mySite.fcgi

copy and paste the following:

#!/usr/bin/python2.6
import sys, os

# Add a custom Python path.
sys.path.insert(0, "/home/DJANGONOOB/.local/lib/python2.6")
sys.path.insert(13, "/home/DJANGONOOB/django_projects/myFirstProject")

# Switch to the directory of your project. (Optional.)
# os.chdir("/home/DJANGONOOB/django_projects/myFirstProject")

# Set the DJANGO_SETTINGS_MODULE environment variable.
os.environ['DJANGO_SETTINGS_MODULE'] = "settings"

from django.core.servers.fastcgi import runfastcgi
runfastcgi(method="threaded", daemonize="false")

remember to :wq to save.

you must create an .htaccess to make sure mySite.fcgi is run when you pull this up in the browser:

vi .htaccess

copy and paste the below:

AddHandler fcgid-script .fcgi
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ mysite.fcgi/$1 [QSA,L]

now set the correct permissions for mySite.fcgi

chmod 0755 mySite.fcgi

now just pull up http://djangoNoob.com/django/testProject/admin/

and you should see the Django administration console!

Finally, I’m sure to have missed something. I tried I really did but I am trying to document 24 hours of jiggering here… so if it doesnt work for you please pipe up in the comments and I will help figure it out!
——————

If you are interested in finding good django hosting, take a look at Webfaction. They are a one-click setup django hosting provider, and offer a lot of other really good features for advanced users.

Get Adobe Flash player