Skip to content

Instantly share code, notes, and snippets.

@opie4624
Created December 19, 2008 01:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save opie4624/37747 to your computer and use it in GitHub Desktop.
Save opie4624/37747 to your computer and use it in GitHub Desktop.
Working through the "Practical Django Projects" book from Apress
External Packages/Sources
Tagging http://code.google.com/p/django-tagging/
Markdown https://sf.net/projects/python-markdown/
pydelicious http://code.google.com/p/pydelicious/
from django.contrib import admin
from cms.search.models import SearchKeyword
from django.contrib.flatpages.models import FlatPage
from django.contrib.flatpages.admin import FlatPageAdmin
class SearchKeywordInline(admin.StackedInline):
model = SearchKeyword
class FlatPageAdmin(FlatPageAdmin):
inlines = [
SearchKeywordInline,
]
#admin.site.register(SearchKeyword)
admin.site.unregister(FlatPage)
admin.site.register(FlatPage, FlatPageAdmin)
from django.contrib import admin
from coltrane.models import *
class CategoryAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": ("title",)}
class EntryAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": ("title",)}
class LinkAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": ("title",)}
admin.site.register(Category, CategoryAdmin)
admin.site.register(Entry, EntryAdmin)
admin.site.register(Link, LinkAdmin)
{% extends "admin/change_form.html" %}
{% load i18n admin_modify adminmedia %}
{% block extrahead %}{{ block.super }}
<script type="text/javascript" src="../../../jsi18n/"></script>
<script type="text/javascript" src="/tiny_mce/tiny_mce.js"></script>
<script type="text/javascript">
tinyMCE.init({
mode: "textareas",
theme: "simple"
});
</script>
{{ media }}
{% endblock %}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>{{ flatpage.title }}</title>
</head>
<body>
<h1>{{ flatpage.title }}</h1>
{{ flatpage.content }}
<form action="/search/" method="get" accept-charset="utf-8">
<p>
<label for="id_q">Search:</label><input type="text" name="q" value="" id="id_q">
<input type="submit" value="Submit">
</p>
</form>
</body>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Latest Entries</title>
</head>
<body>
<h1>Latest Entries</h1>
{% for object in latest %}
<h2>{{ object.title }}</h2>
<p>Published on {{ object.pub_date|date:"F j, Y" }}</p>
{% if object.excerpt_html %}
{{ object.excerpt_html|safe }}
{% else %}
{{ object.body_html|truncatewords_html:"50"|safe }}
{% endif %}
<p><a href="{{ object.get_absolute_url }}">Read full entry</a></p>
{% endfor %}
</body>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Entries for {{ day|date:"F j, Y" }}</title>
</head>
<body>
<h1>Entries for {{ day|date:"F j, Y" }}</h1>
{% for object in object_list %}
<h2>{{ object.title }}</h2>
<p>Published on {{ object.pub_date|date:"F j, Y" }}</p>
{% if object.excerpt_html %}
{{ object.excerpt_html|safe }}
{% else %}
{{ object.body_html|truncatewords_html:"50"|safe }}
{% endif %}
<p><a href="{{ object.get_absolute_url }}">Read full entry</a></p>
{% endfor %}
</body>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Entries for {{ month|date:"F, Y" }}</title>
</head>
<body>
<h1>Entries for {{ month|date:"F, Y" }}</h1>
{% for object in object_list %}
<h2>{{ object.title }}</h2>
<p>Published on {{ object.pub_date|date:"F j, Y" }}</p>
{% if object.excerpt_html %}
{{ object.excerpt_html|safe }}
{% else %}
{{ object.body_html|truncatewords_html:"50"|safe }}
{% endif %}
<p><a href="{{ object.get_absolute_url }}">Read full entry</a></p>
{% endfor %}
</body>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Month index</title>
</head>
<body>
<h1>Month index</h1>
<ul>
{% for month in date_list %}
<li><a href='{{ month|date:"b" }}'>{{ month|date:"F" }}</a></li>
{% endfor %}
</ul>
</body>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>{{ object.title }}</title>
</head>
<body>
<h1>{{ object.title }}</h1>
{{ object.body_html|safe }}
</body>
</html>
#!/usr/bin/env python
from django.core.management import execute_manager
try:
import settings # Assumed to be in the same directory.
except ImportError:
import sys
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__)
sys.exit(1)
if __name__ == "__main__":
execute_manager(settings)
from django.db import models
from django.contrib.flatpages.models import FlatPage
class SearchKeyword(models.Model):
keyword = models.CharField(max_length=50)
page = models.ForeignKey(FlatPage)
def __unicode__(self):
return self.keyword
import datetime
from django.db import models
from django.contrib.auth.models import User
from tagging.fields import TagField
from markdown import markdown
class Category(models.Model):
title = models.CharField(max_length=250, help_text='Maximum 250 characters.')
slug = models.SlugField(unique=True, help_text='Suggested value automatically generated from title. Must be unique.')
description = models.TextField()
class Meta:
verbose_name_plural = "Categories"
ordering = ['title']
def __unicode__(self):
return self.title
def get_absolute_url(self):
return "/categories/%s/" % self.slug
class Entry(models.Model):
LIVE_STATUS = 1
DRAFT_STATUS = 2
HIDDEN_STATUS = 3
STATUS_CHOICES = (
(LIVE_STATUS, 'Live'),
(DRAFT_STATUS, 'Draft'),
(HIDDEN_STATUS, 'Hidden'),
)
# Core Fields
title = models.CharField(max_length=250, help_text="Maximum 250 characters.")
excerpt = models.TextField(blank=True, help_text="A short summary of the entry. Optional.")
body = models.TextField()
pub_date = models.DateTimeField(default=datetime.datetime.now)
# Fields to store generated HTML
excerpt_html = models.TextField(editable=False, blank=True)
body_html = models.TextField(editable=False, blank=True)
# Metadata
slug = models.SlugField(unique_for_date='pub_date', help_text="Suggested value automatically generated from title.")
author = models.ForeignKey(User)
enable_comments = models.BooleanField(default=True)
featured = models.BooleanField(default=False)
status = models.IntegerField(choices=STATUS_CHOICES, default=1, help_text="Only entries with 'Live' status will be publicly displayed.")
# Categorization
categories = models.ManyToManyField(Category)
tags = TagField(help_text="Separate tags with spaces.")
class Meta:
verbose_name_plural = "Entries"
ordering = ['-pub_date']
def __unicode__(self):
return self.title
def save(self):
self.body_html = markdown(self.body)
if self.excerpt:
self.excerpt_html = markdown(self.excerpt)
super(Entry, self).save()
def get_absolute_url(self):
return ('coltrane_entry_detail', (), {'year': self.pub_date.strftime("%Y"),
'month': self.pub_date.strftime("%b"),
'day': self.pub_date.strftime("%d"),
'slug': self.slug})
get_absolute_url = models.permalink(get_absolute_url)
class Link(models.Model):
title = models.CharField(max_length=250)
description = models.TextField(blank=True)
description_html = models.TextField(blank=True)
url = models.URLField(unique=True)
posted_by = models.ForeignKey(User)
pub_date = models.DateTimeField(default=datetime.datetime.now)
slug = models.SlugField(unique_for_date='pub_date')
tags = TagField()
enable_comments = models.BooleanField(default=True)
post_elsewhere = models.BooleanField('Post to del.icio.us', default=True)
via_name = models.CharField('Via', max_length=250, blank=True, help_text='Site where the link was spotted. Optional.')
via_url = models.URLField('Via URL', blank=True, help_text='The URL of the site where link was spotted. Optional.')
class Meta:
ordering = ['-pub_date']
def __unicode__(self):
return self.title
def save(self):
if self.description:
self.description_html = markdown(self.description)
super(Link, self).save()
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Search</title>
</head>
<body>
<form action="/search/" method="get" accept-charset="utf-8">
<p><label for="id_q">Search:</label><input type="text" name="q" value="{{ query }}" id="id_q"></p>
<p><input type="submit" value="Submit"></p>
</form>
{% if keyword_results or results %}
<p>You searched for "{{ query }}".</p>
{% if keyword_results %}
<p>Recommended pages:</p>
<ul>
{% for page in keyword_results %}
<li><a href="{{ page.get_absolute_url }}">{{ page.title }}</a></li>
{% endfor %}
</ul>
{% endif %}
{% if results %}
<p>Search results:</p>
<ul>
{% for page in results %}
<li><a href="{{ page.get_absolute_url }}">{{ page.title }}</a></li>
{% endfor %}
</ul>
{% endif %}
{% endif %}
{% if query and not keyword_results and not results %}
<p>No results found.</p>
{% else %}
<p>Type a search query into the box above, and press "Submit" to search.</p>
{% endif %}
</body>
</html>
from os.path import expanduser
# Django settings for cms project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
('Andrew Kraut', 'akraut@gmail.com'),
)
MANAGERS = ADMINS
DATABASE_ENGINE = 'sqlite3' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
DATABASE_NAME = expanduser('~/Code/djangoprojects/cms/cms.db') # Or path to database file if using sqlite3.
DATABASE_USER = '' # Not used with sqlite3.
DATABASE_PASSWORD = '' # Not used with sqlite3.
DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3.
DATABASE_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.
# 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
# Absolute path to the directory that holds media.
# 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 = '!hnt#_dh*m5p*nsvx(1!z5&jqjb^m1ggsk=gtu3!=#g#m-24%f'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.load_template_source',
'django.template.loaders.app_directories.load_template_source',
# 'django.template.loaders.eggs.load_template_source',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',
)
ROOT_URLCONF = 'cms.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.
expanduser('~/Code/djangoprojects/templates/cms')
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'django.contrib.flatpages',
'cms.search',
'coltrane',
'tagging',
)
from os.path import expanduser
from django.conf.urls.defaults import *
from coltrane.models import Entry
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Example:
# (r'^cms/', include('cms.foo.urls')),
# Uncomment the admin/doc line below and add 'django.contrib.admindocs'
# to INSTALLED_APPS to enable admin documentation:
(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
(r'^admin/(.*)', admin.site.root),
(r'^tiny_mce/(?P<path>.*)$', 'django.views.static.serve',
{ 'document_root': expanduser('~/Code/tinymce/jscripts/tiny_mce') },
),
(r'^search/$', 'cms.search.views.search'),
(r'^weblog/', include('coltrane.urls')),
(r'', include('django.contrib.flatpages.urls')),
)
from django.conf.urls.defaults import *
from coltrane.models import Entry
entry_info_dict = {
'queryset': Entry.objects.all(),
'date_field': 'pub_date',
}
urlpatterns = patterns('django.views.generic.date_based',
(r'^$', 'archive_index', entry_info_dict, 'coltrane_entry_archive_index'),
(r'^(?P<year>\d{4})/$', 'archive_year', entry_info_dict, 'coltrane_entry_archive_year'),
(r'^(?P<year>\d{4})/(?P<month>\w{3})/$', 'archive_month', entry_info_dict, 'coltrane_entry_archive_month'),
(r'^(?P<year>\d{4})/(?P<month>\w{3})/(?P<day>\d{2})/$', 'archive_day', entry_info_dict, 'coltrane_entry_archive_day'),
(r'^(?P<year>\d{4})/(?P<month>\w{3})/(?P<day>\d{2})/(?P<slug>[-\w]+)/$', 'object_detail', entry_info_dict, 'coltrane_entry_detail'),
)
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.contrib.flatpages.models import FlatPage
def search(request):
query = request.GET.get('q', '')
keyword_results = results = []
if query:
keyword_results = FlatPage.objects.filter(searchkeyword__keyword__in=query.split()).distinct()
if keyword_results.count() == 1:
return HttpResponseRedirect(keyword_results[0].get_absolute_url())
results = FlatPage.objects.filter(content__icontains=query)
return render_to_response('search/search.html',
{ 'query': query,
'keyword_results': keyword_results,
'results': results })
from django.shortcuts import get_object_or_404, render_to_response
from coltrane.models import Entry
def entries_index(request):
return render_to_response('coltrane/entry_index.html', { 'entry_list': Entry.objects.all() })
def entry_detail(request, year, month, day, slug):
import datetime, time
date_stamp = time.strptime(year+month+day, "%Y%b%d")
pub_date = datetime.date(*date_stamp[:3])
entry = get_object_or_404(Entry, pub_date__year=pub_date.year,
pub_date__month=pub_date.month,
pub_date__day=pub_date.day,
slug=slug)
return render_to_response('coltrane/entry_detail.html', { 'entry': entry })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment