<repo_name>cambieri/ironika-calosso<file_sep>/fab_deploy.sh
source /home/workspace-django/virtualenvs/ironika-calosso/bin/activate
cd /home/workspace-django/projects/ironika-calosso/calosso/
fab live prepare_deploy
fab live deploy
deactivate
<file_sep>/calosso/apps/main/migrations/0005_auto__add_field_galleria_homepage.py
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models

class Migration(SchemaMigration):

    def forwards(self, orm):
        
        # Adding field 'Galleria.homepage'
        db.add_column(u'main_galleria', 'homepage', self.gf('django.db.models.fields.related.ForeignKey')(default=1, to=orm['main.Homepage']), keep_default=False)


    def backwards(self, orm):
        
        # Deleting field 'Galleria.homepage'
        db.delete_column(u'main_galleria', 'homepage_id')


    models = {
        u'main.articolo': {
            'Meta': {'ordering': "['titolo']", 'object_name': 'Articolo'},
            'descrizione': ('django.db.models.fields.TextField', [], {'max_length': '400', 'blank': 'True'}),
            'galleria': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['main.Galleria']"}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'immagine': ('django.db.models.fields.files.ImageField', [], {'max_length': '100'}),
            'miniatura': ('django.db.models.fields.files.ImageField', [], {'max_length': '100'}),
            'posizione': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '0'}),
            'titolo': ('django.db.models.fields.CharField', [], {'max_length': '80'})
        },
        u'main.galleria': {
            'Meta': {'ordering': "['pk']", 'object_name': 'Galleria'},
            'articolo_principale': ('django.db.models.fields.related.OneToOneField', [], {'blank': 'True', 'related_name': "'+'", 'unique': 'True', 'null': 'True', 'to': u"orm['main.Articolo']"}),
            'homepage': ('django.db.models.fields.related.ForeignKey', [], {'default': '1', 'to': u"orm['main.Homepage']"}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'menu': ('django.db.models.fields.CharField', [], {'max_length': '50'}),
            'posizione': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '0'}),
            'slogan': ('django.db.models.fields.CharField', [], {'max_length': '50', 'blank': 'True'}),
            'titolo': ('django.db.models.fields.CharField', [], {'max_length': '30'})
        },
        u'main.homepage': {
            'Meta': {'object_name': 'Homepage'},
            'descrizione': ('django.db.models.fields.CharField', [], {'max_length': '300', 'blank': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'occhiello': ('django.db.models.fields.CharField', [], {'max_length': '50', 'blank': 'True'}),
            'slogan': ('django.db.models.fields.CharField', [], {'max_length': '50'})
        }
    }

    complete_apps = ['main']
<file_sep>/calosso/urls.py
from django.conf import settings
from django.conf.urls import patterns, include, url
from django.contrib import admin
# from django.views.generic.base import TemplateView

admin.autodiscover()

urlpatterns = patterns('',
    url(r'^admin/', include(admin.site.urls)),
    url(r'^$', 'main.views.index'),
#     url(r'^chi_siamo$', TemplateView.as_view(template_name="chi_siamo.html", get_context_data=lambda:{'sezione': 'chi_siamo'})),
    url(r'^chi_siamo$', 'main.views.chi_siamo'),
#     url(r'^contatti$', TemplateView.as_view(template_name="contatti.html", get_context_data=lambda:{'sezione': 'contatti'})),
    url(r'^contatti$', 'main.views.contatti'),
    url(r'^gallery/(?P<gallery_id>\d)$', 'main.views.gallery'),
)

# static media
if settings.DEBUG:
    urlpatterns += patterns('',
        (r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),
    )

# handler500 = 'main.views.nondefault_500_error'
<file_sep>/calosso/apps/main/templatetags/template_debug.py
from django.template import Library, Node
register = Library()


class PydevDebugNode(Node):
    def render(self, context):
        try:
            import pydevd #@UnresolvedImport
            pydevd.connected = True
            pydevd.settrace()
            return ''
        except:
            # It might be more clear to just let this exception pass through
            return 'Debugger was not turned on'

@register.tag
def template_debug(parser, token):
    return PydevDebugNode()
<file_sep>/calosso/apps/main/models.py
# -*- coding: utf-8 -*-

from django.db import models

### GESTIONE CARICAMENTO E CANCELLAZIONE IMMAGINI ARTICOLI (inizio) ###
import os
from django.core.files.storage import FileSystemStorage
from django.conf import settings
class OverwriteFileStorage(FileSystemStorage):   
    def get_available_name(self, name):
        if self.exists(name):
            os.remove(os.path.join(settings.MEDIA_ROOT, name))
        return name
def get_miniatura_path(instance, filename):
    return 'img/{0}/piccole/{1}'.format(instance.galleria.pk, filename)
def get_immagine_path(instance, filename):
    return 'img/{0}/{1}'.format(instance.galleria.pk, filename)
from django.db.models.fields.files import FieldFile
from django.db.models.signals import pre_delete
def file_cleanup(sender, instance, *args, **kwargs):
    '''
        Deletes the file(s) associated with a model instance. The model
        is not saved after deletion of the file(s) since this is meant
        to be used with the pre_delete signal.
        Se vuote, cancella anche la directory contenitore e la sua parent.
    '''
    for field_name, _ in list(instance.__dict__.iteritems()):
        field = getattr(instance, field_name)
        if issubclass(field.__class__, FieldFile) and field.name:
            dir_path = os.path.join(settings.MEDIA_ROOT, os.path.dirname(field.name))
            field.delete(save=False)
            if os.path.isdir(dir_path) and not os.listdir(dir_path):
                parent_dir_path = os.path.dirname(dir_path)
                os.rmdir(dir_path)
                if os.path.isdir(parent_dir_path) and not os.listdir(parent_dir_path):
                    os.rmdir(parent_dir_path)
### GESTIONE CARICAMENTO E CANCELLAZIONE IMMAGINI ARTICOLI (fine) ###

class Homepage(models.Model):
    slogan = models.CharField('Slogan', max_length=50, blank=False)
    descrizione = models.CharField('Descrizione', max_length=300, blank=True)
    occhiello = models.CharField('Occhiello', max_length=50, blank=True)
    immagine = models.ImageField('Immagine', blank=False, upload_to='img/home', storage=OverwriteFileStorage())
#     galleria_principale = models.OneToOneField('Galleria')
    class Meta:
        verbose_name = "HOMEPAGE"
        verbose_name_plural = "Homepage"
    def __unicode__(self):
        return u"Gestione HOMEPAGE"

class Galleria(models.Model):
    POSIZIONE_SCELTE = (
                     (0,'Disabilitato'),
                     (1,'Galleria Principale'),
                     (2,'Riga 1 - SX'), (3,'Riga 1 - C'), (4,'Riga 1 - DX'),
                     (5,'Riga 2 - SX'), (6,'Riga 2 - C'), (7,'Riga 2 - DX'),
    )
    homepage = models.ForeignKey(Homepage, default=1, editable=False)
    menu = models.CharField('Voce di menù', max_length=50, blank=False)
    slogan = models.CharField('Slogan', max_length=50, blank=True)
    titolo = models.CharField('Titolo', max_length=30, blank=False)
    articolo_principale = models.OneToOneField('Articolo', on_delete=models.SET_NULL, blank=True, null=True, related_name='+') # nessuna backwards relation
    posizione = models.PositiveSmallIntegerField('Posizione in homepage', blank=False, default=0, choices=POSIZIONE_SCELTE)
    class Meta:
        verbose_name = "GALLERIA"
        verbose_name_plural = "Gallerie"
        ordering = ['posizione', 'pk']
    def __unicode__(self):
        return u'{0} - {1}'.format(self.posizione, self.menu)

class Articolo(models.Model):
    POSIZIONE_SCELTE = (
                     (0,'Disabilitato'),
                     (1,'Riga 1 - SX'), (2,'Riga 1 - C'), (3,'Riga 1 - DX'),
                     (4,'Riga 2 - SX'), (5,'Riga 2 - C'), (6,'Riga 2 - DX'),
                     (7,'Riga 3 - SX'), (8,'Riga 3 - C'), (9,'Riga 3 - DX'),
                     (10,'Riga 4 - SX'), (11,'Riga 4 - C'), (12,'Riga 4 - DX'),
                     (13,'Riga 5 - SX'), (14,'Riga 5 - C'), (15,'Riga 5 - DX'),
                     (16,'Riga 6 - SX'), (17,'Riga 6 - C'), (18,'Riga 6 - DX'),
    )
    galleria = models.ForeignKey(Galleria)
    miniatura = models.ImageField('Miniatura', blank=False, upload_to=get_miniatura_path, storage=OverwriteFileStorage())
    immagine = models.ImageField('Immagine', blank=False, upload_to=get_immagine_path, storage=OverwriteFileStorage())
    titolo = models.CharField('Titolo', max_length=80, blank=False)
    descrizione = models.TextField('Descrizione', max_length=400, blank=True)
    posizione = models.PositiveSmallIntegerField('Posizione in galleria', blank=False, default=0, choices=POSIZIONE_SCELTE)
    class Meta:
        verbose_name = "ARTICOLO"
        verbose_name_plural = "Articoli"
        ordering = ['posizione', 'pk']
    def __unicode__(self):
        return u'{0} - {1}'.format(self.posizione, self.titolo)

pre_delete.connect(file_cleanup, sender=Articolo)

class Varie(models.Model):
    immagine_chi_siamo = models.ImageField('Immagine sezione "chi siamo"', blank=False, upload_to='img/varie', storage=OverwriteFileStorage())
    testo_chi_siamo = models.TextField('Testo sezione "chi siamo"', blank=False)
    testo_contatti = models.TextField('Testo sezione "contatti"', blank=False)
    class Meta:
        verbose_name = "VARIE"
        verbose_name_plural = "Varie"
    def __unicode__(self):
        return u"Gestioni VARIE"


<file_sep>/calosso/apps/main/migrations/0002_auto__add_articolo__add_galleria__add_homepage.py
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models

class Migration(SchemaMigration):

    def forwards(self, orm):
        
        # Adding model 'Articolo'
        db.create_table(u'main_articolo', (
            (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('galleria', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['main.Galleria'])),
            ('miniatura', self.gf('django.db.models.fields.files.ImageField')(max_length=100)),
            ('immagine', self.gf('django.db.models.fields.files.ImageField')(max_length=100)),
            ('titolo', self.gf('django.db.models.fields.CharField')(max_length=80)),
            ('descrizione', self.gf('django.db.models.fields.TextField')(max_length=400, blank=True)),
            ('posizione', self.gf('django.db.models.fields.PositiveSmallIntegerField')()),
        ))
        db.send_create_signal(u'main', ['Articolo'])

        # Adding model 'Galleria'
        db.create_table(u'main_galleria', (
            (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('slogan', self.gf('django.db.models.fields.CharField')(max_length=50, blank=True)),
            ('titolo', self.gf('django.db.models.fields.CharField')(max_length=30)),
            ('articolo_principale', self.gf('django.db.models.fields.related.OneToOneField')(blank=True, related_name='+', unique=True, null=True, to=orm['main.Articolo'])),
        ))
        db.send_create_signal(u'main', ['Galleria'])

        # Adding model 'Homepage'
        db.create_table(u'main_homepage', (
            (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('slogan', self.gf('django.db.models.fields.CharField')(max_length=50)),
            ('descrizione', self.gf('django.db.models.fields.CharField')(max_length=300, blank=True)),
            ('occhiello', self.gf('django.db.models.fields.CharField')(max_length=50, blank=True)),
            ('galleria_principale', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['main.Galleria'], unique=True)),
        ))
        db.send_create_signal(u'main', ['Homepage'])


    def backwards(self, orm):
        
        # Deleting model 'Articolo'
        db.delete_table(u'main_articolo')

        # Deleting model 'Galleria'
        db.delete_table(u'main_galleria')

        # Deleting model 'Homepage'
        db.delete_table(u'main_homepage')


    models = {
        u'main.articolo': {
            'Meta': {'ordering': "['titolo']", 'object_name': 'Articolo'},
            'descrizione': ('django.db.models.fields.TextField', [], {'max_length': '400', 'blank': 'True'}),
            'galleria': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['main.Galleria']"}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'immagine': ('django.db.models.fields.files.ImageField', [], {'max_length': '100'}),
            'miniatura': ('django.db.models.fields.files.ImageField', [], {'max_length': '100'}),
            'posizione': ('django.db.models.fields.PositiveSmallIntegerField', [], {}),
            'titolo': ('django.db.models.fields.CharField', [], {'max_length': '80'})
        },
        u'main.galleria': {
            'Meta': {'ordering': "['titolo']", 'object_name': 'Galleria'},
            'articolo_principale': ('django.db.models.fields.related.OneToOneField', [], {'blank': 'True', 'related_name': "'+'", 'unique': 'True', 'null': 'True', 'to': u"orm['main.Articolo']"}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'slogan': ('django.db.models.fields.CharField', [], {'max_length': '50', 'blank': 'True'}),
            'titolo': ('django.db.models.fields.CharField', [], {'max_length': '30'})
        },
        u'main.homepage': {
            'Meta': {'object_name': 'Homepage'},
            'descrizione': ('django.db.models.fields.CharField', [], {'max_length': '300', 'blank': 'True'}),
            'galleria_principale': ('django.db.models.fields.related.OneToOneField', [], {'to': u"orm['main.Galleria']", 'unique': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'occhiello': ('django.db.models.fields.CharField', [], {'max_length': '50', 'blank': 'True'}),
            'slogan': ('django.db.models.fields.CharField', [], {'max_length': '50'})
        }
    }

    complete_apps = ['main']
<file_sep>/calosso/apps/main/admin.py
from django.db import models
from django.contrib import admin
from django.forms.models import ModelForm
from django.forms.widgets import Textarea

from models import Homepage, Galleria, Articolo, Varie
from admin_image_widget import AdminImageWidget

custom_charfield_widget = {'widget': Textarea(attrs={'cols':40, 'rows':2})}
custom_textfield_widget = {'widget': Textarea(attrs={'cols':80, 'rows':3})}
custom_image_widget = {'widget': AdminImageWidget}
widget_overrides = { 
                    models.CharField: custom_charfield_widget, 
                    models.TextField: custom_textfield_widget,
                    models.ImageField: custom_image_widget,
                    }

class ArticoloInline(admin.TabularInline):
    model = Articolo
    max_num = 18
    formfield_overrides = widget_overrides

class GalleriaForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super(GalleriaForm, self).__init__(*args, **kwargs)
        self.fields['articolo_principale'].queryset = Articolo.objects.filter(galleria__exact=self.instance.pk)
        self.exclude = ['homepage']
class GalleriaAdmin(admin.ModelAdmin):
    form = GalleriaForm
    fields = ['menu', 'posizione', 'articolo_principale', 'slogan', 'titolo']
    inlines = [ArticoloInline, ]
    formfield_overrides = widget_overrides
    def get_readonly_fields(self, request, obj=None):
        if request.user.is_superuser:
            return ()
        return ('menu', )

class GalleriaInline(admin.TabularInline):
    model = Galleria
    form = GalleriaForm
    fields = ['posizione', 'articolo_principale', 'slogan', 'titolo']
    formfield_overrides = widget_overrides
    
class HomepageAdmin(admin.ModelAdmin):
    formfield_overrides = { models.CharField: {'widget': Textarea(attrs={'cols':60, 'rows':3})}, }
    inlines = [GalleriaInline, ]

class VarieAdmin(admin.ModelAdmin):
    formfield_overrides = { models.ImageField: custom_image_widget, }
    
admin.site.register(Homepage, HomepageAdmin)
admin.site.register(Galleria, GalleriaAdmin)
# admin.site.register(Articolo)
admin.site.register(Varie, VarieAdmin)
<file_sep>/calosso/apps/main/views.py
from django.template import loader
import sys
from django import http
from django.template.context import Context
from django.shortcuts import render, get_object_or_404

from models import Galleria
from calosso.apps.main.models import Homepage, Varie

def nondefault_500_error(request, template_name='500nondefault.html'):
    """
    500 error handler for debug.

    Templates: `500.html`
    Context: sys.exc_info() results
     """
    t = loader.get_template(template_name) # You need to create a 500.html template.
    ltype,lvalue,ltraceback = sys.exc_info()
    sys.exc_clear() #for fun, and to point out I only -think- this hasn't happened at 
                    #this point in the process already
    return http.HttpResponseServerError(t.render(Context({'type':ltype,'value':lvalue,'traceback':ltraceback})))

def main_menu_context_processor(request):
    voci_menu = Galleria.objects.exclude(menu__iexact = '(nascosta)').values('pk', 'menu')
    return {'voci_menu':voci_menu}

def index(request):
    homepage = Homepage.objects.all()[:1].get()
    try:
        principale = Galleria.objects.get(posizione__exact = 1);
    except:
        principale = None
    try:
        gallerie = Galleria.objects.filter(posizione__gt = 1).order_by('posizione');
    except:
        gallerie = Galleria()
    args = {
            'sezione': '',
            'homepage': homepage,
            'principale': principale,
            'gallerie': gallerie,
            }
    return render(request, 'index.html', args)
    
def gallery(request, gallery_id):
    galleria = get_object_or_404(Galleria, pk = gallery_id)
    try:
        principale = galleria.articolo_principale.posizione
    except:
        principale = 0
    args = {'sezione': galleria.menu, 'galleria': galleria, 'principale': principale}
    return render(request, 'gallery.html', args)

def chi_siamo(request):
    varie = Varie.objects.all()[:1].get()
    args = {
            'sezione': 'chi_siamo',
            'immagine': varie.immagine_chi_siamo,
            'testo': varie.testo_chi_siamo,
            }
    return render(request, 'chi_siamo.html', args)

def contatti(request):
    varie = Varie.objects.all()[:1].get()
    args = {
            'sezione': 'contatti',
            'testo': varie.testo_contatti,
            }
    return render(request, 'contatti.html', args)
