Example #1
0
def create_series(request, extra_context=None):
    """
    Creates a new series.
    """

    dtstart = None
    if request.method == 'POST':
        
        event_form = SeriesForm(request.POST) 
        recurrence_form = MonthlyReadingMultipleOccurrenceForm(request.POST)

        if event_form.is_valid() and recurrence_form.is_valid():
            # We are creating a new reading series, so give it the current user as the contact
            sr = event_form.save(commit=False)
            sr.contact = request.user
            sr.event_type = EventType.objects.get(pk=1)
            sr.site = CitySite.objects.get(pk=settings.SITE_ID)
            sr.save()
            event_form.save_m2m()

            # Saving this form saves the Series (and its underlying Event) and
            # creates the Readings (and their underlying Occurrences) with foreign keys
            # back to the Series (and Event).
            recurrence_form.save(sr)            
            
            tweet_message = ["New series: %s!" % sr.title] 
            
            _send_tweet(request, sr=sr, tweet_message=tweet_message)
            
            return HttpResponseRedirect(sr.get_absolute_url())
        else: # not valid
            # This is for logging only. The forms are already created and will be returned with errors for the user to correct.
            if settings.DEBUG:
                print "\n".join(["form is not valid.", "event_form errors = %s" % event_form.errors, "recurrence_form errors = %s" % recurrence_form.errors])
    else: 
        # not POST, so we create blank forms with a default start time of 5 pm today.
        if 'dtstart' in request.GET:
            try:
                dtstart = parser.parse(request.GET['dtstart'])
            except:
                pass
                
        if dtstart == None:
            today = datetime.today().date()
            dtstart = datetime(today.year, today.month, today.day, 17, 0, 0)

        event_form = SeriesForm()
        recurrence_form = MonthlyReadingMultipleOccurrenceForm(initial=dict(dtstart=dtstart))

    if extra_context is None:
        extra_context = {}
    context = RequestContext(request)
    for key, value in extra_context.items():
        context[key] = callable(value) and value() or value
        
    return render_to_response(
        "create_series.html",
        dict(dtstart=dtstart, event_form=event_form, recurrence_form=recurrence_form),
        context_instance=context
    )
Example #2
0
def edit_series(request, series_id=None):
    """Edits an existing series and its recurring occurrence.

    View an ``Event`` instance and optionally update either the event or its
    occurrences.

    Context parameters:

    event
        the event keyed by ``pk``
        
    event_form
        a form object for updating the event
        
    recurrence_form
        a form object for adding occurrences
    """
	

    series = get_object_or_404(Series, pk=series_id) # grab the existing series
    event_form = recurrence_form = None

    tweet_or_not = False # Start assuming we won't tweet, but if any of the changes occur that trigger a tweet, this value will change to true.
    tweet_message = ["%s has been updated!" % series.title]
        
    if request.method == 'POST':
        if '_update_event' in request.POST:
            # _update_event is the input for the form that updates the Series info.
            
            # For updating existing series, need to create a copy here because is_valid() will trigger 
            # model validation, which will update the model object with the new values
            # and we won't be able to tell what changed to determine whether we should tweet or not.
            # (A new series won't use old_sr for anything.)
            old_sr = copy.deepcopy(series) 
        
            event_form = SeriesForm(request.POST, instance=series)
            if event_form.is_valid():
                
                # If the name has changed, tweet about it:
                if event_form.cleaned_data["title"] != old_sr.title:
                    tweet_or_not = True
                    tweet_message.append("New name: %s" % series.title)               

                # If the location has changed, add that to the tweet.
                if old_sr.venue.id != event_form.cleaned_data["venue"].id:                    
                    tweet_or_not = True
                    tweet_message.append("New venue: %s" % event_form.cleaned_data["venue"])                                  
                
                # TODO Check to see if genre has changed.
                
                try:
                    event_form.save(series)
                except ValueError, ex:
                    messages.add_message(request, messages.ERROR, 'Problem updating %s. Value error %s. ' % (series.title, ex))
                    # TODO log this error and report it to admin
                    return HttpResponseRedirect(series.get_absolute_url())
                else:
                    messages.add_message(request, messages.SUCCESS, 'Updated %s. Thanks!' % (series.title,))               

                if not old_sr.regular and series.regular:
                    pass
                    # TODO If series is going from irregular to regular, need to create new readings with the new rrule.
                    # Need to call series.add_occurrences(), but where to get start_time and end_time? How to get new rrule?
                
                if tweet_or_not:
                    _send_tweet(request, sr=series, tweet_message=tweet_message)                    
                
                return HttpResponseRedirect(series.get_absolute_url())               
            else: # not valid
                messages.error(request, "Please correct the errors below.")
                return render_to_response('edit_series.html', { 'event_form': event_form, 'recurrence_form': recurrence_form or MonthlyReadingMultipleOccurrenceForm(initial=dict(dtstart=datetime.now())), 'event': series }, context_instance=RequestContext(request))

        elif '_add_occurrences' in request.POST:
            # _add_occurrences is the input for the form that adds new Reading occurrences to the Series.
            recurrence_form = MonthlyReadingMultipleOccurrenceForm(request.POST)
            if recurrence_form.is_valid():                
                # Check to see if the submitted recurrence rule is different
                # from the existing recurrence rule.
                # If it isn't, no need for an update.
                new_rr = recurrence_form.get_rrule()
                
                if new_rr != series.rrule:
                    # Hose all the old occurrences for this Series
                    Reading.objects.filter(series=series.id).filter(start_time__gte=datetime.today()).delete()
                    
                    # Create the new occurrences
                    try:
                        recurrence_form.save(series)
                    except ValueError, ex:
                        messages.add_message(request, messages.ERROR, 'Problem updating %s. Value error %s. ' % (series.title, ex))
                        # TODO log this error and report it to admin
                        return HttpResponseRedirect(series.get_absolute_url())
                    else:
                        messages.add_message(request, messages.SUCCESS, 'Updated %s. Thanks!' % (series.title,)) 
                    
                    tweet_or_not = True
                    tweet_message.append("New time: %s" % new_rr.text())
                    
                if tweet_or_not:
                    _send_tweet(request, sr=series, tweet_message=tweet_message)           
                    
                return HttpResponseRedirect(series.get_absolute_url())
            else: # not valid
                messages.error(request, "Please correct the errors below.")
                return render_to_response('edit_series.html', { 'event_form': SeriesForm(instance=series), 'recurrence_form': recurrence_form, 'event': series }, context_instance=RequestContext(request))