Initial Django commit: basic account, zephyr stream, narrowing, etc.

(imported from commit 3cd40521171a4020c19021eda0d20ee9f802af41)
This commit is contained in:
Jessica McKellar 2012-08-28 12:44:51 -04:00 committed by Tim Abbott
parent ea43d2e40e
commit d90e8f6ec5
14 changed files with 519 additions and 0 deletions

0
humbug/__init__.py Normal file
View File

159
humbug/settings.py Normal file
View File

@ -0,0 +1,159 @@
# Django settings for humbug project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
('Jessica McKellar', 'jessica.mckellar@gmail.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'zephyrdb',
'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.
# In a Windows environment this must be set to 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
# 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 = ''
# 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 = ''
# 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 = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
# 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',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'humbug.urls'
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'humbug.wsgi.application'
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.
'/Users/jesstess/dev/humbug/templates',
)
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',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
'zephyr',
)
# 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,
},
}
}
ACCOUNT_ACTIVATION_DAYS=7
EMAIL_HOST='localhost'
EMAIL_PORT=9991
EMAIL_HOST_USER='username'
EMAIL_HOST_PASSWORD='password'

22
humbug/urls.py Normal file
View File

@ -0,0 +1,22 @@
from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', 'zephyr.views.home', name='home'),
url(r'^update$', 'zephyr.views.update', name='update'),
url(r'^get_updates$', 'zephyr.views.get_updates', name='get_updates'),
url(r'^zephyr/', 'zephyr.views.zephyr', name='zephyr'),
url(r'^accounts/home/', 'zephyr.views.accounts_home', name='accounts_home'),
url(r'^accounts/login/', 'django.contrib.auth.views.login', {'template_name': 'zephyr/login.html'}),
url(r'^accounts/logout/', 'django.contrib.auth.views.logout', {'template_name': 'zephyr/index.html'}),
url(r'^accounts/register/', 'zephyr.views.register', name='register'),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
# url(r'^admin/', include(admin.site.urls)),
)

28
humbug/wsgi.py Normal file
View File

@ -0,0 +1,28 @@
"""
WSGI config for humbug project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setting.
Usually you will have the standard Django WSGI application here, but it also
might make sense to replace the whole Django WSGI application with a custom one
that later delegates to the Django one. For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
framework.
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "humbug.settings")
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
# Apply WSGI middleware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application)

View File

@ -0,0 +1 @@
<a href="/accounts/login/?next=/">login</a> | <a href="/accounts/register/">register</a>

View File

@ -0,0 +1,9 @@
{% autoescape off %}
{% if not user.is_authenticated %}<a href="/accounts/login/?next=/">login</a> | <a
href="/accounts/register/">register</a>{% endif %}
{% if user.is_authenticated %}<a href="/accounts/logout/?next=/">logout</a>{% endif %}
{% block content %}
{% endblock %}
{% endautoescape %}

123
templates/zephyr/index.html Normal file
View File

@ -0,0 +1,123 @@
{% extends "zephyr/base.html" %}
{% block content %}
<h1>Hello {{ user_profile.user.username }}!</h1>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$.ajaxSetup({
beforeSend: function(xhr, settings) {
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
// Only send the token to relative URLs i.e. locally.
xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
}
}
});
$(document).keyup(function(event) {
if (event.keyCode == 38 || event.keyCode == 40) {
p = $("#selected");
tr = $(p).closest("tr");
td = $(p).closest("td");
if (event.keyCode == 40) {
offset = 1;
} else {
offset = -1;
}
new_index = parseInt(tr.attr("id").substr(3), 10) + offset;
if ($("#tr_" + new_index).length > 0) {
new_td = $("#tr_" + new_index).children(".pointer");
new_td.html('<p id="selected">-&gt;</p>');
td.empty();
$.post('update', {pointer: new_td.attr("id")});
if ($(new_td).offset().top < $("#main_div").offset().top) {
$("#main_div").scrollTop($("#main_div").scrollTop() - 75);
}
if ($(new_td).offset().top + $(new_td).height() > $("#main_div").offset().top + $("#main_div").height()) {
$("#main_div").scrollTop($("#main_div").scrollTop() + 75);
}
}
}
});
function narrow(class_name) {
$("span.zephyr_class").each(
function() {
if ($(this).text() != class_name) {
$(this).parents("tr").hide();
}
}
);
}
function unhide() {
$("tr").show();
}
$(function() {
setInterval(get_updates, 1000);
});
function get_updates() {
var pointer = $("tr:last").children("td").first().attr("id");
$.post('get_updates', {pointer: pointer},
function(data) {
$.each(data, function(index, zephyr) {
var new_max_id = parseInt($("tr:last").attr("id").substr(3), 10) + 1;
var new_str = "<tr id=tr_" + new_max_id + "> \
<td class='pointer' id=" + zephyr.id + "><p></p></td> \
<td class='zephyr'> \
<p><span onclick='narrow('" + zephyr.zephyr_class + "')' class='zephyr_class' style='background-color: yellow;'>" + zephyr.zephyr_class + "</span> / " + zephyr.instance + " / " + zephyr.sender + "<br />" +
zephyr.content +
"</p></td> \
</tr>"
$("#table tr:last").after(new_str);
});
}, "json");
}
</script>
<form action="/zephyr/" method="post">
{% csrf_token %}
Class: <input type="text" name="class" id="class" value="" />
Instance: <input type="text" name="instance" id="instance" value="" /><br />
Content: <input type="textarea" rows="4" name="new_zephyr" id="new_zephyr" value="" />
<input type="submit" value="Zephyr" />
</form>
<span id="unhide" style="background-color: aqua;" onclick="unhide()">Unhide</span>
<div id="main_div" style="height: 400px; overflow-y: scroll;">
<table id="table">
{% for zephyr in zephyrs %}
<tr id=tr_{{ forloop.counter }}>
<td class="pointer" id={{ zephyr.id }}>{% if user_profile.pointer == zephyr.id %}<p id="selected">-&gt;{% else %}<p>{% endif %}</p></td>
<td class="zephyr">
<p><span onclick="narrow('{{ zephyr.zephyr_class.name }}')" class="zephyr_class" style="background-color: yellow;">{{ zephyr.zephyr_class.name }}</span> / {{ zephyr.instance }} / {{ zephyr.sender.user.username }}<br />
{{ zephyr.content }}
</p></td>
</tr>
{% endfor %}
</table>
</div>
{% endblock %}

View File

@ -0,0 +1,20 @@
{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}
<form method="post" action="{% url django.contrib.auth.views.login %}?next={{ request.get_full_path }}">
{% csrf_token %}
<table>
<tr>
<td>{{ form.username.label_tag }}</td>
<td>{{ form.username }}</td>
</tr>
<tr>
<td>{{ form.password.label_tag }}</td>
<td>{{ form.password }}</td>
</tr>
</table>
<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

View File

@ -0,0 +1,15 @@
<form method="post" action="{% url register %}">{% csrf_token %}
<table>
<tr>
<td>{{ form.username.label_tag }}</td>
<td>{{ form.username }}</td>
</tr>
<tr>
<td>{{ form.password.label_tag }}</td>
<td>{{ form.password }}</td>
</tr>
</table>
<input type="submit" value="register" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

0
zephyr/__init__.py Normal file
View File

5
zephyr/forms.py Normal file
View File

@ -0,0 +1,5 @@
from django import forms
class RegistrationForm(forms.Form):
username = forms.CharField(max_length=100)
password = forms.CharField(max_length=100)

24
zephyr/models.py Normal file
View File

@ -0,0 +1,24 @@
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
class UserProfile(models.Model):
user = models.OneToOneField(User)
pointer = models.IntegerField()
class ZephyrClass(models.Model):
name = models.CharField(max_length=30)
class Zephyr(models.Model):
sender = models.ForeignKey(UserProfile)
zephyr_class = models.ForeignKey(ZephyrClass)
instance = models.CharField(max_length=30)
content = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def create_user_profile(sender, **kwargs):
"""When creating a new user, make a profile for him or her."""
u = kwargs["instance"]
if not UserProfile.objects.filter(user=u):
UserProfile(user=u, pointer=-1).save()
post_save.connect(create_user_profile, sender=User)

16
zephyr/tests.py Normal file
View File

@ -0,0 +1,16 @@
"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.test import TestCase
class SimpleTest(TestCase):
def test_basic_addition(self):
"""
Tests that 1 + 1 always equals 2.
"""
self.assertEqual(1 + 1, 2)

97
zephyr/views.py Normal file
View File

@ -0,0 +1,97 @@
from django.contrib.auth import authenticate, login
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.shortcuts import render
from django.contrib.auth.models import User
from zephyr.models import Zephyr, UserProfile, ZephyrClass
from zephyr.forms import RegistrationForm
import datetime
import simplejson
def register(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
username = request.POST['username']
password = request.POST['password']
u = User.objects.create_user(username=username, password=password)
u.save()
user = authenticate(username=username, password=password)
login(request, user)
return HttpResponseRedirect(reverse('zephyr.views.home'))
else:
form = RegistrationForm()
return render(request, 'zephyr/register.html', {
'form': form,
})
def accounts_home(request):
return render_to_response('zephyr/accounts_home.html',
context_instance=RequestContext(request))
def home(request):
if not request.user.is_authenticated():
return HttpResponseRedirect('accounts/home/')
zephyrs = Zephyr.objects.all()
user = request.user
user_profile = UserProfile.objects.get(user=user)
if user_profile.pointer == -1:
user_profile.pointer = min([zephyr.id for zephyr in zephyrs])
user_profile.save()
return render_to_response('zephyr/index.html', {'zephyrs': zephyrs, 'user_profile': user_profile},
context_instance=RequestContext(request))
def update(request):
if not request.POST:
# Do something
pass
user = request.user
user_profile = UserProfile.objects.get(user=user)
if request.POST.get('pointer'):
user_profile.pointer = request.POST.get("pointer")
user_profile.save()
return HttpResponse(simplejson.dumps({}), mimetype='application/javascript')
def get_updates(request):
if not request.POST:
# Do something
pass
pointer = request.POST.get('pointer')
new_zephyrs = Zephyr.objects.filter(id__gt=pointer)
new_zephyr_list = []
for zephyr in new_zephyrs:
new_zephyr_list.append({"id": zephyr.id,
"sender": zephyr.sender.user.username,
"zephyr_class": zephyr.zephyr_class.name,
"instance": zephyr.instance,
"content": zephyr.content
})
return HttpResponse(simplejson.dumps(new_zephyr_list),
mimetype='application/javascript')
@login_required
def zephyr(request):
class_name = request.POST['class']
if ZephyrClass.objects.filter(name=class_name):
my_class = ZephyrClass.objects.get(name=class_name)
else:
my_class = ZephyrClass()
my_class.name = class_name
my_class.save()
new_zephyr = Zephyr()
new_zephyr.sender = UserProfile.objects.get(user=request.user)
new_zephyr.content = request.POST['new_zephyr']
new_zephyr.zephyr_class = my_class
new_zephyr.instance = request.POST['instance']
new_zephyr.pub_date = datetime.datetime.utcnow()
new_zephyr.save()
return HttpResponseRedirect(reverse('zephyr.views.home'))