Changeset - 66dbfac066b0
[Not reviewed]
Brett Smith (brett) - 4 years ago 2017-11-07 14:00:48
brett@sfconservancy.org
Migrate RequestContext users to render() calls.

This was necessary because render_to_response no longer takes a
context_instance. We were always using this to pass in a RequestContext,
which the render shortcut can already do, so switch to that.
8 files changed with 21 insertions and 36 deletions:
0 comments (0 inline, 0 general)
www/conservancy/__init__.py
Show inline comments
 
import hashlib
 

	
 
from django.conf import settings
 
from django.shortcuts import render_to_response
 
from django.template import RequestContext
 

	
 
# This is backwards compatibilty support for a custom function we wrote
 
# ourselves that is no longer necessary in modern Django.
 
from django.shortcuts import render as render_template_with_context
 

	
 
class ParameterValidator(object):
 
    def __init__(self, given_hash_or_params, params_hash_key=None):
 
        if params_hash_key is None:
 
            self.given_hash = given_hash_or_params
 
        else:
 
            self.given_hash = given_hash_or_params.get(params_hash_key)
 
        seed = getattr(settings, 'CONSERVANCY_SECRET_KEY', '')
 
        self.hasher = hashlib.sha256(seed)
 
        if isinstance(self.given_hash, basestring):
 
            self.hash_type = type(self.given_hash)
 
        else:
 
            self.hash_type = type(self.hasher.hexdigest())
...
 
@@ -32,17 +35,12 @@ class ParameterValidator(object):
 

	
 
    def validate(self, data):
 
        self.valid = self.valid and None
 
        self.hasher.update(data)
 

	
 
    def check(self):
 
        if self.valid or (self.valid is None):
 
            self.valid = self.hash_type(self.hasher.hexdigest()) == self.given_hash
 
        return self.valid
 

	
 
    def fail(self):
 
        self.valid = False
 

	
 

	
 
def render_template_with_context(request, template_path, context_dict):
 
    return render_to_response(template_path, context_dict,
 
                              context_instance=RequestContext(request))
www/conservancy/apps/blog/views.py
Show inline comments
 
from conservancy.apps.blog.models import Entry, EntryTag # relative import
 
# from django.views.generic.list_detail import object_list
 
from django.views.generic import ListView
 
from django.views.generic.dates import YearArchiveView, MonthArchiveView, DayArchiveView, DateDetailView
 
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
 
from conservancy.apps.staff.models import Person
 
from django.shortcuts import get_object_or_404, render_to_response
 
from django.template import RequestContext
 
from django.shortcuts import get_object_or_404, render
 
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
...
 
@@ -56,25 +55,25 @@ def custom_index(request, queryset, *args, **kwargs):
 

	
 
    try:
 
        blog_entries = paginator.page(page)
 
    except PageNotAnInteger:
 
        # If page is not an integer, deliver first page.
 
        blog_entries = paginator.page(1)
 
    except EmptyPage:
 
        # If page is out of range (e.g. 9999), deliver last page of results.
 
        blog_entries = paginator.page(paginator.num_pages)
 

	
 
    extra_context['blog_entries'] = blog_entries
 

	
 
    return render_to_response('blog/entry_list.html', extra_context, context_instance=RequestContext(request))
 
    return render(request, 'blog/entry_list.html', extra_context)
 

	
 
def techblog_redirect(request):
 
    """Redirect from the old 'techblog' to the new blog
 
    """
 

	
 
    path = request.path[len('/technology'):]
 
    if path == '/blog/':
 
        path += "?author=bkuhn"
 

	
 
    return relative_redirect(request, path)
 

	
 
def query(request):
...
 
@@ -94,26 +93,25 @@ def query(request):
 
            base_url = '/feeds/blog/'
 
            d.setlist('rss', []) # remove it
 

	
 
        query_string = d.urlencode()
 

	
 
        return relative_redirect(request, '%s%s%s' % (base_url, '?' if query_string else '', query_string))
 

	
 
    else:
 
        authors = sorted(Person.objects.filter(currently_employed=True,
 
                                               entry__isnull=False).distinct(),
 
                         key=last_name)
 
        tags = EntryTag.objects.all().order_by('label')
 
        return render_to_response('blog/query.html',
 
                                  {'authors': authors, 'tags': tags}, context_instance=RequestContext(request))
 
        return render(request, 'blog/query.html', {'authors': authors, 'tags': tags})
 

	
 
def relative_redirect(request, path):
 
    from django import http
 
    from django.conf import settings
 

	
 
    host = request.get_host()
 
    if settings.FORCE_CANONICAL_HOSTNAME:
 
        host = settings.FORCE_CANONICAL_HOSTNAME
 

	
 
    url = "%s://%s%s" % (request.is_secure() and 'https' or 'http', host, path)
 
    return http.HttpResponseRedirect(url)
 

	
www/conservancy/apps/contacts/views.py
Show inline comments
 
from django.shortcuts import render_to_response
 
from django.template import RequestContext
 
from django.shortcuts import render
 
from django import forms
 
from conservancy.apps.contacts.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_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}, context_instance=RequestContext(request))
 
            return render(request, 'contacts/subscribe_success.html', {'form': form.cleaned_data})
 
    else:
 
        form = ContactEntryForm()
 

	
 
    return render_to_response('contacts/subscribe.html',
 
                              {'form': form}, context_instance=RequestContext(request))
 
    return render(request, 'contacts/subscribe.html', {'form': form})
www/conservancy/apps/events/views.py
Show inline comments
 
# from django.views.generic.list_detail import object_list
 
from django.shortcuts import render_to_response
 
from django.template import RequestContext
 
from django.shortcuts import render
 
from django.http import Http404, HttpResponse
 
from django.template import loader
 
from django.core.exceptions import ObjectDoesNotExist
 
from conservancy.apps.events.models import Event
 
# for debugging...
 
from django.http import HttpResponse
 

	
 
def event_detail(request, year, slug, queryset, **kwargs):
 
    """This view shows event detail.
 

	
 
    Nothing special, but it is necessary because
 
    django.views.generic.date_based.object_detail only works with
 
    slugs that are unique and specified by day, but we make slugs
 
    unique by year.
 
    """
 

	
 
    try:
 
        event = queryset.get(date__year=year, slug__exact=slug)
 
    except ObjectDoesNotExist:
 
        raise Http404, "Event does not exist"
 
    return render_to_response('events/event_detail.html', {'event': event}, context_instance=RequestContext(request))
 
    return render(request, 'events/event_detail.html', {'event': event})
 

	
 
def custom_index(request, queryset, *args, **kwargs):
 
    """Scrollable index of future and past events, with date index.
 
    """
 

	
 
    future_events = None
 
    if not request.GET.has_key("page"):
 
        future_events = Event.future.all().order_by("date")
 

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

	
 
    kwargs = dict(kwargs, extra_context={'date_list': date_list,
www/conservancy/apps/news/views.py
Show inline comments
 
# from django.views.generic.list_detail import object_list
 
from django.views.generic import ListView
 
from django.template import RequestContext
 
from django.shortcuts import render_to_response
 
from django.shortcuts import render
 
from django.views.generic.dates import YearArchiveView, MonthArchiveView, DayArchiveView, DateDetailView
 
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
 
from conservancy.apps.news.models import ExternalArticle
 
from conservancy.apps.news.models import PressRelease
 
from conservancy.apps.events.models import Event
 
from datetime import datetime
 
# for debugging...
 
from django.http import HttpResponse
 

	
 

	
 
class NewsListView(ListView):
 
    extra_context = {}
...
 
@@ -33,25 +32,25 @@ def listing(request, *args, **kwargs):
 
    paginator = Paginator(news_queryset, paginate_by)
 

	
 
    page = request.GET.get('page')
 
    try:
 
        news = paginator.page(page)
 
    except PageNotAnInteger:
 
        # If page is not an integer, deliver first page.
 
        news = paginator.page(1)
 
    except EmptyPage:
 
        # If page is out of range (e.g. 9999), deliver last page of results.
 
        news = paginator.page(paginator.num_pages)
 

	
 
    return render_to_response('news/pressrelease_list.html', {"news": news, "date_list" : date_list}, context_instance=RequestContext(request))
 
    return render(request, 'news/pressrelease_list.html', {"news": news, "date_list" : date_list})
 

	
 
class NewsYearArchiveView(YearArchiveView):
 
    # queryset = Article.objects.all()
 
    # date_field = "pub_date"
 
    make_object_list = True
 
    allow_future = True
 

	
 
# def archive_year(request, **kwargs):
 
#     callable = NewsYearArchiveView.as_view(**kwargs)
 
#     return callable(request)
 

	
 
class NewsMonthArchiveView(MonthArchiveView):
www/conservancy/apps/summit_registration/views.py
Show inline comments
 
from django.shortcuts import render_to_response
 
from django.template import RequestContext
 
from django.shortcuts import render
 
from django import forms
 
from django.template import RequestContext
 
from conervancy.apps.summit_registration.models import SummitRegistration
 

	
 
def register(request):
 
    """Summit registration form view
 
    """
 

	
 
    class SummitForm(ModelForm):
 
        class Meta:
 
            model = SummitRegistration
 

	
 
    SummitForm.base_fields['email'].label = 'Email address'
 
    SummitForm.base_fields['phone'].label = 'Phone number'
 
    SummitForm.base_fields['address'].label = 'Mailing address'
 
    SummitForm.base_fields['cle_credit'].label = 'Attending for CLE credit?'
 

	
 
    if request.method == 'POST':
 
        form = SummitForm(request.POST)
 
        if form.is_valid():
 
            form.save()
 
            return render_to_response('summit_registration/register_success.html',
 
                                      {'form': form.cleaned_data}, context_instance=RequestContext(request))
 
            return render(reqeust, 'summit_registration/register_success.html', {'form': form.cleaned_data})
 
    else:
 
        form = SummitForm()
 

	
 
    return render_to_response('summit_registration/register.html',
 
                              {'form': form}, context_instance=RequestContext(request))
 
    return render(request, 'summit_registration/register.html', {'form': form})
www/conservancy/feeds.py
Show inline comments
 
from django.contrib.syndication.views import Feed
 
from django.utils.feedgenerator import Rss201rev2Feed 
 
from conservancy.apps.news.models import PressRelease
 
from conservancy.apps.blog.models import Entry as BlogEntry
 
from django.template import RequestContext
 
from django.shortcuts import render_to_response
 
from django.shortcuts import render
 
from django.conf import settings
 
from datetime import datetime
 

	
 
import itertools
 
import operator
 

	
 
class ConservancyFeedBase(Feed):
 
    def copyright_holder(self): return "Software Freedom Conservancy"
 

	
 
    def license_no_html(self): return "Licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported License."
 

	
 
    def item_copyright(self, item):
...
 
@@ -246,13 +245,13 @@ class BlogFeed(ConservancyFeedBase):
 
        if 'tag' in GET:
 
            tags = GET.getlist('tag')
 
            queryset = queryset.filter(OR_filter('tags', 'slug', tags))
 

	
 
        return queryset.order_by('-pub_date')[:10]
 

	
 

	
 
def view(request):
 
    """Listing of all available feeds
 
    """
 

	
 
    feeds = (PressReleaseFeed, BlogFeed, OmnibusFeed)
 
    return render_to_response("feeds.html", {'feeds': feeds}, context_instance=RequestContext(request))
 
    return render(request, "feeds.html", {'feeds': feeds})
www/conservancy/sponsors.py
Show inline comments
 
from django.shortcuts import render_to_response
 
from django.template import RequestContext
 
from django.shortcuts import render
 
from conservancy.apps.supporters.models import Supporter as Supporter
 
from datetime import datetime, timedelta
 

	
 
def view(request):
 
    """Conservancy Sponsors Page view
 

	
 
    Performs object queries necessary to render the sponsors page.
 
    """
 

	
 
    supporters = Supporter.objects.all().filter(display_until_date__gte=datetime.now())
 
    supporters_count = len(supporters)
 
    anonymous_count  = len(supporters.filter(display_name = 'Anonymous'))
 
    supporters = supporters.exclude(display_name = 'Anonymous').order_by('ledger_entity_id')
 

	
 
    c = {
 
        'supporters' : supporters,
 
        'supporters_count' : supporters_count,
 
        'anonymous_count' : anonymous_count
 
    }
 
    return render_to_response("sponsors.html", c, context_instance=RequestContext(request))
 
    return render(request, "sponsors.html", c)
0 comments (0 inline, 0 general)