Ejemplo n.º 1
0
 def test_was_published_recently_with_old_event(self):
     """
     was_published_recently() should return False for events whose pub_date
     is older than 1 day
     """
     old_event = Event(pub_date=timezone.now() - datetime.timedelta(days=30))
     self.assertEqual(old_event.was_published_recently(), False)
Ejemplo n.º 2
0
 def test_has_not_registration_limit(self):
     event = Event("Name", "name", "Location", EventType("Type"),
                     starts = datetime(2009, 1, 6, 12, 0),
                     ends = datetime(2009, 1, 6, 12, 42),
                     registration_starts = datetime(2009, 1, 6, 11, 30),
                     registration_limit = 0)
     self.assertEqual(event.has_registration_limit(), False)
Ejemplo n.º 3
0
def newstore(request):
    context = {}
    if request.method == "POST":
        store_name = request.POST['store_name']
        desc = request.POST['description']
        date = request.POST['date']
        time = request.POST['time']
        poster = request.FILES['poster']
        location = request.POST['location']
        event = Event(shop=request.user,
                      Event_name=store_name,
                      Event_description=desc,
                      date=date,
                      time=time,
                      Event_poster=poster,
                      location=location)
        event.save()
        tickets = request.POST.getlist('ticket')
        for ticket in tickets:
            data = ticket.split(',')
            Ticket.objects.create(event=event,
                                  name=data[0],
                                  quantity=data[1],
                                  price=data[2])
        context = {'success': True}
    return render(request, 'dashboard/newstore.html', context)
Ejemplo n.º 4
0
 def test_was_published_recently_with_recent_event(self):
     """
     was_published_recently() should return True for events whose pub_date
     is within the last day
     """
     recent_event = Event(pub_date=timezone.now() - datetime.timedelta(hours=1))
     self.assertEqual(recent_event.was_published_recently(), True)
Ejemplo n.º 5
0
def trigger_event(group_name, event_name):

    event_source = Group.objects.get(name=group_name)
    event_definition = EventDefinition.objects.get(name=event_name)
    event_write = Event(event_definition=event_definition,
                        device_group=event_source)
    event_write.save()
    # completion of automation writes an event which could trigger another automation
    automations = Automation.objects.filter(cause=event_definition,
                                            source_group=event_source)
    for automation in automations:
        dummy_result = [None]
        event_target = automation.target_group
        config_id = str(event_target.get_config_id())
        # initialize automation chain with triggered automation
        automation_chain = signature(automation.effect,
                                     args=dummy_result,
                                     kwargs={'config_id': config_id})
        a = automation
        while a.next:
            a = a.next
            automation_chain |= (signature(
                'events.tasks.evaluate_event',
                kwargs={
                    'group_name': group_name,
                    'event_name': event_name
                }) | signature(a.effect, kwargs={'config_id': config_id}))
        automation_chain.apply_async()
Ejemplo n.º 6
0
    def form_valid(self, form):
        # set the submitter to be the current user
        form.instance.user = self.request.user

        # save the posted message
        self.object = form.save()

        # add event to the Event table
        # build a JSON fragment out of the new song info
        event_info = {
            "user": self.object.user.username,
            "time": TimeFilter(self.object.time),
            "text": self.object.text,
        }
        if self.object.user.is_superuser:
            event_info['user_class'] = "superuser"
        elif self.object.user.is_staff:
            event_info['user_class'] = "staff"
        elif self.object.user.is_active:
            event_info['user_class'] = "default"
        else:
            event_info['user_class'] = "none"

        event = Event(audience_type=Event.AUTHENTICATED, event_type="CHAT", event_value=json.dumps(event_info))
        event.save()

        # return 204 NO CONTENT (prevents redirect)
        return HttpResponse(status=204)
Ejemplo n.º 7
0
    def setUp(self):
        self.factory = RequestFactory(HTTP_HOST='test.com')

        now = timezone.now()
        test_fair = Fair(name="Armada 2000", current=True)
        test_fair.save()

        self.event = Event(fair=test_fair,
                           name='test',
                           event_start=now,
                           event_end=now,
                           registration_start=now,
                           registration_end=now,
                           registration_last_day_cancel=now,
                           public_registration=True,
                           published=True)
        self.event.save()
        self.hidden_event = Event(fair=test_fair,
                                  name='hidden event',
                                  event_start=now,
                                  event_end=now,
                                  registration_start=now,
                                  registration_end=now,
                                  registration_last_day_cancel=now,
                                  public_registration=False)
        self.hidden_event.save()
        self.request = self.factory.get('/api/events/')
Ejemplo n.º 8
0
class TestOccurrencePool(TestCase):
    def setUp(self):
        rule = Rule(frequency="WEEKLY")
        rule.save()
        cal = Calendar(name="MyCal")
        cal.save()
        data = {
            'title': 'Recent Event',
            'start': datetime.datetime(2008, 1, 5, 8, 0),
            'end': datetime.datetime(2008, 1, 5, 9, 0),
            'end_recurring_period': datetime.datetime(2008, 5, 5, 0, 0),
            'rule': rule,
            'calendar': cal
        }
        self.recurring_event = Event(**data)
        self.recurring_event.save()

    def testPeriodFromPool(self):
        """
            Test that period initiated with occurrence_pool returns the same occurrences as "straigh" period
            in a corner case whereby a period's start date is equal to the occurrence's end date
        """
        start = datetime.datetime(2008, 1, 5, 9, 0)
        end = datetime.datetime(2008, 1, 5, 10, 0)
        parent_period = Period(Event.objects.all(), start, end)
        period = Period(parent_period.events, start, end,
                        parent_period.get_persisted_occurrences(),
                        parent_period.occurrences)
        self.assertEquals(parent_period.occurrences, period.occurrences)
Ejemplo n.º 9
0
def active(request):
    """
    Renders default/program template:
    The list of all active (published and not yet expired) news,
    """

    news = News.get_frontpage_news()
    events = Event.get_frontpage_events()
    daytime_events = Event.get_frontpage_daytime_events()

    sticky_news = News.get_sticky_news()

    # get latest albums from gallery
    latest = Album.objects.filter(category=Album.LIVE).order_by("-date_of_event")[:3]

    return render(
        request,
        "news.html",
        {
            "news": news,
            "events": events,
            "daytime_events": daytime_events,
            "latest": latest,
            "sticky_news": sticky_news,
        },
    )
Ejemplo n.º 10
0
    def setUp(self):
        user = UserModel.objects.create_user(name="test test",
                                             password="******",
                                             email="*****@*****.**")
        self.client = APIClient()
        self.client.force_authenticate(user=user)

        future_date_1 = datetime.now() + timedelta(days=+30)
        future_date_2 = datetime.now() + timedelta(days=+37)
        past_date_1 = datetime.now() + timedelta(days=+37)
        self.events = Event.objects.bulk_create([
            Event(
                name="Powerwolf in Wroclaw",
                event_date=future_date_1,
                place="Wroclaw",
                description="lorem ipsum",
            ),
            Event(
                name="Powerwolf in Wroclaw",
                event_date=future_date_2,
                place="Wroclaw",
                description="lorem ipsum",
            ),
            Event(
                name="Powerwolf in Wroclaw",
                event_date=past_date_1,
                place="Wroclaw",
                description="lorem ipsum",
            ),
        ])
Ejemplo n.º 11
0
    def setUp(self):
        weekly = Rule(frequency="WEEKLY")
        weekly.save()
        daily = Rule(frequency="DAILY")
        daily.save()
        cal = Calendar(name="MyCal")
        cal.save()

        self.event1 = Event(**{
                'title': 'Weekly Event',
                'start': datetime.datetime(2009, 4, 1, 8, 0),
                'end': datetime.datetime(2009, 4, 1, 9, 0),
                'end_recurring_period': datetime.datetime(2009, 10, 5, 0, 0),
                'rule': weekly,
                'calendar': cal
               })
        self.event1.save()
        self.event2 = Event(**{
                'title': 'Recent Event',
                'start': datetime.datetime(2008, 1, 5, 9, 0),
                'end': datetime.datetime(2008, 1, 5, 10, 0),
                'end_recurring_period': datetime.datetime(2009, 5, 5, 0, 0),
                'rule': daily,
                'calendar': cal
               })
        self.event2.save()
Ejemplo n.º 12
0
    def create_event(self,
                     number,
                     series=None,
                     location=None,
                     start_date=None,
                     end_date=None,
                     is_published=True):
        """Create event object.

        Args:
            number: Identifier of the event (int).
            location: Location of the event (Location).
            start_date: Date of the event start (Date).
            end_date: Date of the event end (Date).
            is_published: Boolean if event is public (bool).

        Returns:
            Event object.
        """
        if start_date is None:
            start_date = date.today()
        if end_date is None:
            end_date = date.today()
        event = Event(
            name="Event {}".format(number),
            series=series,
            description="Description for Event {}".format(number),
            start_date=start_date,
            end_date=end_date,
            location=location,
            is_published=is_published,
        )
        event.save()
        return event
Ejemplo n.º 13
0
    def setUp(self):
        weekly = Rule(frequency="WEEKLY")
        weekly.save()
        daily = Rule(frequency="DAILY")
        daily.save()
        cal = Calendar(name="MyCal")
        cal.save()

        self.event1 = Event(
            **{
                'title': 'Weekly Event',
                'start': datetime.datetime(2009, 4, 1, 8, 0),
                'end': datetime.datetime(2009, 4, 1, 9, 0),
                'end_recurring_period': datetime.datetime(2009, 10, 5, 0, 0),
                'rule': weekly,
                'calendar': cal
            })
        self.event1.save()
        self.event2 = Event(
            **{
                'title': 'Recent Event',
                'start': datetime.datetime(2008, 1, 5, 9, 0),
                'end': datetime.datetime(2008, 1, 5, 10, 0),
                'end_recurring_period': datetime.datetime(2009, 5, 5, 0, 0),
                'rule': daily,
                'calendar': cal
            })
        self.event2.save()
Ejemplo n.º 14
0
def create_tech_event(request):
    user = request.user
    if user.role_set.filter(id=1):
        if request.method == 'POST':
            form = EventForm(request.POST)
            if form.is_valid():
                name = form.cleaned_data['name']
                description = form.cleaned_data['description']
                event_type = 1
                user_id = request.user.id
                date = form.cleaned_data['date']
                event = Event(user=request.user,
                              name=name,
                              description=description,
                              type=event_type,
                              date=date)
                event.save()
                return redirect('http://127.0.0.1:8000/custom_auth/profile/')
            else:
                return render(request, 'new_event.html', {'form': form})
        else:
            form = EventForm()
            return render(request, "new_event.html", {'form': form})
    else:
        return render(request, 'not_permitted.html')
Ejemplo n.º 15
0
    def test_event_visibility(self):
        response = testing.get_public_client().get(reverse('event_index'))
        self.assertEqual(200, response.status_code)

        author = testing.create_user()
        venue = Venue.create_for_testing()

        event_a = Event.create_for_testing(author, venue)
        event_a.reviewed = True
        event_a.save()

        event_b = Event.create_for_testing(author, venue)
        event_b.reviewed = False
        event_b.save()

        # The general public should see only the reviewed event.
        response = testing.get_public_client().get(reverse('event_index'))
        self.assertEqual(200, response.status_code)
        self.assertEqual(1, len(response.context['events']))

        # The author should see both.
        response = testing.get_user_client(author).get(reverse('event_index'))
        self.assertEqual(200, response.status_code)
        self.assertEqual(2, len(response.context['events']))

        # Another regular user should also see both.
        response = testing.get_user_client().get(reverse('event_index'))
        self.assertEqual(200, response.status_code)
        self.assertEqual(2, len(response.context['events']))
Ejemplo n.º 16
0
 def set_rating(self, user, val, activity):
     """
     Set a user's Vote on a certain object. If the user has previously voted
     on that object, it removes the old vote.
     """
     Vote.objects.record_vote(self, user, val)
     Event.record_event(self, user, activity)
Ejemplo n.º 17
0
class TestOccurrencePool(TestCase):

    def setUp(self):
        rule = Rule(frequency="WEEKLY")
        rule.save()
        cal = Calendar(name="MyCal")
        cal.save()
        data = {
                'title': 'Recent Event',
                'start': datetime.datetime(2008, 1, 5, 8, 0),
                'end': datetime.datetime(2008, 1, 5, 9, 0),
                'end_recurring_period': datetime.datetime(2008, 5, 5, 0, 0),
                'rule': rule,
                'calendar': cal
               }
        self.recurring_event = Event(**data)
        self.recurring_event.save()

    def testPeriodFromPool(self):
        """
            Test that period initiated with occurrence_pool returns the same occurrences as "straigh" period
            in a corner case whereby a period's start date is equal to the occurrence's end date
        """
        start = datetime.datetime(2008, 1, 5, 9, 0)
        end = datetime.datetime(2008, 1, 5, 10, 0)
        parent_period = Period(Event.objects.all(), start, end)
        period = Period(parent_period.events, start, end, parent_period.get_persisted_occurrences(), parent_period.occurrences)
        self.assertEquals(parent_period.occurrences, period.occurrences)
Ejemplo n.º 18
0
def event(request):
    model = Event
    event = Event.objects.all()

    # Handle file upload
    if request.method == 'POST':
        form = EventForm(request.POST , request.FILES)
        if form.is_valid():
            event = Event(user=request.user, snap=request.FILES['snap'], eventtype = request.POST['eventtype'],duration = request.POST['duration'],dresscode = request.POST['duration'],date_event = request.POST['date_event'], description = request.POST['description'], place = request.POST['place'],)
            event.save()

            # Redirect to the document list after POST
            return redirect('/events/')
    else:
        form = EventForm() # A empty, unbound form
    
    event = Event.objects.all()
   # Load documents for the list page
    
    # Render list page with the documents and the form
    return render_to_response(
        'events/event.html',
        { 'event': event,'form': form,},
        context_instance=RequestContext(request)
    )
Ejemplo n.º 19
0
def create_event(request):
    if request.method == 'POST':
        form = EventCreateForm(request.POST, target_user=request.user)
        if form.is_valid():
            title = form.cleaned_data['name']
            description = form.cleaned_data['description']
            event = Event(name=title,
                          description=description,
                          created_by=request.user)
            event.save()
            membership = EventMembership(user=request.user,
                                         event=event,
                                         is_organizer=True,
                                         is_creator=True)
            membership.save()
            messages.success(
                request,
                f"Event successfully created!  Click your event Event Settings button in the "
                f"organizer toolbar to add more members.")
            return redirect('general-home')
    else:
        context = {
            'form': EventCreateForm(target_user=request.user),
            'title': 'New Event'
        }
        return render(request, 'events/create_event.html', context=context)
Ejemplo n.º 20
0
def eventView(request):
    events = Event.objects.all()
    try:
        event_id = request.GET['id']
        Event.objects.filter(id=event_id).delete()
    except MultiValueDictKeyError:
        pass
    if request.method == 'POST':
        form = EventForm(request.POST)
        if form.is_valid():
            name = request.POST['name']
            venue = request.POST['venue']
            date = request.POST['date']
            time = request.POST['time']
            new_event = Event(name=name,
                              venue=venue,
                              date=date,
                              time=time)
            new_event.save()
    else:
        form = EventForm()
    context = {
        'events': events,
        'form': form,
        }
    return render(request, 'users/events.html', context)
Ejemplo n.º 21
0
def save_event(request):
    """ Create a new event """
    print "In Save Event"
    if request.method != "POST":
        print "Save brew received a non post"
        return HttpResponseRedirect(reverse("events_userhome"))

    name = request.POST.get('event_name')
    description = request.POST.get("event_description")
    
    # On empty POST request, return to user home.
    if(name.strip() == "" and description.strip() == ""):
        print "Empty form received"
        return HttpResponseRedirect(reverse("events_userhome"))

    # Create a new event and save it.
    new_event = Event()
    new_event.name = name
    new_event.description = description
    new_event.save()
    print "New Event Created ", new_event.ident
    print type(new_event.ident), str(new_event.ident)
    # Save the user as the host of the new event
    user = request.user.get_profile()
    admin = Host()
    admin.uid = user
    admin.eid = new_event
    admin.save()
    return HttpResponseRedirect(reverse("events.views.event",
                                        args=(new_event.ident,)))
Ejemplo n.º 22
0
    def _save_recurring_events(self, event: dict, super_event: Event):
        if not event['days']:
            raise FunException(
                f"{event['origin_id']} is missing the weekdays it repeats on.")

        recurring_dates = self._create_recurring_event_dates(
            event["start_time"], event["end_time"], event["days"])
        time_from = self._split_time(event.pop('time_from'),
                                     event['origin_id'])
        time_to = self._split_time(event.pop('time_to'), event['origin_id'])
        recurring_datetimes = [(i.replace(hour=time_from[0],
                                          minute=time_from[1]),
                                i.replace(hour=time_to[0], minute=time_to[1]))
                               for i in recurring_dates]
        for i in recurring_datetimes:
            single_event = deepcopy(event)
            single_event[
                'origin_id'] = f"{single_event['origin_id']}_{i[0].strftime('%d%m%Y')}"
            single_event['start_time'] = i[0]
            single_event['end_time'] = i[1]
            single_event['super_event'] = super_event
            self.save_event(single_event)

        super_event.save()
        logger.info(
            f'{super_event.name} saved with {super_event.sub_events.count()} recurring sub events'
        )
Ejemplo n.º 23
0
def new_event_submit(request):
    checked_checklist_items = request.POST.getlist('checklist_items')
    name = request.POST['name']
    description = request.POST['description']
    price = request.POST['price']

    try:
        event = Event(
            name=name,
            description=description,
            price=price
        )

        event.save()

        for item in checked_checklist_items:
            event.checklist_items.add(item)

        messages.success(request, "Your event was saved successfully.")
    except:
        e = sys.exc_info()[0]
        messages.error(request, "There was an error saving your event.")
        print(e)

    return redirect('events:index')
Ejemplo n.º 24
0
def make_json(request, start=None):
    if not start:
        start = utc.localize(datetime.utcnow()).astimezone(
            request.site.tz).date()
    continuing = Event.all().filter('status = ', 'approved').filter(
        'multiday =', True).filter('continues =', str(start))
    events_soon = Event.all().filter('status = ',
                                     'approved').order('local_start').filter(
                                         'local_start >= ', start)

    flattened_events = []
    for event in chain(continuing, events_soon):
        flattened_events.append({
            'title': event.title,
            'start': event.start.isoformat(),
            'end': event.end.isoformat(),
            'location': event.location,
            'link': event.link,
            'cost': event.cost,
            'credit_name': event.credit_name,
            'credit_link': event.credit_link,
        })

    response = HttpResponse(json.dumps(flattened_events),
                            mimetype='application/json')
    response['Cache-Control'] = "public; max-age=3600;"
    return response
Ejemplo n.º 25
0
	def test_has_passed_with_future_event(self):
		"""
		should return false for events in the future
		"""
		time = timezone.now() + datetime.timedelta(days=10)
		future_event = Event(starts_at=time)
		self.assertEqual(future_event.has_passed(), False)
Ejemplo n.º 26
0
 def test_was_published_recently_with_future_event(self):
     """
     was_published_recently() should return False for events whose
     pub_date is in the future
     """
     future_event = Event(pub_date=timezone.now() + datetime.timedelta(days=30))
     self.assertEqual(future_event.was_published_recently(), False)
Ejemplo n.º 27
0
def events_list(request):

    func_return = _init_facebook_app(request)
    if(func_return != False):
        return func_return

    try:
        graph, user, sys_user = _get_facebook_app(request)
        if sys_user is None:
            return HttpResponseRedirect("/facebook/setup/")
    except facebook.GraphAPIError:
        del request.session["access_token"]
        return HttpResponseRedirect("http://apps.facebook.com/"+ settings.FACEBOOK_APP_ID +"/")

    if request.method == 'POST':
        events_ids = request.POST.getlist("object_events")

        for event_id in events_ids:
            event = graph.get_object(event_id)
            image_url = "https://graph.facebook.com/" + event["id"] + "/picture?type=large"

            img_temp = NamedTemporaryFile(delete=True)
            img_temp.write(urllib2.urlopen(image_url).read())
            img_temp.flush()

            user_event = Event(
                title = event["name"],
                from_date = dateutil.parser.parse(event["start_time"]),
                to_date = dateutil.parser.parse(event["end_time"]),
                address = event["location"],
                user = sys_user.username,
                add_user = sys_user,
                category = EventCategory.objects.get(id=1),
                status = 2,
            )

            if "description" in event:
                user_event.description = event["description"]

            user_event.image.save(event["id"] + ".jpg", File(img_temp));
            user_event.slug = SlugifyUniquely( event["name"], user_event.__class__)
            user_event.save()

        if len(events_ids) > 0:
            _add_flash_message(request, "Your events has been added")
        return HttpResponseRedirect( reverse('facebook_events_list') )

    events = graph.get_connections(user["id"], "events")

    for event in events["data"]:
        event["start_time"] = dateutil.parser.parse(event["start_time"])
        event["end_time"] = dateutil.parser.parse(event["end_time"])
        event["picture_url"] = "https://graph.facebook.com/" + event["id"] + "/picture?type=normal"

    return dict(
        user = user,
        events = events,
        message = _get_flash_message(request),
    )
Ejemplo n.º 28
0
 def test_event_get_occurrences_after(self):
     recurring_event = Event(**self.recurring_data)
     recurring_event.save()
     occurrences = recurring_event.get_occurrences(start=datetime.datetime(2008, 1, 5),
         end=datetime.datetime(2008, 1, 6))
     occurrence = occurrences[0]
     occurrence2 = recurring_event.occurrences_after(datetime.datetime(2008, 1, 5)).next()
     self.assertEqual(occurrence, occurrence2)
Ejemplo n.º 29
0
 def test_event_retrieve_category_person_time(self):
     test_event = Event(title='@i created this #test')
     test_event.save()
     self.assertEqual(test_event.person, 'i')
     self.assertEqual(test_event.category, 'test')
     self.assertEqual(test_event.time.year, datetime.datetime.now().year)
     self.assertEqual(test_event.time.month, datetime.datetime.now().month)
     self.assertEqual(test_event.time.day, datetime.datetime.now().day)
Ejemplo n.º 30
0
 def test_get_occurrence(self):
     event = Event(**self.recurring_data)
     event.save()
     occurrence = event.get_occurrence(datetime.datetime(2008, 1, 5, 8, 0))
     self.assertEqual(occurrence.start, datetime.datetime(2008, 1, 5, 8))
     occurrence.save()
     occurrence = event.get_occurrence(datetime.datetime(2008, 1, 5, 8, 0))
     self.assertTrue(occurrence.pk is not None)
Ejemplo n.º 31
0
 def set_rating(self, user, val, activity=None):
     """
     Set a user's Vote on a certain object. If the user has previously voted
     on that object, it removes the old vote.
     """
     Vote.objects.record_vote(self, user, val)
     if activity is not None:
         Event.record_event(self, user, activity)
Ejemplo n.º 32
0
def create_tool(sender, instance, created, **kwargs):
    """
    If we are creating a tool, make a creation event.

    """
    if created:
        event = Event(tool=instance, event_type='Oprettelse')
        event.save()
Ejemplo n.º 33
0
 def add_event(code):
     #ToDo: make sure event isn't already in db
     new_event = Event(api_url=api_url,
                       event_start=start_time,
                       title=api_object['name']['html'],
                       event_url=api_object['url'],
                       event_code=code)
     new_event.save()
Ejemplo n.º 34
0
 def get(self):
     self.response.out.write("Creating New Event")
     e=Event(title="GDG Meetup", details="Final Google Technology User group Hackup Meetup",
              datetime=datetime.datetime.today())
     self.response.out.write("Begin Saving New Event")
     e.put()
     self.response.out.write("Complete Saving New Event")
     pass
Ejemplo n.º 35
0
def show_events_by_slug(request, slug):
    event = Event.objects.active().get(slug=slug)
    if Event.can_view_event(slug, request.user) is True:
        comments = Comment.objects.active().sort()
        comments = comments.filter(event=event).order_by('-created_at')
        form = CommentForm(request.POST or None)
        username_form = UserForm(request.POST or None)

        storage = messages.get_messages(request)
        for message in storage:
            pass

        final_users = []
        final_team = []

        if request.user.is_authenticated:
            if AccountDetails.objects.filter(user=request.user).exists():
                users = AccountDetails.objects.get(
                    user=request.user).friends.all()
                for user in users:
                    if AccountDetails.objects.filter(user=user):
                        details = AccountDetails.objects.get(user=user)
                        user.details = details
                        final_users.append(user)

            if request.method == 'POST':
                if form.is_valid():
                    comment = form.save(commit=False)
                    comment.event = event
                    comment.author = request.user
                    comment.save()

        has_joined = Event.has_joined_event(request.user, slug)

        team = event.team_members.all()
        for user in team:
            if AccountDetails.objects.filter(user=user):
                details = AccountDetails.objects.get(user=user)
                user.details = details
                final_team.append(user)

        context = {
            'event': event,
            'comments': comments,
            'form': form,
            'has_joined': has_joined,
            'guests': Event.get_guests(slug),
            'users': final_users,
            'team': final_team,
            'is_team_member': Event.is_team_member(request.user, slug)
        }
        return render(request, 'events/event.html', context)

    error_message = "Event is not available yet\
          or you don't have permission to view it."

    context = {'error_message': error_message}
    return render(request, 'CRUDops/error.html', context)
Ejemplo n.º 36
0
def select_question(report, question, delta):
    content = '{"question_id":%d}' % question.id
    start = datetime.strptime(report.start, settings.DATE_INPUT_FORMATS[0])
    timestamp = start + timedelta(seconds=delta)
    event = Event(timestamp=timestamp,
                  interview=report,
                  type=Event.QUESTION_SELECTED,
                  content=content)
    event.save()
Ejemplo n.º 37
0
    def _save_recurring_superevents(self, recurring_groups):
        groups = map(frozenset, recurring_groups.values())
        aggregates = set()
        for group in groups:
            kulke_ids = set(map(make_kulke_id, group))
            superevent_aggregates = EventAggregate.objects.filter(members__event__id__in=kulke_ids).distinct()
            cnt = superevent_aggregates.count()

            if cnt > 1:
                print("Error: the superevent has an ambiguous aggregate group.")
                print("Aggregate ids: {}, group: {}".format(superevent_aggregates.values_list("id", flat=True), group))
                continue

            events = Event.objects.filter(id__in=kulke_ids)
            if events.count() < 2:
                continue

            aggregate = None
            if cnt == 0:
                if len(group) == 1:
                    # Do not create aggregates of only one.
                    continue
                aggregate = EventAggregate()
                aggregate.save()
                super_event = Event(
                    publisher=self.organization,
                    super_event_type=Event.SuperEventType.RECURRING,
                    data_source=DataSource.objects.get(pk="kulke"),  # TODO
                    id="linkedevents:agg-{}".format(aggregate.id),
                )
                super_event.save()
                aggregate.super_event = super_event
                aggregate.save()
                for event in events:
                    member = EventAggregateMember.objects.create(event=event, event_aggregate=aggregate)
            elif cnt == 1:
                aggregate = superevent_aggregates.first()
                if len(group) == 1:
                    events = Event.objects.get(pk=make_kulke_id(group.pop()))
                    # The imported event is not part of an aggregate
                    # but one was found it in the db. Remove the event
                    # from the aggregate. This is the only case when
                    # an event is removed from a recurring aggregate.
                    aggregate.members.remove(events)
                else:
                    for event in events:
                        try:
                            member = EventAggregateMember.objects.create(event=event, event_aggregate=aggregate)
                        except IntegrityError:
                            # Ignore unique violations. They
                            # ensure that no duplicate members are added.
                            pass
            for event in events:
                event.super_event = aggregate.super_event
                event.save()
            aggregates.add(aggregate)
        return aggregates
Ejemplo n.º 38
0
def create_event(event, course_id):
    NewEvent = Event()
    course = Course.objects.get(course_id=course_id)
    NewEvent.course_id = course
    for k, v in test_events[event].items():
        setattr(NewEvent, k, v)
    NewEvent.save()
    serializer = EventSerializer(NewEvent)
    return JsonResponse(serializer.data, safe=False)
Ejemplo n.º 39
0
def addNewEvent( date ):
    url = 'http://localhost:8080/events'
    postValue = {'pubdate_since':date}
    print 'Querying ', url, 'with', postValue


    data = urllib.urlencode(postValue)
    req = urllib2.Request(url, data)
    response = urllib2.urlopen(req)
    xml_data = unicode(response.read(), 'utf-8')
    soup = BeautifulSoup(xml_data)
    elems = soup.findAll('event')

    i = 0
    for elem in elems:
		
        matchDate = re.match(r'(\d\d\d\d)/(\d?\d)/(\d?\d)', elem.find('date').string)
        print elem
        #print elem.date.string
        date = datetime.datetime(year = int(matchDate.group(1)),
                                 month = int(matchDate.group(2)),
                                 day = int(matchDate.group(3)))
        #print date
        
        matchPubDate = re.match(r'(\d\d\d\d)/(\d?\d)/(\d?\d)', elem.find('pubdate').string)
        pubDate = datetime.datetime(year = int(matchPubDate.group(1)),
                                    month = int(matchPubDate.group(2)),
                                    day = int(matchPubDate.group(3)))
        
#content =
	#print "asdfasdfasdfasdfadfad\n"
	#print  elem.content.div.renderContents()#find('content')#.string.replace(' clear=\"none\" ','')
	contentString = ''
	if(elem.content.div.string == None):
	  #Celeefind('div').string	 #unicode(elem.content.renderContents()),
	  contentString = ''
	else: 
		contentString = elem.content.div.renderContents()  #unicode(elem.content.renderContents()),
		print contentString
	print contentString
	e = Event(name = elem.title.string,
                  date = date,
                  content = contentString , #unicode(elem.content.renderContents()),
                  place = elem.place.string, 
                  category= u'none',
                  image= u'',
                  pub_date = pubDate,
                  rating=0,
              source = elem.source.string)
        e.save()

        print 'Added to the Event table:', e
        i = i + 1

    print
    print i, 'events added. Danke sch?n'
Ejemplo n.º 40
0
def json_to_db(filename):
	data = read_from_file(filename)
	
	for key,value in data.iteritems():
		event = Event(str_id=key, name=value['name'], is_public=True)
		event.save()
		print "created event %s" %key
		for media in value['media']:
			media = Media(full_res=media['full_res'], thumbnail = media['thumbnail'], event=event)
			media.save()
Ejemplo n.º 41
0
def accept_suggested(modeladmin, request, queryset):
    for suggested_event in queryset:
        kwargs = model_to_dict(suggested_event)
        kwargs.pop('id', None)
        kwargs['date'] = now()
        kwargs['owner'] = request.user
        event = Event(**kwargs)
        event.save()
    modeladmin.message_user(request, _("Suggested events accepted."))
    return redirect(reverse('admin:events_event_changelist'))
Ejemplo n.º 42
0
def newPost(request):
  #We create a default event
  e =  Event(name = "default",date = datetime.datetime.now(),place = "",  rating =0, pub_date = datetime.datetime.now(), image ="" )
  e.save()
  
  EventFormSet = modelformset_factory(Event, exclude=('pub_date','rating'),max_num=1)
  formset = EventFormSet(queryset=Event.objects.order_by('-date'))[:1]
  #formset = EventFormSet(request.POST)

  return HttpResponse(formset)
Ejemplo n.º 43
0
def create_reminder(by, date, reminder_choice, registration, step, timezone):
    offset = get_reminder_minutes_offset(reminder_choice)
    when = date - dt.timedelta(minutes=offset)

    reminder, created_at = Reminder.objects.get_or_create(
        registration=registration)

    reminder.step = step
    reminder.by = by
    reminder.when = when
    reminder.date = date
    reminder.timezone = timezone
    reminder.save()

    costumer_name = registration.costumer.get_full_name()

    event = Event.objects.filter(reminder=reminder).first()
    if not event:
        event = Event(reminder=reminder)

    event.user = registration.consultant
    event.title = u'Ad Astra Reminder - {}'.format(costumer_name)
    event.description = u'You have one {} with {}'.format(
        reminder.get_step_display(), costumer_name)
    event.start = date
    event.end = date + dt.timedelta(minutes=30)
    event.save()
Ejemplo n.º 44
0
def migrate_events():
    
    """
    Event Types
    """
    
    
    """
    Events
    """
    
    l_events = EventsEvent.objects.all()
    
    user = User.objects.get(pk=1)
    
    for l_event in l_events:
        
        kwargs = {
            'city': l_event.city,
            'content':  l_event.content,
            'country': l_event.country,
            'created': l_event.created,
            'created_by': user,
            'email': l_event.email,
            'end_date': l_event.end_date,
            'event_type': l_event.event_type,
            'fax': l_event.fax,
            'is_published': l_event.is_published,
            'mobile': l_event.mobile,
            'phone': l_event.phone,
            'post_code': l_event.post_code,
            'published': l_event.published,
            'slug': l_event.slug,
            'start_date': l_event.start_date,
            'state': l_event.state,
            'street': l_event.street,
            'suburb': l_event.suburb,
            'summary': l_event.summary,
            'title': l_event.title,
            'venue': l_event.venue,
            'website': l_event.website,
            'website_name': l_event.website_name,
        }
        
        event = Event(**kwargs)
        
        try:
            event.full_clean()
        except ValidationError, e:
            # Do something based on the errors contained in e.message_dict.
            # Display them to a user, or handle them programatically.
            print e
        else:
            print event
Ejemplo n.º 45
0
def rate_updated(rate, report, question, delta):
    content = '{"new_rating":%d,"old_rating":%d, "question_id":%d}' \
              % (random.randint(1, 9), rate, question.id)
    start = datetime.strptime(report.start, settings.DATE_INPUT_FORMATS[0])
    timestamp = start + timedelta(seconds=delta)
    event = Event(timestamp=timestamp,
                  interview=report,
                  type=Event.RATE_UPDATED,
                  content=content)
    event.save()
    return event
Ejemplo n.º 46
0
    def handle(self, *args, **options):
        try:
            import bpdb as pdb
        except ImportError:
            import pdb

        try:
            Event.sync_from_meetup()
        except Exception as exc:
            self.stderr.write("ERROR: %s" % exc)
            pdb.pm()
Ejemplo n.º 47
0
def event_delete(request, event: Event):
    """
    Delete an existing event by primary key
    """
    if not event.cast.is_manager(request.user):
        return HttpResponseForbidden()
    event_name = event.name
    slug = event.cast.slug
    event.delete()
    messages.success(request, f'"{event_name}" has been deleted')
    return redirect('cast_home', slug=slug)
Ejemplo n.º 48
0
 def test_event_forms(self):
     user = User.objects.create(username="******")
     event1 = Event(
         title='PyCon 2013', 
         slug='pycon-2013', 
         description='The most advanced conference about Python',
         where='Santa Clara, California',
         posted_by=user,
         datetime = timezone.now())
     event1.save()
     form = EventForm()
Ejemplo n.º 49
0
    def handle(self, *args, **options):
        """
        Events
        """

        l_events = EventsEvent.objects.all()

        user = User.objects.get(pk=1)

        for l_event in l_events:

            try:
                event_type = EventType.objects.get(pk=l_event.event_type.id)
            except:
                event_type = None

            kwargs = {
                "city": l_event.city,
                "content": l_event.content,
                "country": l_event.country,
                "created": l_event.created,
                "created_by": user,
                "email": l_event.email,
                "end_date": l_event.end_date,
                "event_type": event_type,
                "fax": l_event.fax,
                "is_published": l_event.is_published,
                "mobile": l_event.mobile,
                "phone": l_event.phone,
                "post_code": l_event.post_code,
                "published": l_event.published,
                "slug": l_event.slug,
                "start_date": l_event.start_date,
                "state": l_event.state,
                "street": l_event.street,
                "suburb": l_event.suburb,
                "summary": l_event.summary,
                "title": l_event.title,
                "venue": l_event.venue,
                "website": l_event.website,
                "website_name": l_event.website_name,
            }

            event = Event(**kwargs)

            try:
                event.full_clean()
                # pass
            except ValidationError, e:
                # Do something based on the errors contained in e.message_dict.
                # Display them to a user, or handle them programatically.
                print e
            else:
                print event
Ejemplo n.º 50
0
def rate_created(report, question, delta):
    rate = random.randint(1, 9)
    content = '{"rating":%d, "question_id":%d}' % (rate, question.id)
    start = datetime.strptime(report.start, settings.DATE_INPUT_FORMATS[0])
    timestamp = start + timedelta(seconds=delta)
    event = Event(timestamp=timestamp,
                  interview=report,
                  type=Event.RATE_CREATED,
                  content=content)
    event.save()
    return rate
Ejemplo n.º 51
0
def create_event(request):
    user = request.user
    if user.is_staff:
        if request.method == 'POST':
            res = request.POST
            files = request.FILES
            if validate_event(res, files):
                categories = []
                for category in res['categories'].split():
                    category_object = Category.objects.filter(name=category)
                    if category_object.count():
                        categories.append(category_object.first())
                    else:
                        categories.append(Category(name=category))

                event = Event(title=res['title'],
                              start_date=parse(res['start_date']),
                              finish_date=parse(res['finish_date']),
                              organizer=res['organizer'],
                              place=res['place'],
                              cover_url=files['cover_url'],
                              logo_url=files['logo_url'],
                              description=res['description'])
                print(files)
                print(res)
                print("files['lecturer_photo']", files['lecturer_photo'])
                lecturer = Lecturer(name=res['name'],
                                    resume_url=files['resume_url'],
                                    photo_url=files['lecturer_photo'])

                lecture = Lecture(title=res['lecture_title'])
                event.save()
                lecturer.save()
                lecture.lecturer = lecturer
                lecture.event = event
                lecture.save()
                for category in categories:
                    category.save()
                    event.categories.add(category)
                return render(request, 'users/create_event.html', {
                    'user': request.user,
                    'succeed': True
                })
            else:
                return render(request, 'users/create_event.html', {
                    'user': request.user,
                    'not_valid': True
                })
        else:
            return render(request, 'users/create_event.html',
                          {'user': request.user})
    else:
        raise PermissionDenied
Ejemplo n.º 52
0
 def test_start_after_end_events_rejected(self):
     """ Test that events with start time greater than end time are rejected """
     with self.assertRaises(ValidationError):
         event = Event(
             room=self.room,
             activity=self.activity,
             status=Event.APPROVED,
             start=default_datetime(2016, 5, 3, 19, 0),
             end=default_datetime(2016, 5, 3, 17, 0),
             creator=self.user
         )
         event.clean()
Ejemplo n.º 53
0
def add(request, type):

    kid = get_object_or_404(Kid, id=request.GET.get('child'))

    event = Event(
        user=request.user,
        kid=kid,
        typ=type,
    )
    event.save()

    return HttpResponseRedirect('/?n&child=%d' % kid.id)
Ejemplo n.º 54
0
def add(request, type):

    kid = get_object_or_404(Kid, id=request.GET.get('child'))

    event = Event(
        user=request.user,
        kid=kid,
        typ=type,
    )
    event.save()

    return HttpResponseRedirect('/?n&child=%d' % kid.id)
Ejemplo n.º 55
0
def populate_events():

    if not events_file_exists:
        print '[!] Did not find events.csv'
        return

    print '\n[*] Importing Events...'

    # Allow changes to be made to db after nested blocks have been
    # completed.
    with transaction.atomic():
        next(events_csv)  # Skip first entry of the csv file, a header.
        for row in events_csv:

            # Check if Event is already in database.
            # If it's not, it'd throw an error if we didn't have this check.
            # If an error is thrown, then transaction.atomic() breaks,
            # meaning it won't save any Events to the database.
            if Event.objects.filter(request_number=row[0],
                                    date_submitted=row[1],
                                    title=row[2],
                                    status=row[3],
                                    date_last_edited=row[4],
                                    submitters=row[5],
                                    assignees=row[6].split(":")[0]).exists():
                # Warn user.
                if verbose:
                    print '[!] Event already in database: %s' % row[0]

            else:
                # Get event
                e = Event(request_number=row[0],
                          date_submitted=row[1],
                          title=row[2],
                          status=row[3],
                          date_last_edited=row[4],
                          submitters=row[5],
                          assignees=row[6].split(":")[0])

                # We only want to save Closed events
                if e.status == "Closed":
                    # Save Event to db (won't actually happen until
                    #  'with transaction.atomic()' is completed):
                    try:
                        e.save()
                    except Exception as e:
                        # This shouldn't happen, unless the user screwed up
                        # the events file.
                        # If we get an exception here, then the database
                        # will not save any of the events.
                        print '[!] %s' % e

    print '[*] Events: Done!'
Ejemplo n.º 56
0
 def test_waiting_overlapping_events_rejected(self):
     """ Test that waiting overlapping events are rejected """
     with self.assertRaises(ValidationError):
         event = Event(
             room=self.room,
             activity=self.activity,
             status=Event.WAITING,
             start=default_datetime(2016, 5, 3, 12, 00),
             end=default_datetime(2016, 5, 3, 16, 00),
             creator=self.user
         )
         event.clean()
Ejemplo n.º 57
0
    def create(self, validated_data):

        event = Event(origin_date=validated_data.get('origin_date'),
                      converted_date=validated_data.get('converted_date'),
                      title=validated_data.get('title'),
                      content=validated_data.get('content'),
                      type=validated_data.get('type'),
                      is_lunar=validated_data.get('is_lunar'),
                      summary=validated_data.get('summary'),
                      image_url=validated_data.get('image_url'))
        event.save()
        return event
Ejemplo n.º 58
0
 def test_event_serializer(self):
     event = Event(title='just for @serializer #test')
     event.save()
     serializer = EventSerializer(event)
     self.assertDictEqual(
         dict(serializer.data), {
             'id': 1,
             'title': 'just for @serializer #test',
             'person': 'serializer',
             'category': 'test',
             'time': make_django_time(event.time)
         })