Source

pentasubmitter / src / submitter / views.py

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
# -*- coding: utf-8 -*-
"""
views for the news submitter
"""

import datetime
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponseRedirect, HttpResponse, Http404
from django.shortcuts import render_to_response, get_object_or_404, \
        get_list_or_404
from django.views.generic import list_detail
from django.contrib.auth.decorators import login_required, user_passes_test
from django.core import serializers
from django.template import RequestContext
from voting.models import Vote
from uni_form.helpers import FormHelper, Submit, Reset
from submitter.models import EntryCategory, NewsEntry
from submitter.forms import EntryCategoryForm, NewsEntryFormShort, \
        NewsEntryFormFull
from show.models import PentaShow
from pentasubmitter.template import set_template_params

from pentasubmitter.debug import interact

def get_next_shows():
    "Return a list of shows that have a production_data later than now"
    return PentaShow.objects.filter(
        production_date__gte=datetime.datetime.now()).order_by(
            'production_date')

def news_per_next_show(request):
    """Show all news for the upcoming pentaradio show
    """
    next_shows = get_next_shows()
    if not next_shows:
        raise Http404
    next_show = next_shows[0]
    return news_per_show(request, show_slug=next_show.slug)

def news_entries_index(request):
    """Return view of all NewsEntry() instances"""
    return render_to_response('submitter/news_entry_index.html',
                              {'news_entry_list': NewsEntry.objects.order_by(
                                  '-submit_date')},
                              context_instance=RequestContext(request)
                             )

def get_read_news(request):
    """Returns a list of all news read in the show"""
    return render_to_response('submitter/news_entry_index.html',
            {'news_entry_list': NewsEntry.objects.filter(
                was_read=True).order_by(
                    '-submit_date')},
            context_instance=RequestContext(request)
            )

def news_per_category(request, category_slug=None):
    """Return HTTP response of all NewsEntry() per NewsCategory()"""

    entry_category = get_object_or_404(
        EntryCategory,
        slug__iexact=category_slug
    )
    next_shows = get_next_shows()
    # TODO (a8) return a warning, not a 404 in that case
    if not next_shows:
        raise Http404
    next_show = next_shows[0]
    filters = {'show': next_show, 'status': 1, 'categories': entry_category}
    return list_detail.object_list(
        request,
        queryset = NewsEntry.objects.filter(**filters),
        template_name = 'submitter/news_per_category.html',
        template_object_name = 'object',
        extra_context = {
            'category': entry_category,
            'tag_filters': filters,
        },
    )

def news_per_show(request, show_slug=None):
    """Return HTTP response of all NewsEntry() per PentaShow()"""

    if not show_slug:
        next_shows = get_next_shows()
        if not next_shows:
            raise Http404
        penta_show = next_shows[0]
    else:
        penta_show = get_object_or_404(
            PentaShow,
            slug__iexact=show_slug
        )
    filters = {'show': penta_show, 'status': 1}
    return list_detail.object_list(
        request,
        queryset = NewsEntry.objects.filter(**filters),
        template_name = 'submitter/news_per_show.html',
        template_object_name = 'object',
        extra_context = {
            'show': penta_show,
            'count': NewsEntry.objects.filter(**filters).count(),
            'tag_filters': filters,
        },
    )

def print_news_per_show(request, show_slug=None):
    """Return HTTP response of all NewsEntry() per PentaShow()"""

    penta_show = get_object_or_404(
        PentaShow,
        slug__iexact=show_slug
    )
    #filters = {'show': penta_show, 'status': 1}
    entries_per_category = {}
    categories = EntryCategory.objects.all()
    count = NewsEntry.objects.filter(show=penta_show, status=1).count()
    for category in categories:
        entries_per_category[category] = NewsEntry.objects.filter(
        show=penta_show,
        status=1,
        categories=category,
        )

    
    return render_to_response(
        'submitter/news_per_show_print.html',
        locals(),
        context_instance=RequestContext(request)
    )

@login_required(redirect_field_name='redirect_to')
def entry_category_create_and_update(request, entry_category_id=None):
    """Create and update EntryCategory()

    request:obj -- html request object
    entry_category_id:str -- id of the entry_category object
    """

    if entry_category_id is None:
        entry_category = None
    else:
        entry_category = get_object_or_404(
            EntryCategory,
            pk=entry_category_id,
        )
        title_main = _(u"Edit an News Entry Category")

    template = "create_update_form.html"
    form = EntryCategoryForm(
        data=request.POST.copy() or None,
        instance=entry_category,
    )

    if form.is_valid():
        try:
            entry_category = form.save()
            return HttpResponseRedirect(
                "/submit/category/")
        except:
            comment = _(u"Encountered an error while saving data.")

    extra_context = set_template_params(
        request,
        'entry_category',
        title_main=title_main,
        form=form,
    )

    return render_to_response(
        template,
        extra_context,
        context_instance=RequestContext(request),
    )

@login_required(redirect_field_name='redirect_to')
def news_entry_create_and_update(request, news_entry_id=None, form_type=None):
    """Create and update NewsEntry()

    request:obj -- html request object
    news_entry_id:str -- id of the news_entry object
    """

    next_shows = get_next_shows()

    # TODO (a8) if Pentashow CRUD exists, redirect there
    if not next_shows:
        raise Http404
    next_show = next_shows[0]

    if news_entry_id is None:
        news_entry = None
        title_main = _(u"Add an News Entry")
        show = next_show
    else:
        news_entry = get_object_or_404(
            NewsEntry,
            pk=news_entry_id,
        )
        title_main = _(u"Edit an News Entry")
        show = news_entry.show

    template = "create_update_form.html"

    helper = FormHelper()
    if form_type == 'short':
        news_entry = NewsEntry(show=next_show, status=1)
        form = NewsEntryFormShort(
            data=request.POST.copy() or None,
            instance=news_entry,
        )
        helper.form_class = 'input_short'
    else:
        form = NewsEntryFormFull(
            data=request.POST.copy() or None,
            initial={'show': next_shows[0].pk},
            instance=news_entry,
        )
        helper.form_class = 'input'

    # Add in a class and id
    helper.form_id = 'news_entry_cu'

    # add in a submit and reset button
    if news_entry_id:
        submit = Submit('Update','Update News Entry')
    else:
        submit = Submit('Add','Add News Entry')
    helper.add_input(submit)
    reset = Reset('reset','reset the form')
    helper.add_input(reset)
    if form.is_valid():
        #try:
        news_entry = form.save(commit=False)
        if not news_entry.author_id:
            news_entry.author = request.user.get_profile()
        #print "Tags: " + news_entry.tags_string
        news_entry = form.save()
        return HttpResponseRedirect(
            "/submit/news-per-next-show/")
        #except:
            #    comment = _(u"Encountered an error while saving data.")

    filters = {'show': show, 'status': 1}

    extra_context = set_template_params(
        request,
        'news_entry',
        title_main=title_main,
        form=form,
        helper=helper,
        hide_quick_form = True,
        show=show,
        tag_filters = filters,
    )

    return render_to_response(
        template,
        extra_context,
        context_instance=RequestContext(request),
    )

def news_entry_as_json(request, news_entry_id=None):
    """Return the NewsEntry() as JSON
    
    This will be used for auto update of the page.

    request:obj -- html request object
    news_entry_id:str -- id of the oldest news_entry object
    """
    news_entry = get_object_or_404(
        NewsEntry,
        pk=news_entry_id,
    )

    response = HttpResponse()
    response['Content-Type'] = "text/javascript; charset=utf-8"

    news_entry = NewsEntry.objects.get(
        pk=news_entry_id, status=1)  # no hidden or draft entries
    
    if not news_entry:
        raise Http404

    # TODO when Django 1.2 is released use natural_key here
    # http://docs.djangoproject.com/en/dev/topics/serialization/
    response.write(
        serializers.serialize(
            "json",
            [news_entry],
            ensure_ascii=True,
            fields=('title', 'external_url',
                    'absolute_url'),
            extras=('get_absolute_url',)
        )
    )
    return response

def news_entries_as_json(request, news_entry_id=None):
    """Return the NewsEntry() as JSON
    
    This will be used for auto update of the page.

    request:obj -- html request object
    news_entry_id:str -- id of the oldest news_entry object
    """
    news_entry = get_object_or_404(
        NewsEntry,
        pk=news_entry_id,
    )

    response = HttpResponse()
    response['Content-Type'] = "text/javascript; charset=utf-8"

    news_entries = NewsEntry.objects.filter(
        pk__gt=news_entry_id).filter(status=1)  # no hidden or draft entries
    for news_entry in news_entries:
        score = Vote.objects.get_score(news_entry)
        setattr(news_entry, 'score', score['score'])
        setattr(news_entry, 'num_votes', score['num_votes'])
        setattr(news_entry, 'page_shot_thumbnail',
                news_entry.page_screenshot.url_120x80,)

    # TODO when Django 1.2 is released use natural_key here
    # http://docs.djangoproject.com/en/dev/topics/serialization/
    response.write(
        serializers.serialize(
            "json",
            news_entries,
            ensure_ascii=True,
            fields=('title', 'page_screenshot', 
                    'absolute_url'),
            extras=('get_absolute_url','score', 'num_votes',
                    'page_shot_thumbnail',)
        )
    )
    return response

def penta_shows_as_json(request):
    """Return the last 12 PentaShow()s for Pentaradio shows as JSON
    
    This will be used for auto update of the page.

    request:obj -- html request object
    """

    response = HttpResponse()
    response['Content-Type'] = "text/javascript; charset=utf-8"

    penta_shows = PentaShow.objects.filter(
        show_type=1).order_by('-air_date')[:12]

    # TODO when Django 1.2 is released use natural_key here
    # http://docs.djangoproject.com/en/dev/topics/serialization/
    response.write(
        serializers.serialize(
            "json",
            penta_shows,
            ensure_ascii=True,
            fields=('title', 'slug', 'excerpt_html', 'description_html',
                   'air_date', 'production_date', 'recording_release_date',
                   'media'),
            extras=('get_absolute_url'),
        )
    )
    return response

def news_entries_per_show(request, penta_show_id=None):
    """Return the NewsEntry()s per PentaShow().id as JSON
    
    request:obj -- html request object
    penta_show_id:str -- id of the PentaShow() in question
    """
    penta_show = get_object_or_404(
        PentaShow,
        pk=penta_show_id,
    )

    response = HttpResponse()
    response['Content-Type'] = "text/javascript; charset=utf-8"

    news_entries = NewsEntry.objects.filter(
        show=penta_show, status=1)  # no hidden or draft entries

    for news_entry in news_entries:
        score = Vote.objects.get_score(news_entry)
        setattr(news_entry, 'score', score['score'])
        setattr(news_entry, 'num_votes', score['num_votes'])
        setattr(news_entry, 'page_shot_thumbnail',
                news_entry.page_screenshot.url_120x80,)
        setattr(news_entry, 'categories_list',
                news_entry.categories.values_list(),)
    # TODO when Django 1.2 is released use natural_key here
    # http://docs.djangoproject.com/en/dev/topics/serialization/
    response.write(
        serializers.serialize(
            "json",
            news_entries,
            ensure_ascii=True,
            fields=('title', 'slug', 'excerpt_html', 'body_html',
                    'page_screenshot', 'external_url', 'featured',
                    'status', 'submit_date', 'absolute_url',
                    'tags_string',
                   ),
            extras=('get_absolute_url','score', 'num_votes',
                    'page_shot_thumbnail', 'categories_list')
        )
    )
    return response

@login_required(redirect_field_name='redirect_to')
def list_my_submissions(request):
    """List all submissions by NewsEntry.author (or User())

    request:obj     -   Django request object
    """
    pass
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.