Changeset - f7e45da6ddc8
[Not reviewed]
www/conservancy/apps/blog/models.py
Show inline comments
 
from django.db import models
 
from django.conf import settings
 
from sflc.apps.staff.models import Person
 
from conservancy.apps.staff.models import Person
 
from datetime import datetime, timedelta
 

	
 
class EntryTag(models.Model):
 
    """Tagging for blog entries"""
 

	
 
    label = models.CharField(max_length=100)
 
    slug = models.SlugField()
 

	
 
    class Meta:
 
        db_table = 'techblog_entrytag' # legacy
 

	
 
    def __unicode__(self):
 
        return self.label
 

	
 
    def get_absolute_url(self):
 
        return u"/blog/?tag=%s" % self.slug
 

	
 
class Entry(models.Model):
 
    """Blog entry"""
 

	
 
    headline = models.CharField(max_length=200)
 
    slug = models.SlugField(unique_for_date='pub_date')
 
    summary = models.TextField(help_text="Use raw HTML.  Unlike in the press release model, this summary is not included at the beginning of the body when the entry is displayed.")
 
    body = models.TextField(help_text="Use raw HTML.  Include the full body of the post.")
...
 
@@ -32,45 +32,45 @@ class Entry(models.Model):
 
    date_created = models.DateTimeField(auto_now_add=True)
 
    date_last_modified = models.DateTimeField(auto_now=True)
 

	
 
    class Meta:
 
        db_table = 'techblog_entries' # legacy
 
        verbose_name_plural = 'entries'
 
        ordering = ('-pub_date',)
 
        get_latest_by = 'pub_date'
 

	
 
    def __unicode__(self):
 
        return self.headline
 

	
 
    def get_absolute_url(self):
 
        return (u"/blog/%s/%s/"
 
                % (self.pub_date.strftime("%Y/%b/%d").lower(),
 
                   self.slug))
 

	
 
    def is_recent(self):
 
        return self.pub_date > (datetime.now() - timedelta(days=14))
 
        # question: does datetime.now() do a syscall each time is it called?
 

	
 
    # Ping google blogs and technorati.  Taken from
 
    # http://blog.foozia.com/blog/2007/apr/21/ping-technorati-your-django-blog-using-xml-rpc/
 
    def save(self):
 
        if settings.SFLC_DEVEL or True: # "or True" means it is disabled always
 
        if settings.CONSERVANCY_DEVEL or True: # "or True" means it is disabled always
 
            super(Entry, self).save()
 
            return
 

	
 
        blog_name = 'Software Freedom Law Center Blog'
 
        blog_url =  'http://www.softwarefreedom.org/blog/'
 
        post_url = ('http://www.softwarefreedom.org'
 
                    + self.get_absolute_url())
 

	
 
        import xmlrpclib
 

	
 
        # Ping Technorati
 
        j = xmlrpclib.Server('http://rpc.technorati.com/rpc/ping')
 
        reply = j.weblogUpdates.ping(blog_name, blog_url)
 

	
 
        # Ping Google Blog Search
 
        j = xmlrpclib.Server('http://blogsearch.google.com/ping/RPC2')
 
        reply = j.weblogUpdates.ping(blog_name, blog_url, post_url)
 

	
 
        # Call any superclass's method
 
        super(Entry, self).save()
www/conservancy/apps/blog/urls.py
Show inline comments
 
from django.conf.urls.defaults import *
 
from models import Entry, EntryTag # relative import
 
from views import last_name # relative import
 
from sflc.apps.staff.models import Person
 
from conservancy.apps.staff.models import Person
 
from datetime import datetime
 

	
 
extra_context = {}
 

	
 
info_dict = {
 
    'queryset': Entry.objects.all(),
 
    'date_field': 'pub_date',
 
    'extra_context': extra_context,
 
}
 

	
 
urlpatterns = patterns('django.views.generic.date_based',
 
   (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/(?P<day>\w{1,2})/(?P<slug>[-\w]+)/$', 'object_detail', dict(info_dict, slug_field='slug')),
 
   (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/(?P<day>\w{1,2})/$', 'archive_day', info_dict),
 
   (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$', 'archive_month', info_dict),
 
   (r'^(?P<year>\d{4})/$', 'archive_year', dict(info_dict,
 
                                                make_object_list=True)),
 
)
 

	
 
urlpatterns += patterns('sflc.apps.blog.views',
 
urlpatterns += patterns('conservancy.apps.blog.views',
 
   (r'^/?$', 'custom_index', dict(info_dict, paginate_by=10)),
 
   (r'^query/$', 'query'),
 
)
 

	
 
# Code to display authors and tags on each blog page
 

	
 
def all_tags_by_use_amount():
 
    """Returns all tags with an added 'cnt' attribute (how many times used)
 

	
 
    Also sorts the tags so most-used tags appear first.
 
    """
 

	
 
    # tally use amount
 
    retval = []
 
    current = None
 
    for obj in EntryTag.objects.filter(entry__pub_date__lte=datetime.now(),
 
                                       entry__isnull=False).order_by('label'):
 
        if current is not None and obj.id == current.id:
 
            current.cnt += 1
 
        else:
 
            if current is not None:
 
                retval.append(current)
 
            current = obj
 
            current.cnt = 1
www/conservancy/apps/blog/views.py
Show inline comments
 
from models import Entry, EntryTag # relative import
 
from django.views.generic.list_detail import object_list
 
from sflc.apps.staff.models import Person
 
from conservancy.apps.staff.models import Person
 
from django.shortcuts import get_object_or_404, render_to_response
 
from datetime import datetime
 

	
 
def OR_filter(field_name, objs):
 
    from django.db.models import Q
 
    return reduce(lambda x, y: x | y,
 
                  [Q(**{field_name: x.id}) for x in objs])
 

	
 
def last_name(person):
 
    return person.formal_name.rpartition(' ')[2]
 

	
 
def custom_index(request, queryset, *args, **kwargs):
 
    """Blog list view that allows scrolling and also shows an index by
 
    year.
 
    """
 

	
 
    kwargs = kwargs.copy()
 
    kwargs['extra_context'] = kwargs.get('extra_context', {}).copy()
 
    extra_context = kwargs['extra_context']
 

	
 
    date_field = kwargs['date_field']
 
    del kwargs['date_field']
 

	
 
    if not kwargs.get('allow_future', False):
www/conservancy/apps/contacts/admin.py
Show inline comments
 
from django.contrib import admin
 
from models import ContactEntry
 

	
 
class ContactEntryAdmin(admin.ModelAdmin):
 
    list_display = ('email', 'subscribe_sflc', 'subscribe_sfc')
 
    list_display = ('email', 'subscribe_conservancy')
 

	
 

	
 
admin.site.register(ContactEntry, ContactEntryAdmin)
www/conservancy/apps/contacts/models.py
Show inline comments
 
from django.db import models
 

	
 
class ContactEntry(models.Model):
 
    """SFLC contact system
 
    """Conservancy contact system
 

	
 
    Hopefully this will be deprecated soon"""
 

	
 
    email = models.EmailField() # should make it unique, but we really cannot
 
    subscribe_sflc = models.BooleanField()
 
    subscribe_sfc = models.BooleanField()
 
    subscribe_conservancy = models.BooleanField()
 

	
 
    class Meta:
 
        ordering = ('email',)
 

	
www/conservancy/apps/contacts/urls.py
Show inline comments
 
from django.conf.urls.defaults import *
 

	
 
urlpatterns = patterns('sflc.apps.contacts.views',
 
urlpatterns = patterns('conservancy.apps.contacts.views',
 
   (r'^/?$', 'subscribe'),
 
)
www/conservancy/apps/contacts/views.py
Show inline comments
 
from django.shortcuts import render_to_response
 
from django import forms
 
from models import ContactEntry
 
from django.forms import ModelForm
 

	
 
def subscribe(request):
 
    """Mailing list subscription form
 
    """
 

	
 
    class ContactEntryForm(ModelForm):
 
        class Meta:
 
            model = ContactEntry
 

	
 
    ContactEntryForm.base_fields['subscribe_sflc'].label = 'Receive Software Freedom Law Center updates'
 
    ContactEntryForm.base_fields['subscribe_sfc'].label = 'Receive Software Freedom Conservancy updates'
 
    ContactEntryForm.base_fields['subscribe_conservancy'].label = 'Receive Software Freedom Conservancy updates'
 

	
 
    if request.method == 'POST':
 
        form = ContactEntryForm(request.POST)
 
        if form.is_valid():
 
            form.save()
 
            return render_to_response('contacts/subscribe_success.html',
 
                                      {'form': form.cleaned_data})
 
    else:
 
        form = ContactEntryForm()
 

	
 
    return render_to_response('contacts/subscribe.html',
 
                              {'form': form})
www/conservancy/apps/events/models.py
Show inline comments
 
from django.db import models
 
from sflc.apps.staff.models import Person
 
from sflc.apps.worldmap.models import EarthLocation
 
from conservancy.apps.staff.models import Person
 
from conservancy.apps.worldmap.models import EarthLocation
 
from datetime import datetime, timedelta
 

	
 
class EventTag(models.Model):
 
    """Tagging for events
 

	
 
    (currently unused)
 
    """
 

	
 
    label = models.CharField(max_length=100)
 

	
 
    date_created = models.DateField(auto_now_add=True)
 

	
 
    def __unicode__(self):
 
        return self.label
 

	
 
class PastEventManager(models.Manager):
 
    """Returns all past events"""
 

	
 
    def get_query_set(self):
 
        return super(PastEventManager, self).get_query_set().filter(date__lt=datetime.today())
 

	
 
class FutureEventManager(models.Manager):
 
    """Returns all future events"""
 

	
 
    def get_query_set(self):
 
        return super(FutureEventManager, self).get_query_set().filter(date__gte=datetime.today())
 

	
 
class Event(models.Model):
 
    """Model for SFLC staff member events (presentations, etc)"""
 
    """Model for Conservancy staff member events (presentations, etc)"""
 

	
 
    title = models.CharField(max_length=400)
 
    date = models.DateField()
 
    date_tentative = models.BooleanField()
 
    datetime = models.CharField("Date and Time", max_length=300, blank=True)
 
    slug = models.SlugField(unique_for_year='date')
 
    description = models.TextField(blank=True)
 
    people = models.ManyToManyField(Person, null=True, blank=True)
 
    location = models.CharField(max_length=1000)
 
    earth_location = models.ForeignKey(EarthLocation, null=True, blank=True,
 
                                       help_text="Label will not be displayed")
 
    tags = models.ManyToManyField(EventTag, null=True, blank=True)
 

	
 
    date_created = models.DateTimeField(auto_now_add=True)
 
    date_last_modified = models.DateTimeField(auto_now=True)
 

	
 
    class Meta:
 
        ordering = ("-date",)
 

	
 
    def __unicode__(self):
 
        return u"%s (%s)" % (self.title, self.date)
 

	
 
    def get_absolute_url(self):
 
        return u"/events/%s/%s/" % (self.date.strftime("%Y"), self.slug)
www/conservancy/apps/events/urls.py
Show inline comments
 
from django.conf.urls.defaults import *
 
from models import Event # relative import
 

	
 
info_dict = {
 
    'queryset': Event.objects.all(),
 
    'date_field': 'date',
 
    'allow_future': True,
 
}
 

	
 
urlpatterns = patterns('django.views.generic.date_based',
 
    (r'^(?P<year>\d{4})/$', 'archive_year', dict(info_dict,
 
                                                 make_object_list=True)),
 
)
 

	
 
urlpatterns += patterns('sflc.apps.events.views',
 
urlpatterns += patterns('conservancy.apps.events.views',
 
    (r'^/?$', 'custom_index', dict(info_dict, queryset=Event.past.all(), paginate_by=10)),
 
    (r'^(?P<year>\d{4})/(?P<slug>[-\w]+)/$', 'event_detail', dict(info_dict, slug_field='slug')),
 
    (r'^ics/$', 'future_event_ics', info_dict),
 
)
www/conservancy/apps/news/models.py
Show inline comments
 
from django.db import models
 
from django.conf import settings
 
from sflc.apps.staff.models import Person
 
from sflc.apps.events.models import Event
 
from conservancy.apps.staff.models import Person
 
from conservancy.apps.events.models import Event
 
from django.contrib.sites.models import Site
 
from datetime import datetime, timedelta
 

	
 
class PressRelease(models.Model):
 
    """News release model"""
 

	
 
    headline = models.CharField(max_length=300)
 
    subhead = models.CharField(max_length=300, blank=True)
 
    slug = models.SlugField(unique_for_date="pub_date",
 
                            help_text=("automatically built from headline"))
 
    summary = models.TextField(help_text="First paragraph (raw HTML)")
 
    body = models.TextField(help_text="Remainder of post (raw HTML)",
 
                            blank=True)
 
    pub_date = models.DateTimeField("date [to be] published")
 
    sites = models.ManyToManyField(Site)
 

	
 
    date_last_modified = models.DateTimeField(auto_now=True)
 

	
 
    class Meta:
 
        ordering = ("-pub_date",)
 
        get_latest_by = "pub_date"
 

	
 
    def __unicode__(self):
 
        return self.headline
 

	
 
    def get_absolute_url(self):
 
        return u"/news/%s/%s/" % (self.pub_date.strftime("%Y/%b/%d").lower(),
 
                                  self.slug)
 

	
 
    def is_recent(self):
 
        return self.pub_date > (datetime.now() - timedelta(days=5))
 
        # question: does datetime.now() do a syscall each time is it called?
 

	
 
    def is_in_past_month(self):
 
        # This function is deprecated.  Use the date_within template
 
        # filter instead (example in sflc/templates/frontpage.html)
 
        # filter instead (example in conservancy/templates/frontpage.html)
 
        return self.pub_date > (datetime.now() - timedelta(days=30))
 

	
 
    def save(self):
 
        if settings.SFLC_DEVEL or True:
 
        if settings.CONSERVANCY_DEVEL or True:
 
            super(PressRelease, self).save()
 
            return
 

	
 
        blog_name = 'Software Freedom Law Center News'
 
        blog_url =  'http://www.softwarefreedom.org/news/'
 
        post_url = ('http://www.softwarefreedom.org'
 
                    + self.get_absolute_url())
 

	
 
        import xmlrpclib
 

	
 
        # Ping Technorati
 
        j = xmlrpclib.Server('http://rpc.technorati.com/rpc/ping')
 
        reply = j.weblogUpdates.ping(blog_name, blog_url)
 

	
 
        # Ping Google Blog Search
 
        j = xmlrpclib.Server('http://blogsearch.google.com/ping/RPC2')
 
        reply = j.weblogUpdates.ping(blog_name, blog_url, post_url)
 

	
 
        # Call any superclass's method
 
        super(PressRelease, self).save()
 

	
 
class ExternalArticleTag(models.Model):
 
    """A way to tag external articles"""
 

	
 
    label = models.CharField(max_length=100)
 

	
 
    date_created = models.DateField(auto_now_add=True)
 

	
 
    def __unicode__(self):
 
        return self.label
 

	
 
class PublicExternalArticleManager(models.Manager):
 
    def get_query_set(self):
 
        return super(PublicExternalArticleManager, self).get_query_set().filter(visible=True)
 

	
 
class ExternalArticle(models.Model):
 
    """A system for displaying SFLC news mentions on the site.
 
    """A system for displaying Conservancy news mentions on the site.
 

	
 
    (Currently unused)
 
    """
 

	
 
    title = models.CharField(max_length=400)
 
    info = models.CharField(help_text="subscribers only? audio? pdf warning?",
 
                            blank=True, max_length=300)
 
    publication = models.CharField("source of article", max_length=300)
 
    url = models.URLField(blank=True, verify_exists=False)
 
    date = models.DateField()
 
    visible = models.BooleanField(help_text="Whether to display on website")
 

	
 
    tags = models.ManyToManyField(ExternalArticleTag, null=True, blank=True)
 
    people = models.ManyToManyField(Person, null=True, blank=True)
 
    event = models.ForeignKey(Event, null=True, blank=True)
 
    press_release = models.ForeignKey(PressRelease, null=True, blank=True)
 

	
 
    date_created = models.DateField(auto_now_add=True)
 

	
 
    class Meta:
 
        ordering = ("-date_created",)
 
        get_latest_by = "date_created"
 

	
 
    def __unicode__(self):
www/conservancy/apps/news/views.py
Show inline comments
 
from django.views.generic.list_detail import object_list
 
from sflc.apps.news.models import ExternalArticle
 
from sflc.apps.events.models import Event
 
from conservancy.apps.news.models import ExternalArticle
 
from conservancy.apps.events.models import Event
 
from datetime import datetime
 

	
 
def custom_index(request, queryset, *args, **kwargs):
 
    """News index.  Calls a generic list view, but passes additional
 
    context including past and future events, and an index of news by
 
    year.
 
    """
 

	
 
    articles = None
 
    #if not request.GET.has_key("page"):
 
    #    articles = ExternalArticle.public.all().order_by("-date")[:10]
 

	
 
    if (not kwargs.has_key('allow_future')) or not kwargs['allow_future']:
 
        queryset = queryset.filter(**{'%s__lte' % kwargs['date_field']:
 
                                      datetime.now()})
 

	
 
    future_events = Event.future.all().filter(date_tentative=False).order_by("date")
 
    past_events = Event.past.all().order_by("-date")[:6]
 

	
 
    date_list = queryset.dates(kwargs['date_field'], 'year')
 

	
 
    kwargs = dict(kwargs, extra_context={'articles': articles,
 
                                         'date_list': date_list,
 
                                         'future_events': future_events,
www/conservancy/apps/podcast/models.py
Show inline comments
 
from django.db import models
 
from django.conf import settings
 
from sflc.apps.staff.models import Person
 
from conservancy.apps.staff.models import Person
 
from datetime import datetime, timedelta
 

	
 
class PodcastTag(models.Model):
 
    """Tagging for podcasts"""
 

	
 
    label = models.CharField(max_length=100)
 
    slug = models.SlugField()
 

	
 
    class Meta:
 
        db_table = 'podcast_tags' # legacy
 

	
 
    def __unicode__(self):
 
        return self.label
 

	
 
    def get_absolute_url(self):
 
        return u"/podcast/?tag=%s" % self.slug
 

	
 
class Podcast(models.Model):
 
    """Podcast"""
 

	
 
    title = models.CharField(max_length=200)
 
    slug = models.SlugField(unique=True)
 
    summary = models.TextField(help_text="Use raw HTML.  This summary is not included at the beginning of the body when the entry is displayed.  It used only for the material on the front page.")
 
    body = models.TextField(help_text="Use raw HTML.  Include the full body of any show notes or other information about this episode.  It will be labelled on the site as Show Notes.  It is included on the detail entry, and in the description data on the podcast RSS feed.")
www/conservancy/apps/podcast/urls.py
Show inline comments
 
from django.conf.urls.defaults import *
 
from models import Podcast, PodcastTag # relative import
 
from sflc.apps.staff.models import Person
 
from conservancy.apps.staff.models import Person
 
from datetime import datetime
 

	
 
extra_context = {}
 

	
 
info_dict = {
 
    'queryset': Podcast.objects.all(),
 
    'date_field': 'pub_date',
 
    'extra_context': extra_context,
 
}
 

	
 
urlpatterns = patterns('django.views.generic.date_based',
 
   (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/(?P<day>\w{1,2})/(?P<slug>[-\w]+)/$', 'object_detail', dict(info_dict, slug_field='slug')),
 
   (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/(?P<day>\w{1,2})/$', 'archive_day', info_dict),
 
   (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$', 'archive_month', info_dict),
 
   (r'^(?P<year>\d{4})/$', 'archive_year', dict(info_dict,
 
                                                make_object_list=True)),
 
# FIXME HOW DO I MAKE THE SLUG WORK WITH NO DATES IN IT.
 
#   (r'^(?P<slug>[-\w]+)/$', 'object_detail', dict(info_dict, slug_field='slug')),
 
)
 

	
 
urlpatterns += patterns('sflc.apps.podcast.views',
 
urlpatterns += patterns('conservancy.apps.podcast.views',
 
   (r'^/?$', 'custom_index', dict(info_dict, paginate_by=20)),
 
   (r'^query/$', 'query'),
 
)
 

	
 
# Code to display authors and tags on each blog page
 

	
 
def all_tags_by_use_amount():
 
    """Returns all tags with an added 'cnt' attribute (how many times used)
 

	
 
    Also sorts the tags so most-used tags appear first.
 
    """
 

	
 
    # tally use amount
 
    retval = []
 
    current = None
 
    for obj in PodcastTag.objects.filter(podcast__pub_date__lte=datetime.now(),
 
                                       podcast__isnull=False).order_by('label'):
 
        if current is not None and obj.id == current.id:
 
            current.cnt += 1
 
        else:
 
            if current is not None:
 
                retval.append(current)
 
            current = obj
 
            current.cnt = 1
www/conservancy/apps/podcast/views.py
Show inline comments
 
from models import Podcast, PodcastTag # relative import
 
from django.views.generic.list_detail import object_list
 
from sflc.apps.staff.models import Person
 
from conservancy.apps.staff.models import Person
 
from django.shortcuts import get_object_or_404, render_to_response
 
from datetime import datetime
 

	
 
def OR_filter(field_name, objs):
 
    from django.db.models import Q
 
    return reduce(lambda x, y: x | y,
 
                  [Q(**{field_name: x.id}) for x in objs])
 

	
 
def last_name(person):
 
    return person.formal_name.rpartition(' ')[2]
 

	
 
def custom_index(request, queryset, *args, **kwargs):
 
    """Podcast list view that allows scrolling and also shows an index by
 
    year.
 
    """
 

	
 
    kwargs = kwargs.copy()
 
    kwargs['extra_context'] = kwargs.get('extra_context', {}).copy()
 
    extra_context = kwargs['extra_context']
 

	
 
    date_field = kwargs['date_field']
 
    del kwargs['date_field']
 

	
 
    if not kwargs.get('allow_future', False):
www/conservancy/apps/summit_registration/urls.py
Show inline comments
 
from django.conf.urls.defaults import *
 

	
 
urlpatterns = patterns('sflc.apps.summit_registration.views',
 
urlpatterns = patterns('conservancy.apps.summit_registration.views',
 
   (r'^/?$', 'register'),
 
)
0 comments (0 inline, 0 general)