def create_event(request, calendar_id=None, calendar_slug=None, year=None, month=None, day=None, hour=None, minute=None, redirect=None): if calendar_id: calendar = get_object_or_404(Calendar, id=calendar_id) elif calendar_slug: calendar = get_object_or_404(Calendar, slug=calendar_slug) starttime = datetime.datetime(year=int(year),month=int(month),day=int(day),hour=int(hour),minute=int(minute)) endtime = starttime + datetime.timedelta(minutes=30) end_recur = endtime + datetime.timedelta(days=8) init_values = { 'start' : starttime, 'end' : endtime, 'end_recurring_period' : end_recur } form = EventForm(data=request.POST or None, initial=init_values) if form.is_valid(): event = form.save(commit=False) event.creator = request.user event.save() calendar.events.add(event) next = redirect or reverse('s_event', args=[event.id]) if 'next' in request.GET: next = _check_next_url(request.GET['next']) or next return HttpResponseRedirect(next) return render_to_response('schedule/create_event.html', { "form": form, "calendar": calendar }, context_instance=RequestContext(request))
def showDashboard(request): # user not logged in try: user_email = request.session['outlook_user_email'] access_token = request.session['outlook_access_token'] except KeyError: pass if request.user.is_anonymous(): return redirect('home') else: #logged in context = RequestContext(request) redirect_uri = request.build_absolute_uri(reverse('gettoken')) signin_url = get_signin_url(redirect_uri) if request.method == 'POST': profile = UserProfile.objects.get(user=request.user) user_calendar = Calendar.objects.get_calendar_for_object(profile) event_form = EventForm(data=request.POST) if event_form.is_valid: #save event in db event = event_form.save() #add the event to the users calendar user_calendar.events.add(event) else: HttpResponse(event_form.errors) else: event_form = EventForm() return render(request, 'dashboard/main_dashboard.html', {'event_form' : event_form,'signin_url' : signin_url,})
def test_event_form(self): now = datetime.datetime.now() data = {'start_0': now.strftime('%Y-%m-%d'), 'start_1': '00:00', 'end_0': (now + datetime.timedelta(days=1)).strftime('%Y-%m-%d'), 'end_1': '00:00', 'title': u'some title'} form = EventForm(data=data) validated = form.is_valid() self.assertTrue(validated) data['end_0'] = (now - datetime.timedelta(days=1)).strftime('%Y-%m-%d') form = EventForm(data=data) validated = form.is_valid() self.assertFalse(validated) self.assertEqual(len(form.non_field_errors()), 1) self.assertEqual(form.non_field_errors()[0], u"The end time must be later than start time.") del data['end_0'] del data['end_1'] del data['start_0'] del data['start_1'] form = EventForm(data=data) validated = form.is_valid() self.assertFalse(validated) self.assertEqual(len(form.non_field_errors()), 0) self.assertEqual(len(form.errors), 2) self.assertEqual(len(form.errors['end']), 1) self.assertEqual(form.errors['end'][0], u"This field is required.") self.assertEqual(len(form.errors['start']), 1) self.assertEqual(form.errors['start'][0], u"This field is required.")
def today(request): """ This view has to get all the events from today onwards for the current user, up to a point (for now its a week), it then must generate two event lists: today, and upcoming and send those lists back to the today template. """ user = request.user print "User is authenticated: " + str(user.is_authenticated()) print "Getting events for user " + user.username if request.method == 'POST': print "POST data detected " if 'confirm_remove' in request.POST: print "Remove request detected" event_id = request.POST['event_id'] event = Event.objects.get(pk=event_id) event.delete() if 'add_event' in request.POST: print "Add request detected" event_form = EventForm(request.POST) if event_form.is_valid(): print "Its valid" new_event = event_form.save(commit=False) new_event.owner = request.user new_event.save() del event_form print "Saved" else: print "Its not valid" try: event_form except: event_form = EventForm() today = datetime.now().date() today_plus_7 = today + timedelta(days=7) events = Event.objects.filter(owner=user.pk, date__gte=today, date__lte=today_plus_7).order_by('date', 'begin_time') print "Total number of events: " + str(events.count()) todays_events = events.filter(date=today) incoming_events = events.exclude(date=today) return render_to_response('today.templ', {'todays_events': todays_events, 'incoming_events': incoming_events, 'event_form': event_form}, context_instance=RequestContext(request))
def ajax_create_event(request, calendar_slug): if not request.is_ajax() or not request.POST: return HttpResponseBadRequest() form = EventForm(data=request.POST) if form.is_valid(): event = form.save(commit=False) import pdb; pdb.set_trace() event.creator = request.user calendar = get_object_or_404(Calendar, slug=calendar_slug) event.calendar = calendar event.save() return HttpResponse() else: return HttpResponseBadRequest(json.dumps(form.errors), content_type="application/json")
def create_or_edit_event(request, calendar_id=None, event_id=None, redirect=None): """ This function, if it recieves a GET request or if given an invalid form in a POST request it will generate the following response * Template: schedule/create_event.html * Context: * form: an instance of EventForm * calendar: a Calendar with id=calendar_id If this form recieves an event_id it will edit the event with that id, if it recieves a calendar_id and it is creating a new event it will add that event to the calendar with the id calendar_id If it is given a valid form in a POST request it will redirect with one of three options, in this order # Try to find a 'next' GET variable # If the key word argument redirect is set # Lastly redirect to the event detail of the recently create event """ instance = None if event_id: instance = get_object_or_404(Event, id=event_id) calendar = None if calendar_id is not None: calendar = get_object_or_404(Calendar, id=calendar_id) if instance: form = EventForm(data=request.POST or None, instance=instance) else: starttime = datetime.datetime.now() endtime = starttime + datetime.timedelta(minutes=60) end_recur = endtime + datetime.timedelta(days=8) init_values = {"start": starttime, "end": endtime, "end_recurring_period": end_recur} form = EventForm(data=request.POST or None, initial=init_values) if form.is_valid(): event = form.save(commit=False) if instance is None: event.creator = request.user event.save() if calendar is not None and instance is None: calendar.events.add(event) next = redirect or reverse("s_event", args=[event.id]) if "next" in request.GET: next = _check_next_url(request.GET["next"]) or next return HttpResponseRedirect(next) return render_to_response( "schedule/create_event.html", {"form": form, "calendar": calendar}, context_instance=RequestContext(request) )
def create_event(request): if request.method not in ['POST', 'GET']: return Error.http405() elif request.method == 'GET': form = EventForm() return render(request, 'event.htm', {'form': form}) elif request.method == 'POST': form = EventForm(request.POST) if form.is_valid(): try: e = Event(name=form.cleaned_data['name'], color=form.cleaned_data['color'], count=form.cleaned_data['count'], created=datetime.now()) e.save() return Message.object_created(e.id) except Exception as e: return Error.debug(str(e))
def create_or_edit_event(request, calendar_id=None, event_id=None, redirect=None): """ This function, if it receives a GET request or if given an invalid form in a POST request it will generate the following response * Template: schedule/create_event.html * Context: * form: an instance of EventForm * calendar: a Calendar with id=calendar_id If this form receives an event_id it will edit the event with that id, if it recieves a calendar_id and it is creating a new event it will add that event to the calendar with the id calendar_id If it is given a valid form in a POST request it will redirect with one of three options, in this order # Try to find a 'next' GET variable # If the key word argument redirect is set # Lastly redirect to the event detail of the recently create event """ instance = None if event_id: instance = get_object_or_404(Event, id=event_id) calendar = None if calendar_id is not None: calendar = get_object_or_404(Calendar, id=calendar_id) form = EventForm(data=request.POST or None, instance=instance, hour24=True) if form.is_valid(): event = form.save(commit=False) if instance is None: event.creator = request.user event.save() if calendar is not None and instance is None: calendar.events.add(event) next = redirect or reverse('s_event', args=[event.id]) if 'next' in request.GET: next = _check_next_url(request.GET['next']) or next return HttpResponseRedirect(next) return render_to_response('schedule/create_event.html', { "form": form, "calendar": calendar }, context_instance=RequestContext(request))
def create_or_edit_event(request, calendar_id=None, event_id=None, redirect=None): """ This function, if it recieves a GET request or if given an invalid form in a POST request it will generate the following response * Template: schedule/create_event.html * Context: * form: an instance of EventForm * calendar: a Calendar with id=calendar_id If this form recieves an event_id it will edit the event with that id, if it recieves a calendar_id and it is creating a new event it will add that event to the calendar with the id calendar_id If it is given a valid form in a POST request it will redirect with one of three options, in this order # Try to find a 'next' GET variable # If the key word argument redirect is set # Lastly redirect to the event detail of the recently create event """ instance = None if event_id: instance = get_object_or_404(Event, id=event_id) calendar = None if calendar_id is not None: calendar = get_object_or_404(Calendar, id=calendar_id) if instance: form = EventForm(data=request.POST or None, instance=instance) else: starttime = datetime.datetime.now() endtime = starttime + datetime.timedelta(minutes=60) end_recur = endtime + datetime.timedelta(days=8) init_values = { 'start': starttime, 'end': endtime, 'end_recurring_period': end_recur } form = EventForm(data=request.POST or None, initial=init_values) if form.is_valid(): event = form.save(commit=False) if instance is None: event.creator = request.user event.save() if calendar is not None and instance is None: calendar.events.add(event) next = redirect or reverse('s_event', args=[event.id]) if 'next' in request.GET: next = _check_next_url(request.GET['next']) or next return HttpResponseRedirect(next) return render_to_response('schedule/create_event.html', { "form": form, "calendar": calendar }, context_instance=RequestContext(request))
def calendar_initialize(request): today = time_zone_user(request.user) if request.user.is_teacher: teacher = Teacher.objects.get(user=request.user) relationships = Relationship.objects.filter(parcours__teacher=teacher, date_limit__gte=today).exclude(date_limit=None) parcourses = Parcours.objects.filter(teacher=teacher,is_trash=0) calendars = Calendar.objects.filter(user=request.user) form = EventForm(request.user, request.POST or None) nb_teacher_level = teacher.levels.count() communications = Communication.objects.values('id', 'subject', 'texte').filter(active=1) context = {'form': form, 'relationships': relationships, 'parcourses': parcourses, 'calendars': calendars,'nb_teacher_level' :nb_teacher_level , 'communications' : communications , 'teacher': teacher} else: student = Student.objects.get(user=request.user.id) relationships = Relationship.objects.filter(Q(is_publish = 1)|Q(start__lte=today), students=student, date_limit__gte=today).order_by("date_limit") exercise_tab = [] for r in relationships: if r not in exercise_tab: exercise_tab.append(r.exercise) num = 0 for e in exercise_tab : if Studentanswer.objects.filter(student=student, exercise = e).count() > 0 : num += 1 exercises = [] studentanswers = Studentanswer.objects.filter(student = student) for studentanswer in studentanswers: if not studentanswer.exercise in exercises: exercises.append(studentanswer.exercise) relationships_in_late = Relationship.objects.filter(Q(is_publish = 1)|Q(start__lte=today), students=student, is_evaluation=0, date_limit__lt=today).exclude(exercise__in=exercises).order_by("date_limit") nb_relationships = Relationship.objects.filter(Q(is_publish = 1)|Q(start__lte=today), students=student, date_limit__gte=today).count() try : ratio = int(num/nb_relationships*100) except : ratio = 0 ratiowidth = int(0.9*ratio) student = Student.objects.get(user=request.user) parcours = Parcours.objects.filter(students = student,is_trash=0) context = {'student' : student , 'relationships' : relationships , 'ratio' : ratio , 'ratiowidth' : ratiowidth , 'relationships_in_late' : relationships_in_late , } return render(request, "schedule/base.html" , context )
def create_event(request, calendar_id, year, month, day, hour, minute, redirect=None): calendar = get_object_or_404(Calendar, id=calendar_id) starttime = datetime.datetime(year=int(year), month=int(month), day=int(day), hour=int(hour), minute=int(minute)) endtime = starttime + datetime.timedelta(minutes=30) end_recur = endtime + datetime.timedelta(days=8) init_values = { 'start': starttime, 'end': endtime, 'end_recurring_period': end_recur } form = EventForm(data=request.POST or None, initial=init_values) if form.is_valid(): event = form.save(commit=False) event.creator = request.user event.save() calendar.events.add(event) next = redirect or reverse('s_event', args=[event.id]) if 'next' in request.GET: next = _check_next_url(request.GET['next']) or next return HttpResponseRedirect(next) return render_to_response('schedule/create_event.html', { "form": form, "calendar": calendar }, context_instance=RequestContext(request))
def today(request): """ This view has to get all the events from today onwards for the current user, up to a point (for now its a week), it then must generate two event lists: today, and upcoming and send those lists back to the today template. """ user = request.user print "User is authenticated: " + str(user.is_authenticated()) print "Getting events for user " + user.username if request.method == 'POST': print "POST data detected " if 'confirm_remove' in request.POST: print "Remove request detected" event_id = request.POST['event_id'] event = Event.objects.get(pk=event_id) event.delete() if 'add_event' in request.POST: print "Add request detected" event_form = EventForm(request.POST) if event_form.is_valid(): print "Its valid" new_event = event_form.save(commit=False) new_event.owner = request.user new_event.save() del event_form print "Saved" else: print "Its not valid" try: event_form except: event_form = EventForm() today = datetime.now().date() today_plus_7 = today + timedelta(days=7) events = Event.objects.filter(owner=user.pk, date__gte=today, date__lte=today_plus_7).order_by( 'date', 'begin_time') print "Total number of events: " + str(events.count()) todays_events = events.filter(date=today) incoming_events = events.exclude(date=today) return render_to_response('today.templ', { 'todays_events': todays_events, 'incoming_events': incoming_events, 'event_form': event_form }, context_instance=RequestContext(request))
def create_or_edit_event(request, calendar_slug, event_id=None, next=None, template_name='schedule/create_event.html'): """ This function, if it receives a GET request or if given an invalid form in a POST request it will generate the following response Template: schedule/create_event.html Context Variables: form: an instance of EventForm calendar: a Calendar with id=calendar_id if this function gets a GET request with ``year``, ``month``, ``day``, ``hour``, ``minute``, and ``second`` it will auto fill the form, with the date specifed in the GET being the start and 30 minutes from that being the end. If this form receives an event_id it will edit the event with that id, if it recieves a calendar_id and it is creating a new event it will add that event to the calendar with the id calendar_id If it is given a valid form in a POST request it will redirect with one of three options, in this order # Try to find a 'next' GET variable # If the key word argument redirect is set # Lastly redirect to the event detail of the recently create event """ date = coerce_date_dict(request.GET) initial_data = None if date: try: start = datetime.datetime(**date) initial_data = { "start": start, "end": start + datetime.timedelta(minutes=30) } except TypeError: raise Http404 except ValueError: raise Http404 instance = None if event_id is not None: instance = get_object_or_404(Event, id=event_id) calendar = get_object_or_404(Calendar, slug=calendar_slug) form = EventForm(data=request.POST or None, instance=instance, hour24=True, initial=initial_data) if form.is_valid(): event = form.save(commit=False) if instance is None: event.creator = request.user event.calendar = calendar event.save() next = next or reverse('event', args=[event.id]) if 'next' in request.GET: next = check_next_url(request.GET['next']) or next return HttpResponseRedirect(next) return render_to_response(template_name, { "form": form, "calendar": calendar }, context_instance=RequestContext(request))
def test_event_form(self): now = datetime.datetime.now() data = { "start_0": now.strftime("%Y-%m-%d"), "start_1": "00:00", "end_0": (now + datetime.timedelta(days=1)).strftime("%Y-%m-%d"), "end_1": "00:00", "title": "some title", } form = EventForm(data=data) validated = form.is_valid() self.assertTrue(validated) data["end_0"] = (now - datetime.timedelta(days=1)).strftime("%Y-%m-%d") form = EventForm(data=data) validated = form.is_valid() self.assertFalse(validated) self.assertEqual(len(form.non_field_errors()), 1) self.assertEqual( form.non_field_errors()[0], "The end time must be later than start time." ) del data["end_0"] del data["end_1"] del data["start_0"] del data["start_1"] form = EventForm(data=data) validated = form.is_valid() self.assertFalse(validated) self.assertEqual(len(form.non_field_errors()), 0) self.assertEqual(len(form.errors), 2) self.assertEqual(len(form.errors["end"]), 1) self.assertEqual(form.errors["end"][0], "This field is required.") self.assertEqual(len(form.errors["start"]), 1) self.assertEqual(form.errors["start"][0], "This field is required.")
def create_or_edit_event(request, calendar_slug, event_id=None, next=None): date = coerce_date_dict(request.GET) initial_data = None if date: try: start = datetime.datetime(**date) initial_data = { "start": start, "end": start + datetime.timedelta(minutes=30) } except TypeError: raise Http404 except ValueError: raise Http404 instance = None if event_id is not None: instance = get_object_or_404(Event, id=event_id) calendar = get_object_or_404(Calendar, slug=calendar_slug) data = request.POST.copy() if data: data["title"] = data["oncall"] + "," + data["fallback"] form = EventForm(data=data or None, instance=instance, initial=initial_data) users = User.objects.all() groups = Group.objects.all() if request.method == 'POST': if form.is_valid(): event = form.save(commit=False) if instance is None: event.creator = request.user event.calendar = calendar event.save() return HttpResponseRedirect( reverse('calendar_details', kwargs={'calendar_slug': calendar.slug})) if instance is not None: officers = instance.title.split(",") data["oncall"] = officers[0] data["fallback"] = officers[1] data["start_ymd"] = instance.start.date().isoformat() data["start_hour"] = instance.start.time().strftime("%H:%M") data["end_ymd"] = instance.end.date().isoformat() data["end_hour"] = instance.end.time().strftime("%H:%M") if instance.end_recurring_period: data["recurr_ymd"] = instance.end_recurring_period.date( ).isoformat() data["description"] = instance.description data["rule"] = (instance.rule and instance.rule.id) or "" next = get_next_url(request, next) context = { "data": data, "calendar": calendar, "next": next, "users": users, "groups": groups, "form": form } template = 'event/edit.html' return render(request, template, context)
def test_event_form(self): now = datetime.datetime.now() data = { 'start_0': now.strftime('%Y-%m-%d'), 'start_1': '00:00', 'end_0': (now + datetime.timedelta(days=1)).strftime('%Y-%m-%d'), 'end_1': '00:00', 'title': 'some title' } form = EventForm(data=data) validated = form.is_valid() self.assertTrue(validated) data['end_0'] = (now - datetime.timedelta(days=1)).strftime('%Y-%m-%d') form = EventForm(data=data) validated = form.is_valid() self.assertFalse(validated) self.assertEqual(len(form.non_field_errors()), 1) self.assertEqual(form.non_field_errors()[0], "The end time must be later than start time.") del data['end_0'] del data['end_1'] del data['start_0'] del data['start_1'] form = EventForm(data=data) validated = form.is_valid() self.assertFalse(validated) self.assertEqual(len(form.non_field_errors()), 0) self.assertEqual(len(form.errors), 2) self.assertEqual(len(form.errors['end']), 1) self.assertEqual(form.errors['end'][0], "This field is required.") self.assertEqual(len(form.errors['start']), 1) self.assertEqual(form.errors['start'][0], "This field is required.")