Commit 92a31098 authored by fred's avatar fred

initial models and views (emission, episode, diffusion)

parents
*.pyc
/static
panikdb.sqlite3
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "panikdb.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
from django.contrib import admin
from .models import Emission, Episode
class EmissionAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('title',)}
admin.site.register(Emission, EmissionAdmin)
class EpisodeAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('title',)}
admin.site.register(Episode, EpisodeAdmin)
import datetime
import re
import unicodedata
from django import forms
from django.forms import fields
from .models import Emission, Episode, Diffusion
def slugify(s):
s = unicodedata.normalize('NFKD', s).encode('ascii', 'ignore').lower()
return re.sub(r'\W+', '-', s)
class DayAndHourWidget(forms.MultiWidget):
def __init__(self, attrs=None):
WEEKDAYS = [u'Lundi', u'Mardi', u'Mercredi', u'Jeudi', u'Vendredi', u'Samedi', u'Dimanche']
widgets = (
forms.Select(attrs=attrs, choices=([(weekday, WEEKDAYS[weekday]) for weekday in range(7)])),
forms.Select(attrs=attrs, choices=([(hour, hour) for hour in range(24)])),
forms.Select(attrs=attrs, choices=([(minute, str(minute).zfill(2)) for minute in range(60)])),
)
super(DayAndHourWidget, self).__init__(widgets, attrs)
def decompress(self, value):
print 'decompress', value
if value:
return [value.weekday(), value.hour, value.minute]
return [None, None, None]
def value_from_datadict(self, data, files, name):
# we only care about day/hour/minutes, but we conveniently use a
# datetime value to store that; we pick 2007 as reference year as
# it had its January 1st on a Monday.
data_list = [
widget.value_from_datadict(data, files, name + '_%s' % i)
for i, widget in enumerate(self.widgets)]
if data_list:
return datetime.datetime(2007, 1, int(data_list[0])+1, int(data_list[1]), int(data_list[2]))
return None
class EmissionForm(forms.ModelForm):
class Meta:
model = Emission
exclude = ('slug',)
widgets = {
'first_diffusion': DayAndHourWidget(),
}
def save(self, commit=True):
if not self.instance.slug:
self.instance.slug = slugify(self.instance.title)
return super(EmissionForm, self).save(commit=commit)
class EpisodeForm(forms.ModelForm):
class Meta:
model = Episode
exclude = ('slug',)
widgets = {'emission': forms.HiddenInput()}
class EpisodeNewForm(EpisodeForm):
diffusion = forms.DateTimeField()
def save(self, commit=True):
episode = super(EpisodeNewForm, self).save(commit=commit)
diffusion = Diffusion()
diffusion.episode_id = episode.id
diffusion.datetime = self.cleaned_data.get('diffusion')
diffusion.save()
return episode
from datetime import datetime
from django.forms import fields
from django.core.urlresolvers import reverse
from django.db import models
class Emission(models.Model):
title = models.CharField(max_length=50)
slug = models.SlugField()
description = models.TextField()
first_diffusion = models.DateTimeField()
# other_diffusions =
def __unicode__(self):
return self.title
class Episode(models.Model):
emission = models.ForeignKey('Emission', verbose_name=u'Emission')
title = models.CharField(max_length=50)
slug = models.SlugField()
description = models.TextField()
def __unicode__(self):
return self.title
def get_absolute_url(self):
return reverse('episode-view',
kwargs={'emission_id': str(self.emission.id),
'pk': str(self.id)})
class Diffusion(models.Model):
episode = models.ForeignKey('Episode', verbose_name=u'Episode')
datetime = models.DateTimeField()
{% extends "panikdb/base.html" %}
{% block content %}
<h2>{{ emission.title }}</h2>
{% if emission.description %}
<p>
{{ emission.description }}
</p>
{% endif %}
<h3>Épisodes</h3>
<ul>
{% for episode in episodes %}
<li><a href="{{ episode.id }}/">{{ episode.title }}</a></li>
{% endfor %}
</ul>
<a href="add">New Episode</a> - <a href="edit/">Edit</a>
{% endblock %}
{% extends "panikdb/base.html" %}
{% block content %}
<form method="post">
<div id="form-content">
{% csrf_token %}
{{ form.as_p }}
</div>
{% block buttons %}
<button class="enable-on-change">Modifier</button>
{% endblock %}
</form>
{% endblock %}
{% extends "panikdb/base.html" %}
{% block content %}
<ul>
{% for emission in object_list %}
<li><a href="{{ emission.id }}/">{{ emission.title }}</a></li>
{% endfor %}
</ul>
<a href="add">New</a>
{% endblock %}
{% extends "panikdb/base.html" %}
{% block content %}
<h2>{{ episode.emission.title }} — {{ episode.title }}</h2>
{% if episode.description %}
<p>
{{ episode.description }}
</p>
{% endif %}
<h3>Diffusions</h3>
<ul>
{% for diffusion in diffusions %}
<li>{{ diffusion.datetime }}</li>
{% endfor %}
</ul>
<a href="edit/">Edit</a>
{% endblock %}
{% extends "panikdb/base.html" %}
{% block content %}
<h2>Nouvel épisode de « {{ emission.title }} »</h2>
<form method="post">
<div id="form-content">
{% csrf_token %}
<input type="hidden" name="id_emission" value="{{ emission.id }}"/>
{{ form.as_p }}
</div>
{% block buttons %}
<button class="enable-on-change">Modifier</button>
{% endblock %}
</form>
{% endblock %}
"""
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)
from django.conf.urls import patterns, url
from .views import *
urlpatterns = patterns('',
url(r'^$', EmissionListView.as_view(), name='emission-list'),
url(r'^add$', EmissionCreateView.as_view(), name='emission-add'),
url(r'^(?P<pk>\d+)/$', EmissionDetailView.as_view(), name='emission-view'),
url(r'^(?P<pk>\d+)/edit/$', EmissionUpdateView.as_view(), name='emission-update'),
url(r'^(?P<pk>\d+)/delete/$', EmissionDeleteView.as_view(), name='emission-delete'),
url(r'^(?P<emission_id>\d+)/add$', EpisodeCreateView.as_view(), name='episode-add'),
url(r'^(?P<emission_id>\d+)/(?P<pk>\d+)/$', EpisodeDetailView.as_view(), name='episode-view'),
url(r'^(?P<emission_id>\d+)/(?P<pk>\d+)/edit/$', EpisodeUpdateView.as_view(), name='episode-update'),
url(r'^(?P<emission_id>\d+)/(?P<pk>\d+)/delete/$', EpisodeDeleteView.as_view(), name='episode-delete'),
)
from django.core.urlresolvers import reverse_lazy
from django.views.generic.base import TemplateView
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
from .models import Emission, Episode, Diffusion
from .forms import EmissionForm, EpisodeForm, EpisodeNewForm
__all__ = ['EmissionListView', 'EmissionDetailView', 'EmissionCreateView',
'EmissionUpdateView', 'EmissionDeleteView',
'EpisodeCreateView', 'EpisodeDetailView', 'EpisodeUpdateView',
'EpisodeDeleteView']
class EmissionListView(ListView):
model = Emission
class EmissionDetailView(DetailView):
model = Emission
def get_context_data(self, **kwargs):
context = super(EmissionDetailView, self).get_context_data(**kwargs)
context['episodes'] = Episode.objects.filter(emission=self.object.id)
return context
class EmissionCreateView(CreateView):
form_class = EmissionForm
model = Emission
success_url = reverse_lazy('emission-list')
class EmissionUpdateView(UpdateView):
form_class = EmissionForm
model = Emission
class EmissionDeleteView(DeleteView):
model = Emission
class EpisodeCreateView(CreateView):
model = Episode
form_class = EpisodeNewForm
def get_initial(self):
initial = super(EpisodeCreateView, self).get_initial()
initial['emission'] = self.kwargs.get('emission_id')
return initial
def get_context_data(self, **kwargs):
context = super(EpisodeCreateView, self).get_context_data(**kwargs)
context['emission'] = Emission.objects.get(id=self.kwargs.get('emission_id'))
return context
class EpisodeDetailView(DetailView):
model = Episode
def get_context_data(self, **kwargs):
context = super(EpisodeDetailView, self).get_context_data(**kwargs)
context['diffusions'] = Diffusion.objects.filter(episode=self.object.id)
return context
class EpisodeUpdateView(UpdateView):
form_class = EpisodeForm
model = Episode
class EpisodeDeleteView(DeleteView):
model = Episode
# Django settings for panikdb project.
import os
DEBUG = True
TEMPLATE_DEBUG = DEBUG
PROJECT_PATH = os.path.dirname(os.path.dirname(__file__))
ADMINS = (
('Frederic Peters', 'fred@radiopanik.org'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(PROJECT_PATH, 'panikdb.sqlite3'),
}
}
# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts
ALLOWED_HOSTS = []
# 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 = 'Europe/Brussels'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'fr-be'
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: "/var/www/example.com/media/"
MEDIA_ROOT = os.path.join(PROJECT_PATH, 'media')
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://example.com/media/", "http://media.example.com/"
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: "/var/www/example.com/static/"
STATIC_ROOT = os.path.join(PROJECT_PATH, 'static')
# URL prefix for static files.
# Example: "http://example.com/static/", "http://static.example.com/"
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.
os.path.join(PROJECT_PATH, 'panikdb', 'static'),
)
# 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 = '(jwx-1y#d#vps93glikirr&tq_!^_4g+9-qj(jy#l=sllqw(^j'
# 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 = 'panikdb.urls'
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'panikdb.wsgi.application'
TEMPLATE_DIRS = (
os.path.join(PROJECT_PATH, 'panikdb', 'templates'),
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'panikdb.emissions',
)
# 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,
},
}
}
try:
from local_settings import *
except ImportError:
pass
This source diff could not be displayed because it is too large. You can view the blob instead.
/* theme derived and inspired by TerraFirma
* <http://www.oswd.org/design/information/id/3557/>
*/
@font-face {
font-family: "FontAwesome";
src: url('fontawesome-webfont.eot');
src: url('fontawesome-webfont.eot?#iefix') format('eot'), url('fontawesome-webfont.woff') format('woff'), url('fontawesome-webfont.ttf') format('truetype'), url('fontawesome-webfont.svg#FontAwesome') format('svg');
font-weight: normal;
font-style: normal;
}
html, body {
margin: 0;
font-family: sans-serif;
}
html {
background: #F9F9F7 url(../images/a1.gif) repeat-x;
color: #8c8c73;
}
a {
color: #FF7800;
text-decoration: underline;
transition: all .2s ease-in-out;
-webkit-transition: all .2s ease-in-out;
-moz-transition: all .2s ease-in-out;
}
a:hover {
text-decoration: none;
color: #D76500;
}
div#user-links {
display: inline;
padding: 5px;
background: rgba(100, 100, 100, 0.8);
border-top-right-radius: 6px;
border-bottom-left-radius: 6px;
}
div#user-links a {
color: white;
text-decoration: none;
}
div#user-links a:hover {
text-shadow: 1px 1px 1px black;
}
div#wrap {
background: white;
margin: 3em auto;
margin-bottom: 0;
padding: 15px;
border-radius: 6px;
-moz-border-radius: 6px;
-webkit-border-radius:6px;
box-shadow: 0 0 4px rgba(0,0,0,0.75);
-moz-box-shadow: 0 0 4px rgba(0,0,0,0.75);
-webkit-box-shadow: 0 0 4px rgba(0,0,0,0.75);
position: relative;
width: 90%;
}
#header
{
position: absolute;
background: #FF7800 url(../images/a8.gif) repeat-x;
border-radius: 6px 0 0 6px;
-moz-border-radius: 6px 0 0 6px;
-webkit-border-radius: 6px 0 0 6px;
width: 212px;
width: 212px;
height: 92px;
color: #fff;
padding-left: 10px;
z-index: 14;
}
#header h1
{
font-size: 23px;
letter-spacing: -1px;
padding-top: 30px;
margin: 0;
}
#header span
{
margin: 0;
font-size: 10px;
font-weight: normal;
color: #FCE2CA;
}
#header h1 a,
#header span a {
color: white;
text-decoration: none;
}
#splash
{
position: absolute;
right: 15px;
background: #282f2e url(../images/banner-1054.png) no-repeat 0px top;
width: 90%;
height: 87px;
border-radius: 0 6px 6px 0;
-moz-border-radius: 0 6px 6px 0;
-webkit-border-radius: 0 6px 6px 0;
z-index: 10;
color: white;
font-weight: bold;
text-align: right;
padding-top: 5px;
}
div#content {
margin: 1em 1ex;
margin-top: 100px;
padding: 7px;
position: relative;
}
div#content h2 {
margin-top: 0;
font-weight: normal;
color: #656551;
font-size: 18px;
letter-spacing: -1px;
line-height: 25px;
margin-bottom: 20px;
padding: 0 0 10px 15px;
position: relative;
top: 4px;
background: url(../images/a22.gif) bottom repeat-x;
}
div#content ul {
line-height: 1.5em;
}
#footer
{
font-size: 70%;
position: relative;
clear: both;
height: 66px;
text-align: center;
line-height: 66px;
background-image: url(../images/a50.gif);
color: #A8A88D;
}
#footer a
{
color: #8C8C73;
}
form#login-form p {
float: left;
width: 40%;
}
form input.submit {
float: right;
width: 18%;
margin-top: 30px;
}
div.login-actions {
clear: both;
padding-top: 2em;
}
div.login-actions p {
margin: 0;
}
form p {
margin: 0 0 1em 0;
}
form.inline p label {
display: inline;
}
form .inline label {
display: inline;
}
form .inline li {
display: inline;
}
form p label {
display: block;
}
form p input,
form p textarea {
margin-left: 10px;
}