def date_as_block_filter(value):
    df = DateFormat(value)
    result = '''<{0} class="day">{1}</{0}>
        <{0} class="month">{2}</{0}>
        <{0} class="year">{3}</{0}>'''.format(
        'span', df.format('d'), df.format('M'), df.format('Y'))
    return mark_safe(result)
Beispiel #2
0
def ApproveB(request, id):
    tb = tbboarlog.objects.get(id=id)
    if tb.approve == 'dissapprove':
        mail = smtplib.SMTP('smtp.mailgun.org', 587)
        mail.ehlo()
        mail.starttls()
        mail.login(settings.EMAIL_HOST_USER, settings.EMAIL_HOST_PASSWORD)
        dt = datetime.now()
        df = DateFormat(dt)
        date = df.format('d-m-Y')
        a = dt + timedelta(days=30)
        b = DateFormat(a)
        todate = b.format('d-m-Y')

        message = "Breed \n  Hai " + tb.fname + " " + tb.lname + ",\nYou are approved as Trainer, it is free until " + todate + " After that u want to pay 1000 RS for a month"
        email = tb.email
        mail.sendmail(settings.EMAIL_HOST_USER, email, message)
        tb.approve = "Approve"

        data = tbBandTpay.objects.create(hisid=id,
                                         fromdate=date,
                                         todate=todate,
                                         payment='done')
        tb.save()
    return HttpResponseRedirect(reverse('adminapp:demoadmin'))
Beispiel #3
0
def create_coursecomment(request, id):
    # if the comment is not null
    if not 'commentArea' in request.POST or not request.POST['commentArea']:
        context = json.dumps({"message": "error"})
        return HttpResponse(context, content_type='application/json')

    course = Course.objects.get(course_id=id)
    user = request.user
    new_comment = CourseComment(text=request.POST['commentArea'],
                                user=user,
                                Course=course)
    new_comment.save()
    df = DateFormat(localtime(new_comment.time))
    date = df.format(get_format('DATE_FORMAT'))
    time = df.format('f a')
    timestamp = date + ", " + time
    firstname = user.first_name
    lastname = user.last_name
    userid = user.id
    # convert into json format
    context = json.dumps({
        "commentText": request.POST['commentArea'],
        "firstname": firstname,
        "time": timestamp,
        "lastname": lastname,
        "userid": userid
    })
    # return json ajax
    return HttpResponse(context, content_type='application/json')
Beispiel #4
0
def select(request):
    if not request.user.first:
        dt = datetime.now()
        df = DateFormat(dt)
        df.format(get_format('DATE_FORMAT'))
        df.format('Y-m-d')
        tmp_first = request.POST['bar_id_name']
        obj = Product.objects.get(pk=tmp_first)
        current_user = request.user
        current_user.first = obj
        current_user.first_date = dt
        current_user.save()

    elif not request.user.second:
        tmp_second = request.POST['bar_id_name']
        obj = Product.objects.get(pk=tmp_second)
        current_user = request.user
        current_user.second = obj
        current_user.save()

    elif not request.user.third:
        tmp_third = request.POST['bar_id_name']
        obj = Product.objects.get(pk=tmp_third)
        current_user = request.user
        current_user.third = obj
        current_user.save()

    return redirect('home')
def create_comment(request,post_id):
	context={}
	messages=[]
	if not 'commentArea' in request.POST or not request.POST['commentArea']:
		context=json.dumps({"message":"error"})
		return HttpResponse(context, content_type='application/json')	
	post = Post.objects.get(id=post_id)
	new_comment=Comment(profile=request.user.profile, post=post, text=request.POST['commentArea'])
	new_comment.save()
	
	# profiles.add(Profile.objects.get(user=post.profile.user))
	profile=Profile.objects.get(user=request.user)
	# profileJson = serializers.serialize("json",profiles)

	df = DateFormat(localtime(new_comment.time))
  	date=df.format(get_format('DATE_FORMAT'))
  	time=df.format('f a')
  	timestamp=date+", "+time
  	firstname = profile.firstname
  	lastname=profile.lastname
  	profileid=profile.id
	context=json.dumps({"commentText":request.POST['commentArea'],"firstname":firstname,"time":timestamp,
		"lastname":lastname,"profileid":profileid})
  	
	return HttpResponse(context,content_type='application/json')
def createWeeks(startMonday, numWeeks):
    """ 
    create a dictionary to group days by weeks from a start date to a number of weeks
    args:
        startMonday (date): First date
        numWeeks (int): Number of weeks
    return:
        Dictionary: Days grouped by weeks
    """
    w = 0
    monday = startMonday
    weeks = {}
    while w <= numWeeks:
        name = "Semana actual" if w == 0 else "Semana " + str(w + 1)
        wid = "week" + str(w + 1)
        weekInfo = {"week": {}, "name": name, "index": w, "id": wid}
        for r in range(7):
            day = (monday + timedelta(days=r))
            df = DateFormat(day)
            weekInfo["week"][r] = {
                "hours": {},
                "weekday": r,
                "name": df.format("D"),
                "date": df.format("b/d")
            }

        weeks[DateFormat(monday).format("b d Y")] = weekInfo
        monday = (monday + timedelta(days=7))
        w += 1
    return weeks
Beispiel #7
0
def agenda_nota_list_json(request):
    if service.validar_session(request):
        notas = Nota.objects.all()
        cantidad = len(notas)
        json_pro = {}
        json_pro["draw"] = 1
        json_pro["recordsTotal"] = cantidad
        json_pro["recordsFiltered"] = cantidad
        listas = []
        for nota in notas:
            df = DateFormat(nota.fecha_registro)
            fecha_registro_corta = str(df.format('YmdHi'))
            fecha_registro_normal = str(df.format('d/m/Y H:i'))
            listas.append({
                "id": nota.id,
                "titulo": nota.titulo,
                "categoria": nota.categoria.nombre,
                "fecha_registro_normal": fecha_registro_normal,
                "fecha_registro_corta": fecha_registro_corta
            })
        json_pro["data"] = listas
        json_lista = json.dumps(json_pro)
        return HttpResponse(json_lista, content_type='application/json')
    else:
        return redirect('agenda_ingreso')
def taskInfo(task):
    """ 
    Task info to display
    args:
        task (Task): Task to store
    return:
        Dictionary: dictionary containing the task information
    """
    df = DateFormat(task.date.astimezone(timezone.get_current_timezone()))

    htmlInfo = {
        "icon": task.category.icon,
        "color": task.category.color,
        "h": "h" + df.format("H")
    }
    tInfo = {
        "id": task.id,
        "title": task.title,
        "category": task.category.name,
        "description": task.description,
        "date": df.format("l b d Y - H:i"),
        "complete": task.complete,
        "htmlInfo": htmlInfo
    }
    return tInfo
Beispiel #9
0
def diagram(request):
    data = []
    rooms = Rooms.objects.all()

    try:
        if request.POST:
            roomsPOSTGraph = request.POST.get('r', False)
            roomsName = Rooms.objects.get(nameRoom=roomsPOSTGraph)
            date_start = request.POST.get('dateStart', False)
            date_end = request.POST.get('dateEnd', False)

            for s in Sensor.objects.all():
                if roomsName == s.idRoom:
                    measurement_graph = MeasurementData.objects.filter(
                        idSensor=s.id,
                        timestamp__gte=date_start,
                        timestamp__lte=date_end)
                    for m in measurement_graph:

                        data.append(
                            MeasurementClass(m.timestamp, m.temperature,
                                             m.humidity, m.idSensor,
                                             roomsName))
            text = "----"
            first_data = date_start
            last_data = date_end
        else:
            text = "Wszystkie Pomiary"
            sensor = Sensor.objects.get(id=1)
            roomsName = sensor.idRoom
            data = MeasurementData.objects.filter(idSensor=1)

            df = DateFormat(data[0].timestamp)
            first_data = df.format('Y-m-d')
            df2 = DateFormat(data[len(data) - 1].timestamp)
            last_data = df2.format('Y-m-d')

    except ObjectDoesNotExist:
        textproblem = "Prosze o wybranie czujnika."
        return render(request, 'diagram.html', {
            'problem': textproblem,
            'rooms': rooms
        })
    except ValidationError as e:
        textproblem = "Prosze o wybranie daty."
        return render(request, 'diagram.html', {
            'problem': textproblem,
            'rooms': rooms
        })

    return render_to_response('diagram.html', {
        'data': data,
        'rooms': rooms,
        'text': text,
        'roomName': roomsName,
        'firstData': first_data,
        'lastData': last_data
    },
                              context_instance=RequestContext(request))
Beispiel #10
0
 def get_value(self, value):
     if isinstance(value, date):
         date_format = DateFormat(value)
         return date_format.format("d/m/y").capitalize()
     elif isinstance(value, datetime):
         date_format = DateFormat(value)
         return date_format.format("d/m/y H:M").capitalize()
     return value
Beispiel #11
0
 def get_value(self, value):
     if isinstance(value, date):
         date_format = DateFormat(value)
         return date_format.format("d/m/y").capitalize()
     elif isinstance(value, datetime):
         date_format = DateFormat(value)
         return date_format.format("d/m/y H:M").capitalize()
     return value
Beispiel #12
0
def occurrences(request):

    user = User.objects.get(id=request.user.id)

    occurrences_objects = Occurrences.objects.filter(
        user=user, bullshit=0).order_by('created_at')
    forcing_objects = OccurrencesReforce.objects.filter(user=user)

    result = []

    # query for own occurrences
    if (len(occurrences_objects) > 0):
        for occ in occurrences_objects:
            df = DateFormat(occ.created_at)
            new_date = df.format('m/d/Y H:i:s')

            o = {'is_owner': 1, 
                 'id': occ.id, 
                 'user_id': occ.user_id, 
                 'user_name': user.username, 
                 'created_at': str(new_date), 
                 'coordinate': occ.coordinate, 
                 'category_id': occ.category_id, 
                 'forced': 0, 
                 'category_name': occ.category.name, 
                 'title': occ.title, 
                 'description': occ.description, 
                 'validated': occ.validated, 
                 'vote_counter': occ.vote_counter}
            result.append(o)

    # query for occurrences user follows
    if(forcing_objects.exists()):
        for forcing in forcing_objects:
            occ = forcing.occurrence

            df = DateFormat(occ.created_at)
            new_date = df.format('m/d/Y H:i:s')

            perm = has_write_permission(occ.id, request.user.id)

            o = {'permission': perm,
                 'is_owner': 0, 
                 'id': occ.id, 
                 'user_id': occ.user_id, 
                 'user_name': occ.user.username, 
                 'created_at': str(new_date), 
                 'coordinate': occ.coordinate, 
                 'category_id': occ.category_id, 
                 'forced': 1, 
                 'category_name': occ.category.name, 
                 'title': occ.title, 
                 'description': occ.description, 
                 'validated': occ.validated, 
                 'vote_counter': occ.vote_counter}
            result.append(o)

    return HttpResponse(simplejson.dumps(result), content_type="json")
Beispiel #13
0
def buy(request,id):
    try:
        myid=request.session['userid']
    except:
        try:
            myid=request.session['trainerid']
        except:
            try:
                myid=request.session['boardingid']
            except:
                return HttpResponseRedirect(reverse('app:Ulogin'))
    if myid:
        cartc=tbcart.objects.filter(userid=myid).count()
        item=tbshoping.objects.get(id=id)
        userdata=tbboarlog.objects.get(id=myid)
        if request.method=="POST":
            qty=request.POST.get('qty')
            cvv=request.POST.get('cvv')
            cardno=request.POST.get('cardNumber')
            if tbatm.objects.filter(cvv=cvv,Atmno=cardno):
                atmdetails=tbatm.objects.get(cvv=cvv,Atmno=cardno)
                actaddress=request.POST.get('actaddress')
                month=request.POST.get('month')
                year1=request.POST.get('year')
                year=int(year1)
                price=item.price
                total=request.POST.get('price')
                amt=atmdetails.amt
                if atmdetails.amt < total:
                    err="sorry...pls check your act balance"
                    return render(request,'app/buy.html',{'cartc':cartc,'item':item,'userdata':userdata,'err':err})
                dt = datetime.now()
                df = DateFormat(dt)
                date=df.format('d-m-Y')
                yo=df.format('Y')
                mo=df.format('m')
                y=int(yo)
                quty=int(item.quty)-int(qty)
                if quty<0:
                    err="We have only " + item.quty + "left....sorry"
                    return render(request,'app/cartbuy.html',{'cartc':cartc,'item':item,'userdata':userdata,'err':err})
                if year < y:
                    err="Card Expired"
                    return render(request,'app/cartbuy.html',{'cartc':cartc,'item':item,'userdata':userdata,'err':err})
                else:
                    pay=tbpayment.objects.create(address=actaddress,userid=myid,date=date,item=item.item,itemid=id,qty=qty,price=price,total=total,payment='done')
                    item.quty=quty
                    item.save()
                    atmdetails.amt=int(amt)-int(total)
                    atmdetails.save()
                    succ="Payment Successfully completed"
                    return render(request,'app/buy.html',{'succ':succ})
            else:
                err="Not a valid card number"
                return render(request,'app/buy.html',{'cartc':cartc,'item':item,'userdata':userdata,'err':err})
    return render(request,'app/buy.html',{'cartc':cartc,'item':item,'userdata':userdata})
Beispiel #14
0
    def handle(self, *args, **options):
        tenant = Customer.objects.filter(
            schema_name=connection.schema_name).first()
        if tenant.is_public_tenant():
            return
        ContentType.objects.clear_cache()

        # Get Daily Digest subscribers
        content_type = ContentType.objects.get_for_model(Event)
        perm = Permission.objects.get(content_type=content_type,
                                      codename='receive_daily_digest')
        recipients = User.objects.filter(
            Q(groups__permissions=perm) | Q(user_permissions=perm)).distinct()

        dt = datetime.now()
        start_dt = dt - timedelta(days=1)
        plaintext = get_template('email/daily_digest_email.txt')
        htmly = get_template('email/daily_digest_email.html')
        checkin_type = ContentType.objects.get(model="checkin")
        comment_type = ContentType.objects.get(model="comment")
        employeezone_type = ContentType.objects.get(model="employeezone")
        feedbackdigest_type = ContentType.objects.get(model="feedbackdigest")

        for recipient in recipients:
            # Get past days worth of activity items subscriber is allowed to see
            events = Event.objects.get_events_for_all_employees(
                requester=recipient)
            events = events.exclude(event_type=employeezone_type,
                                    user__employee__id=F("employee__id"))
            events = events.filter(date__range=[start_dt, dt])
            if events.count() > 0:
                df = DateFormat(dt)
                from_email = 'Scoutmap<*****@*****.**>'
                subject = 'Daily Recap for ' + df.format('l, d F')
                date = df.format('l, d F')
                data = Context({
                    'date': date,
                    'events': events,
                    'site': tenant.domain_url,
                    'checkin_type': checkin_type,
                    'comment_type': comment_type,
                    'employeezone_type': employeezone_type,
                    'feedbackdigest_type': feedbackdigest_type,
                    'recipient': recipient
                })
                text_content = plaintext.render(data)
                html_content = htmly.render(data)
                msg = EmailMultiAlternatives(subject, text_content, from_email,
                                             [recipient.email])
                msg.attach_alternative(html_content, "text/html")
                msg.send()
                self.stdout.write('Successfully sent Daily Digest.')
            else:
                self.stdout.write('Daily Digest had no new events to send.')
Beispiel #15
0
def format_story_link_date__long(date, now=None):
    if not now: now = datetime.datetime.utcnow()
    diff = now.date() - date.date()
    parsed_date = DateFormat(date)
    if diff.days == 0:
        return 'Today, ' + parsed_date.format('F jS ') + date.strftime('%I:%M%p').lstrip('0').lower()
    elif diff.days == 1:
        return 'Yesterday, ' + parsed_date.format('F jS g:ia').replace('.','')
    elif date.date().timetuple()[7] == now.date().timetuple()[7]:
        return parsed_date.format('l, F jS g:ia').replace('.','')
    else:
        return parsed_date.format('l, F jS, Y g:ia').replace('.','')
Beispiel #16
0
def format_story_link_date__long(date, now=None):
    if not now: now = datetime.datetime.utcnow()
    diff = now.date() - date.date()
    parsed_date = DateFormat(date)
    if diff.days == 0:
        return 'Today, ' + parsed_date.format('F jS ') + date.strftime(
            '%I:%M%p').lstrip('0').lower()
    elif diff.days == 1:
        return 'Yesterday, ' + parsed_date.format('F jS g:ia').replace('.', '')
    elif date.date().timetuple()[7] == now.date().timetuple()[7]:
        return parsed_date.format('l, F jS g:ia').replace('.', '')
    else:
        return parsed_date.format('l, F jS, Y g:ia').replace('.', '')
Beispiel #17
0
def format_story_link_date__long(date, now=None):
    if not now:
        now = datetime.datetime.utcnow()
    diff = now.date() - date.date()
    parsed_date = DateFormat(date)
    if diff.days == 0:
        return "Today, " + parsed_date.format("F jS ") + date.strftime("%I:%M%p").lstrip("0").lower()
    elif diff.days == 1:
        return "Yesterday, " + parsed_date.format("F jS g:ia").replace(".", "")
    elif date.date().timetuple()[7] == now.date().timetuple()[7]:
        return parsed_date.format("l, F jS g:ia").replace(".", "")
    else:
        return parsed_date.format("l, F jS, Y g:ia").replace(".", "")
Beispiel #18
0
def format_story_link_date__long(date, now=None):
    if not now:
        now = datetime.datetime.now()
    date = date.replace(tzinfo=None)
    midnight = midnight_today(now)
    parsed_date = DateFormat(date)

    if date >= midnight:
        return "Today, " + parsed_date.format("F jS ") + date.strftime("%I:%M%p").lstrip("0").lower()
    elif date >= midnight_yesterday(midnight):
        return "Yesterday, " + parsed_date.format("F jS g:ia").replace(".", "")
    elif date >= beginning_of_this_month():
        return parsed_date.format("l, F jS g:ia").replace(".", "")
    else:
        return parsed_date.format("l, F jS, Y g:ia").replace(".", "")
def format_story_link_date__long(date, now=None):
    if not now:
        now = datetime.datetime.now()
    date = date.replace(tzinfo=None)
    midnight = midnight_today(now)
    parsed_date = DateFormat(date)

    if date >= midnight:
        return 'Today, ' + parsed_date.format('F jS ') + date.strftime('%I:%M%p').lstrip('0').lower()
    elif date >= midnight_yesterday(midnight):
        return 'Yesterday, ' + parsed_date.format('F jS g:ia').replace('.','')
    elif date >= beginning_of_this_month():
        return parsed_date.format('l, F jS g:ia').replace('.','')
    else:
        return parsed_date.format('l, F jS, Y g:ia').replace('.','')
Beispiel #20
0
    def get_timestring(self):
        """
        Returns a nice human-readable string that represents that date, start
        and end time

        e.g. 24th May 2018, 7 a.m. to 2:30 p.m.
        """
        date_format_obj = DateFormat(self.date)
        start_format_obj = DateFormat(self.start_time)
        end_format_obj = DateFormat(self.end_time)

        return '{date}, {start} to {end}'.format(
            date=date_format_obj.format('jS F Y'),
            start=start_format_obj.format('P'),
            end=end_format_obj.format('P'))
Beispiel #21
0
def format_story_link_date__long(date, now=None):
    if not now:
        now = datetime.datetime.now()
    date = date.replace(tzinfo=None)
    midnight = midnight_today(now)
    parsed_date = DateFormat(date)

    if date >= midnight:
        return 'Today, ' + parsed_date.format('F jS ') + date.strftime('%I:%M%p').lstrip('0').lower()
    elif date >= midnight_yesterday(midnight):
        return 'Yesterday, ' + parsed_date.format('F jS g:ia').replace('.','')
    elif date >= beginning_of_this_month():
        return parsed_date.format('l, F jS g:ia').replace('.','')
    else:
        return parsed_date.format('l, F jS, Y g:ia').replace('.','')
def test_list_measurement(admin_client, live_server,  # pylint: disable=R0914
                          webdriver):
    selenium = webdriver()
    create_correct_sample_data()
    create_characteristic_values()
    try:
        selenium.get(live_server + '/measurement/')
        login_as_admin(selenium)
        title = selenium.find_element_by_css_selector('#page-wrapper h1').text
        assert title == 'List of measurements'
        table_rows = selenium.find_elements_by_class_name('clickable-row')
        assert len(table_rows) == 19
        all_meas = Measurement.objects.all()
        header = selenium.find_elements_by_css_selector('#page-wrapper th')
        assert len(header) == 6
        for index, field_name in enumerate(['date', 'order', 'order_items',
                                            'examiner', 'meas_item',
                                            'measurement_tag']):
            field = Measurement._meta.get_field(field_name)  # pylint: disable=W0212
            assert header[index].text == field.verbose_name
        for index, row in enumerate(table_rows):
            url = '/measurement/{}/'.format(all_meas[index].pk)
            assert row.get_attribute('data-href') == url
            columns = row.find_elements_by_css_selector('#page-wrapper td')
            assert len(columns) == 6
            date = DateFormat(all_meas[index].date)
            assert columns[0].text == date.format(settings.DATETIME_FORMAT)
            assert columns[1].text == str(all_meas[index].order).strip()
            items = all_meas[index].order_items.all()
            assert columns[2].text == ';'.join([str(item) for item in items])
            assert columns[3].text == all_meas[index].examiner.username
            assert columns[4].text == str(all_meas[index].meas_item)
            assert columns[5].text == str(all_meas[index].measurement_tag)
    finally:
        selenium.quit()
Beispiel #23
0
def check(request, id):
    data = tbnoti.objects.get(id=id)
    data.status = "Accept"
    data.seen = "YES"
    userid = data.sentid
    data.save()
    recid = data.recid
    petid = data.arg1
    boardingid = request.session['boardingid']
    if request.method == "POST":
        date = request.POST.get("date")
        dt = datetime.now()
        df = DateFormat(dt)
        datenow = df.format('d-m-Y')
        amount = request.POST.get('amount')
        descriptions = datenow + " Bordings Accepted user Requested and Add requested user to deliver his/n"
        data1 = tbonuser.objects.create(descriptions=descriptions,
                                        usersid=userid,
                                        petid=petid,
                                        varid=boardingid,
                                        date=date,
                                        status="You can send your pet",
                                        amount=amount,
                                        handler="",
                                        duration="",
                                        days="")
    return HttpResponseRedirect(reverse('boardingapp:demoboarding'))
Beispiel #24
0
def check(request, id):
    data = tbnoti.objects.get(id=id)
    data.status = "Accept"
    data.seen = "YES"
    userid = data.sentid
    data.save()
    petid = data.arg1
    trainerid = request.session['trainerid']
    if request.method == "POST":
        date = request.POST.get("date")
        dt = datetime.now()
        df = DateFormat(dt)
        datenow = df.format('d-m-Y')

        amount = request.POST.get('amount')
        duration = request.POST.get('duration')
        days = request.POST.get('days')
        handlerid = request.POST.get("handler")
        descriptions = datenow + " Trainer Accepted user Requested and Add requested user to deliver his dog on or befor " + date + '/n'
        data = tbonuser.objects.create(descriptions=descriptions,
                                       usersid=userid,
                                       petid=petid,
                                       varid=trainerid,
                                       date=date,
                                       status="You can send your pet please",
                                       handler=handlerid,
                                       amount=amount,
                                       days=days,
                                       duration=duration)

        handlers = tbhandlers.objects.get(name=handlerid)
        handlers.assigments = "yes"
        handlers.dogid = petid
        handlers.save()
    return HttpResponseRedirect(reverse('trainerapp:demotrainer'))
Beispiel #25
0
def viewnoti(request):
    var = "BorardingRequest"
    notif = ""
    full = tbboarlog.objects.all()
    userid = request.session['userid']
    mydata = tbboarlog.objects.get(id=userid)
    data = ""
    nan = "You can send your pet"
    media = ""
    dt = datetime.now()
    df = DateFormat(dt)
    date = df.format('d-m-Y')
    nowdate = datetime.strptime(date, '%d-%m-%Y')
    data1 = tbboarlog.objects.all()
    if tbonuser.objects.filter(usersid=userid, status=nan):
        data = tbonuser.objects.filter(usersid=userid, status=nan, useracc="")
    if tbnoti.objects.filter(subject=var, recid=userid):
        notif = tbnoti.objects.filter(subject=var, recid=userid)
    return render(
        request, 'userapp/viewnoti.html', {
            'mydata': mydata,
            'full': full,
            'notif': notif,
            'data': data,
            'data1': data1
        })
Beispiel #26
0
def places(request):
	context_dict = {}
	if request.method == 'POST':
		from_station = request.POST.get('from_station')
		to_station = request.POST.get('to_station')
		date = request.POST.get('departure_date')
		time = request.POST.get('departure_time')
		train_number = request.POST.get('train_number')
		departure_date = datetime.strptime(date, "%Y-%m-%d")
		client = Client(api_usernumber = conf.USER_NUMBER, api_passmd5 = conf.USER_PASSMD5, id_terminal = conf.ID_TERMINAL, id_service = conf.ID_SERVICE, request_url = conf.API_URL)
		df = DateFormat(departure_date)
		places = client.get_train_places(from_station, to_station, df.format('d.m.Y'), time, train_number)
		data = json.dumps(places, ensure_ascii=False)
		response_dict = json.loads(data)
		if 'status' in response_dict:
			context_dict['error'] = response_dict['message']
		else:
			context_dict = place_handler(response_dict)
		context_dict['data'] = data
		context_dict['from_station'] = Station.objects.get(code=from_station)
		context_dict['to_station'] = Station.objects.get(code=to_station)
		context_dict['departure_date'] = date
		context_dict['departure_time'] = time
		context_dict['train_number'] = train_number
		context_dict['stations'] = Station.objects.all()
	return render(request, 'search/places.html', context_dict)
Beispiel #27
0
def demoapp(request):
    pet=tbpets.objects.all()
    for i in pet:
        dob=datetime.strptime(i.dob,'%Y-%m-%d')
        vaccdat=datetime.strptime(i.Vdate,'%Y-%m-%d')
        dt = datetime.now()
        df = DateFormat(dt)
        date=df.format('d-m-Y')
        nowdate=datetime.strptime(date,'%d-%m-%Y')
        balance=nowdate-dob
        mm=balance/365
        i.age=mm.days
        nan=vaccdat-nowdate
        i.bal=nan.days
        i.save()
    try:
        myid=request.session['userid']
    except:
        try:
            myid=request.session['trainerid']
        except:
            try:
                myid=request.session['boardingid']
            except:
                return render(request,'app/demoapp.html',{})
    if myid:
        cartc=tbcart.objects.filter(userid=myid).count()
        data=tbboarlog.objects.get(id=myid)
        return render(request,'app/demoapp.html',{'cartc':cartc,'data':data})
    return render(request,'app/demoapp.html',{})
Beispiel #28
0
    def posts_by_date(self,
                      request,
                      year,
                      month=None,
                      day=None,
                      *args,
                      **kwargs):
        """The PostPages are listed by date. No pinned posts after date select."""
        self.posts = self.get_all_live_posts().filter(
            first_published_at__year=year)
        self.search_header = _('Filtered by appeared at:')
        self.search_term = year
        if month:
            try:
                month = datetime.datetime.strptime(month, '%b').month
            except ValueError:
                month = int(month)

            self.posts = self.posts.filter(first_published_at__month=month)
            try:
                df = DateFormat(date(int(year), int(month), 1))
            except ValueError:
                # the year, or month or date is wrong, return 404
                raise Http404(_('Wrong date.'))
            self.search_term = df.format('F Y')

        if day:
            self.posts = self.posts.filter(first_published_at__day=day)
            self.search_term = date_format(
                date(int(year), int(month), int(day)))

        self.posts = self.posts.order_by('-first_published_at')
        return self.serve(request, *args, **kwargs)
def recently_read(**kwargs):
    """ return html containing data from the recently read list
        Specify an argument n=[int] to determine how many entries
        are rendered in the list.
    """
    num_entries = int(kwargs['n']) if 'n' in kwargs else lib.NUM_READ_LIST
    read_list = ReadingListItem.objects.filter(wishlist=False).order_by('-date_published')[:num_entries]

    list_html = format_html("<h3>Recently Read</h3><div class=\"book-list\">")
    for book in read_list:
        list_html += format_html("<div class='book-book-result book-book-result-hover group'>")
        list_html += format_html("<img src='{}' class='left'>", book.cover)
        list_html += format_html("<p class='title'>{}</p>", book.title)
        list_html += format_html("<p class='author'>{}</p>", book.author)
        list_html += format_html("<p class='description'>{}</p>", book.description)

        dt = DateFormat(book.date_published)
        list_html += format_html("<p class='date'>Added on {}</p>", dt.format("F j, Y g:i A"))

        if book.favorite:
            list_html += format_html("<span class='favorite' title='Cory\'s Favorites'>&#x2605;</span>")

        list_html += format_html("<a class='overlay' href='{}' target='_blank'></a></div>", book.link)

    if len(read_list) == 0:
        list_html += format_html("<p class='empty'>Cory hasn't read any books yet!</p>")

    list_html += format_html("<p class='empty'><a href='{}'>(See More)</a></p></div>", reverse('books'))
    return list_html
Beispiel #30
0
    def ping_response(self, obj):
        interval = settings.JOB_RUNNER_WORKER_PING_INTERVAL
        margin = settings.JOB_RUNNER_WORKER_PING_MARGIN

        if not obj.ping_response_dts:
            return '<span style="color: red;">(none)</span>'

        date_local = obj.ping_response_dts.astimezone(
            timezone.get_current_timezone())
        date_formatted = DateFormat(date_local)
        date_formatted = date_formatted.format(settings.DATETIME_FORMAT)

        if not obj.is_responsive():
            return ('<img src="{0}admin/img/icon_error.gif" /> '
                    '<span style="color: red;">{1}</span>'.format(
                        settings.STATIC_URL, date_formatted))

        if (obj.ping_response_dts <
                timezone.now() - timedelta(seconds=interval + margin)):
            return ('<img src="{0}admin/img/icon_alert.gif" /> '
                    '<span style="color: orange;">{1}</span>'.format(
                        settings.STATIC_URL, date_formatted))

        return ('<img src="{0}admin/img/icon_success.gif" /> '
                '<span style="color: green;">{1}</span>'.format(
                    settings.STATIC_URL, date_formatted))
Beispiel #31
0
def usertreg(request):
    userid = request.session['userid']
    if tbpets.objects.filter(userid=userid):
        pets = tbpets.objects.filter(userid=userid)
        if request.method == "POST":
            mat = request.POST.get('matter')
            dogid = request.POST.get('arg1')
            trainerid = request.POST.get('trainerid')
            dt = datetime.now()
            df = DateFormat(dt)
            date = df.format('d-m-Y')
            sub = "TraingRequest"
            status = ""
            seen = ""
            data1 = tbnoti.objects.create(sentid=userid,
                                          recid=trainerid,
                                          date=date,
                                          subject=sub,
                                          mater=mat,
                                          status=status,
                                          seend=seen,
                                          arg1=dogid)

    else:
        return HttpResponseRedirect('app:Ulogin')
    return HttpResponseRedirect(reverse('userapp:usertrainer'))
 def post(self, request, *args, **kwargs):
     article_id = self.request.POST.get("article_id")
     comment = self.request.POST.get("comment")
     article = Article.objects.get(pk=article_id)
     new_comment = article.comments.create(author=request.user, content=comment)
     likes_count = new_comment.get_likes()
     dislikes_count = new_comment.get_dislikes()
     dt = datetime.now()
     df = DateFormat(dt)
     tf = TimeFormat(dt)
     new_comment_timestamp = (
         df.format(get_format("DATE_FORMAT"))
         + ", "
         + tf.format(get_format("TIME_FORMAT"))
     )
     data = [
         {
             "author": new_comment.author.get_full_name(),
             "comment": new_comment.content,
             "comment_id": new_comment.pk,
             "comment_likes": likes_count,
             "comment_dislikes": dislikes_count,
             "timestamp": new_comment_timestamp,
             "slug": article.slug,
         }
     ]
     return JsonResponse(data, safe=False)
    def _format_json_list(self, obj, options):
        if (len(obj) > 0):
            result = []

            for occ in obj:
                df = DateFormat(occ.created_at)
                new_date = df.format('m/d/Y H:i:s')

                o = {	'is_owner': is_owner(occ.id, options['request_user_id']),
                      'id': occ.id,
                      'user_id': occ.user_id,
                      'created_at': str(new_date),
                      'coordinate': occ.coordinate,
                      'category_id': occ.category_id,
                      'category_name': occ.category.name,
                      'title': occ.title,
                      'description': occ.description,
                      'validated': occ.validated,
                      'vote_counter': occ.vote_counter
                      }
                result.append(o)

            return simplejson.dumps(result)
        else:
            return simplejson.dumps({'Success': False})
Beispiel #34
0
 def handle(cls, args, text):
     if "format" in args:
         format_string = args["format"]
     else:
         format_string = "Y.m.d H:i:s"
     df = DateFormat(datetime.datetime.now())
     return df.format(format_string)
Beispiel #35
0
def get_occurrence(request, ident, user):
    result = {}
    result["success"] = False
    path = settings.CDN_URL + "/static/"

    occ = Occurrences.objects.get(id=int(ident))

    df = DateFormat(occ.created_at)
    new_date = df.format('m/d/Y H:i:s')
    result["occurrence"] = {'id_occ': occ.id, 
                            'user_id': occ.user_id, 
                            'created_at': str(new_date), 
                            'coordinate': occ.coordinate, 
                            'category_id': occ.category_id, 
                            'category_name': occ.category.name, 
                            'title': occ.title, 
                            'description': occ.description, 
                            'vote_counter': occ.vote_counter}
    occ_photos = occ.photos_set.all()
    result["occurrence"]["photos"] = []
    userObj = User.objects.get(id=int(user))
    result["occurrence"]["is_following"] = is_following(occ, userObj)

    for photo in occ_photos:
        result["occurrence"]["photos"].append(
            {"path_small": path + photo.path_small,
             "path_big": path + photo.path_big,
             "path_medium": path + photo.path_medium})

    result["success"] = True
    return HttpResponse(simplejson.dumps(result), content_type="json")
Beispiel #36
0
def gitlab_detail(request, slug):
    if slug.isdigit():
        iid = slug
        instance = get_object_or_404(GitlabProject, project_id=iid)
        return redirect(
            'gitlab:detail', slug=instance.slug
        )  # remove this line if you want to accept ids in the final url
    else:
        instance = get_object_or_404(GitlabProject, slug=slug.lower())
        iid = instance.project_id

    url = "https://gitlab.com/api/v4/projects/{}/repository/commits".format(
        iid)

    req = requests.get(url)
    content = req.json()

    for commit in content:
        date = parse(commit["committed_date"])

        formatted_date = DateFormat(date)

        #formatted_date = date.strftime("%B %-d, %Y, %I:%M %p")
        #print(commit["committed_date"])
        commit["committed_date"] = formatted_date.format('F jS, Y H:i')

    context = {"project": instance, "commits": content[:50]}

    return render(request, "gitlab_detail.html", context=context)
Beispiel #37
0
def index(request):
	currentDate = datetime.now()
	formattedDate = DateFormat(currentDate)
	context = {
        "time" : currentDate.strftime("%I:%M %p"),
		"date" : formattedDate.format(get_format('DATE_FORMAT'))
    }
	return render(request, "time_display/index.html", context)
Beispiel #38
0
    def get_initial(self):
        self.year = int(self.kwargs["year"])
        self.month = int(self.kwargs["month"])
        self.day = int(self.kwargs["day"])
        dt = date(self.year, self.month, self.day)
        df = DateFormat(dt)
        
	return {'date': date(self.year, self.month, self.day), 'title': ("%s -" % df.format('F jS')), 'user':self.request.user.username}
Beispiel #39
0
 def serialize_for_ajax(self):
     """ Serializes the time, puzzle, team, and status fields for ajax transmission """
     message = dict()
     df = DateFormat(self.submission_time.astimezone(time_zone))
     message['time_str'] = df.format("h:i a")
     message['puzzle'] = self.puzzle.serialize_for_ajax()
     message['team_pk'] = self.team.pk
     message['status_type'] = "submission"
     return message
Beispiel #40
0
 def serialize_for_ajax(self):
     """ Serializes the puzzle, team, time, and status fields for ajax transmission """
     message = dict()
     message['episode'] = self.episode.serialize_for_ajax()
     message['team_pk'] = self.team.pk
     df = DateFormat(self.time.astimezone(time_zone))
     message['time_str'] = df.format("h:i a")
     message['status_type'] = "solve"
     return message
Beispiel #41
0
def server_time(request):
    """ AJAX call to get the current server time. """

    if request.is_ajax():
        df = DateFormat(datetime.now())
        payload = df.format("F jS Y @ h:iA")
    else:
        payload = "Sorry, this URL is for AJAX calls only."
    return HttpResponse(payload, mimetype="text/plain")
Beispiel #42
0
def server_time(request):
    """ AJAX call to get the current server time. """
    
    if request.is_ajax():
        df = DateFormat(datetime.now())
        payload = df.format("F jS Y @ h:iA")
    else:
        payload = "Sorry, this URL is for AJAX calls only."
    return HttpResponse(payload, mimetype="text/plain")
Beispiel #43
0
 def serialize_for_ajax(self):
     """ Serializes the time, puzzle, team, and status fields for ajax transmission """
     message = dict()
     df = DateFormat(self.guess_time.astimezone(time_zone))
     message['time_str'] = df.format("h:i a")
     message['puzzle'] = self.puzzle.serialize_for_ajax()
     message['team_pk'] = self.team.pk
     message['status_type'] = "guess"
     return message
Beispiel #44
0
def ok(request, id):
    data = tbonuser.objects.get(id=id)
    data.useracc = "ok"
    dt = datetime.now()
    df = DateFormat(dt)
    date = df.format('d-m-Y')
    data.descriptions = data.descriptions + date + "User Selected trainer" + '/n'
    data.save()
    return HttpResponseRedirect(reverse('userapp:demouser'))
def rfc3339(value):
    from django.utils.dateformat import DateFormat
    if not value:
        return u''
    try:
        df = DateFormat(value)
        offset = (lambda seconds: u"%+03d:%02d" % (seconds // 3600, (seconds // 60) % 60))(df.Z())
        return df.format("Y-m-d\TH:i:s") + offset
    except AttributeError:
        return ''
Beispiel #46
0
 def post_by_date(self, request, year, month=None, day=None, *args, **kwargs):
     self.posts = self.get_posts().filter(date__year=year)
     if month:
         self.posts = self.posts.filter(date__month=month)
         df = DateFormat(date(int(year), int(month), 1))
         self.search_term = df.format('F Y')
     if day:
         self.posts = self.posts.filter(date__day=day)
         self.search_term = date_format(date(int(year), int(month), int(day)))
     return Page.serve(self, request, *args, **kwargs)
Beispiel #47
0
def sales_items_paginate(request):
	page = int(request.GET.get('page'))
	list_sz = request.GET.get('size')
	p2_sz = request.GET.get('psize')
	select_sz = request.GET.get('select_size')
	date = request.GET.get('gid')
	sales = Sales.objects.all().order_by('-id')
	today_formart = DateFormat(datetime.date.today())
	today = today_formart.format('Y-m-d')
	ts = Sales.objects.filter(created__icontains=today)
	tsum = ts.aggregate(Sum('total_net'))
	total_sales = Sales.objects.aggregate(Sum('total_net'))
	total_tax = Sales.objects.aggregate(Sum('total_tax'))

	try:
		last_sale = Sales.objects.latest('id')
		last_date_of_sales = DateFormat(last_sale.created).format('Y-m-d')
		all_sales = Sales.objects.filter(created__contains=last_date_of_sales)
		total_sales_amount = all_sales.aggregate(Sum('total_net'))
		items = SoldItem.objects.values('product_name', 'product_category', 'sku', 'quantity',
										   'unit_cost') \
			.annotate(Count('sku')) \
			.annotate(Sum('total_cost')) \
			.annotate(Sum('unit_cost')) \
			.annotate(Sum('quantity')).order_by('product_name')
		total_items = []
		for t in items:
			product = ProductVariant.objects.get(sku=t['sku'])
			try:
				itemPrice = product.get_cost_price().gross * t['quantity']
				retailPrice = product.get_cost_price().gross
			except ValueError, e:
				itemPrice = product.get_cost_price() * t['quantity']
				retailPrice = product.get_cost_price()
			except:
				itemPrice = 0
				retailPrice = 0
			unitSalesCost = t['unit_cost']
			totalSalesCost = t['total_cost__sum']
			try:
				grossProfit = unitSalesCost - itemPrice
				unitMargin = unitSalesCost - retailPrice
				salesMargin = totalSalesCost - (itemPrice)
				totalCost = retailPrice * t['quantity']
			except:
				grossProfit = 0
				unitMargin = 0
				salesMargin = 0
				totalCost = 0
			t['unitMargin'] = unitMargin
			t['salesMargin'] = salesMargin
			t['retailPrice'] = retailPrice
			t['totalCost'] = totalCost
			total_items.append(t)
Beispiel #48
0
def diagram(request):
    data = []
    rooms = Rooms.objects.all()

    try:
        if request.POST:
            roomsPOSTGraph = request.POST.get('r', False)
            roomsName = Rooms.objects.get(nameRoom=roomsPOSTGraph)
            date_start = request.POST.get('dateStart', False)
            date_end = request.POST.get('dateEnd', False)

            for s in Sensor.objects.all():
                if roomsName == s.idRoom:
                    measurement_graph = MeasurementData.objects.filter(idSensor=s.id, timestamp__gte=date_start,
                                                                       timestamp__lte=date_end)
                    for m in measurement_graph:

                        data.append(MeasurementClass(m.timestamp, m.temperature, m.humidity, m.idSensor, roomsName))
            text = "----"
            first_data = date_start
            last_data = date_end
        else:
            text = "Wszystkie Pomiary"
            sensor = Sensor.objects.get(id=1)
            roomsName = sensor.idRoom
            data = MeasurementData.objects.filter(idSensor=1)

            df = DateFormat(data[0].timestamp)
            first_data = df.format('Y-m-d')
            df2 = DateFormat(data[len(data)-1].timestamp)
            last_data = df2.format('Y-m-d')

    except ObjectDoesNotExist:
        textproblem = "Prosze o wybranie czujnika."
        return render(request, 'diagram.html', {'problem': textproblem, 'rooms': rooms})
    except ValidationError as e:
        textproblem = "Prosze o wybranie daty."
        return render(request, 'diagram.html', {'problem': textproblem, 'rooms': rooms})

    return render_to_response('diagram.html', {'data': data, 'rooms': rooms, 'text': text, 'roomName': roomsName,
                                               'firstData': first_data, 'lastData': last_data}, context_instance=RequestContext(request))
Beispiel #49
0
 def entries_by_date(self, request, year, month=None, day=None, *args, **kwargs):
     self.entries = self.get_entries().filter(date__year=year)
     self.search_type = _('date')
     self.search_term = year
     if month:
         self.entries = self.entries.filter(date__month=month)
         df = DateFormat(date(int(year), int(month), 1))
         self.search_term = df.format('F Y')
     if day:
         self.entries = self.entries.filter(date__day=day)
         self.search_term = date_format(date(int(year), int(month), int(day)))
     return Page.serve(self, request, *args, **kwargs)
Beispiel #50
0
def send_chat_message(message):
    redis_publisher = RedisPublisher(facility='chat_message',
                      users=[settings.ADMIN_ACCT, message.team.login_info.username])
    packet = dict()
    packet['team_pk'] = message.team.pk
    packet['team_name'] = message.team.team_name
    packet['text'] = message.text
    packet['is_response'] = message.is_response
    df = DateFormat(message.time.astimezone(time_zone))
    packet['time'] = df.format("h:i a")
    packet = RedisMessage(json.dumps(packet))
    redis_publisher.publish_message(packet)
Beispiel #51
0
 def by_date(self, request, year, month=None, day=None, *args, **kwargs):
     self.posts = self.queryset.filter(first_published_at__year=year)
     self.filter_type = _('date')
     self.filter_term = year
     if month:
         self.posts = self.posts.filter(date__month=month)
         df = DateFormat(date(int(year), int(month), 1))
         self.filter_term = df.format('F Y')
     if day:
         self.posts = self.posts.filter(date__day=day)
         self.filter_term = date_format(date(int(year), int(month), int(day)))
     return Page.serve(self, request, *args, **kwargs)
Beispiel #52
0
def info_session(request, session_type):
    try:
        STYPES[session_type]
    except:
        raise Http404, "Page not found"
    if request.method == 'POST':
        form = InfoSessionForm(session_type,request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            cd['session_type'] = session_type
            # fetch event
            event = Event.objects.using('livewhale').get(pk=cd['event'])
            cd['event'] = event
            # munge datetime
            lc = localtime(event.date_dt)
            df = DateFormat(lc)
            day = df.format('D')
            date = df.format('M d, Y')
            time = df.format('h:ia')
            datetime = '%s. %s at %s' % (day, date, time)
            cd['datetime'] = datetime
            # to
            recipients = settings.CONTINUING_EDUCATION_INFOSESSION_RECIPIENTS
            to = recipients[session_type]
            if settings.DEBUG:
                to = [settings.SERVER_MAIL,]
            subject = "OCS Information Session Request: "
            subject +="%s on %s" % (session_type, datetime)
            send_mail(
                request, to, subject, cd['email'],
                'admissions/infosession.txt', cd, BCC, content=''
            )
            return HttpResponseRedirect(
                reverse_lazy('info_session_success')
            )
    else:
        form = InfoSessionForm(session_type)
    return render(
        request, 'admissions/infosession.html',{'form': form,}
    )
Beispiel #53
0
def send_new(request, author, body):
    dajax = Dajax()

    joke = Joke(author=author, body=body)
    joke.save()

    body = body.replace('\n', '<br />')
    date = joke.date
    df = DateFormat(date)
    function = 'set_new("{}", "{}", "{}", "{}");'.format(author, df.format(DATETIME_FORMAT), joke.pk, body)
    dajax.script(function)

    return dajax.json()
Beispiel #54
0
def get_data_for_mail(load):
    result = None

    if (load == "overloaded_events"):
        events = Event.objects.all()
        overloaded_events = []
        text = "==================== Überbelegte Stunden ==================== \n\n"
        tmp_text = ""
        i = 0
        n = 0

        for event in events:
            try:
                a = event
                b = events[(i+1)]
    
                if (a.room == b.room and 
                    ((a.start_time <= b.start_time and a.end_time > b.start_time) or 
                    (a.start_time < b.end_time and a.end_time >= b.end_time))):

                    f_a_date = DateFormat(a.date)
                    f_b_date = DateFormat(b.date)
                    date_is_equal = f_a_date.format("d.m.Y") == f_b_date.format("d.m.Y")
                    lead_exists = a.lead and b.lead

                    if (lead_exists and date_is_equal):
                        tmp_text = tmp_text + " - " + str(f_a_date.format("d.m.Y")) + " um " +  a.start_time.strftime("%H:%M") + " im: " + str(a.room) + " " + str(a.lead.last_name) + " " + str(a.lead.first_name) + " und " + str(b.lead.last_name) + " " + str(b.lead.first_name) + "\n"
                        n = n + 1
            except:
                traceback.print_exc()
            i = i + 1

        text = text + " Es wurden " + str(n) + " Konflikte entdeckt! \n\n\n"
        text = text + tmp_text
        text = text + "\n\n=============================================================\n\n"
        result = text

    return result
Beispiel #55
0
def sales_paginate(request):
	page = int(request.GET.get('page'))
	list_sz = request.GET.get('size')
	p2_sz = request.GET.get('psize')
	select_sz = request.GET.get('select_size')
	date = request.GET.get('gid')
	sales = Sales.objects.all().order_by('-id')
	today_formart = DateFormat(datetime.date.today())
	today = today_formart.format('Y-m-d')
	ts = Sales.objects.filter(created__icontains=today)
	tsum = ts.aggregate(Sum('total_net'))
	total_sales = Sales.objects.aggregate(Sum('total_net'))
	total_tax = Sales.objects.aggregate(Sum('total_tax'))


	if date:
		try:
			all_salesd = Sales.objects.filter(created__icontains=date).order_by('-id')
			that_date_sum = Sales.objects.filter(created__contains=date).aggregate(Sum('total_net'))
			sales = []
			total_margin = []
			for sale in all_salesd:
				costPrice = []
				discounts = []
				quantity = SoldItem.objects.filter(sales=sale).aggregate(c=Sum('quantity'))
				setattr(sale, 'quantity', quantity['c'])
				for i in SoldItem.objects.filter(sales=sale):
					product = ProductVariant.objects.get(sku=i.sku)
					try:
						quantity = product.get_cost_price().gross * i.quantity
					except ValueError, e:
						quantity = product.get_cost_price() * i.quantity
					except:
						quantity = 0
					costPrice.append(quantity)
					discounts.append(i.discount)

				totalCostPrice = sum(costPrice)
				totalDiscounts = sum(discounts)
				setattr(sale, 'totalCostPrice', totalCostPrice)
				setattr(sale, 'totalDiscounts', totalDiscounts)
				try:
					grossProfit = sale.total_net - totalCostPrice
					margin = round(grossProfit - totalDiscounts, 2)
				except Exception as e:
					grossProfit = 0
					margin = 0
				setattr(sale, 'margin', margin)
				sales.append(sale)
				total_margin.append(margin)
Beispiel #56
0
def send_submission_update(submission):
    redis_publisher = RedisPublisher(facility='puzzle_submissions',
             users=[submission.team.login_info.username, settings.ADMIN_ACCT])
    modelJSON = json.loads(serializers.serialize("json", [submission]))[0]
    message = modelJSON['fields']
    message['response_text'] = escape(message['response_text'])
    message['puzzle'] = submission.puzzle.puzzle_id
    message['puzzle_name'] = submission.puzzle.puzzle_name
    message['team'] = submission.team.team_name
    message['pk'] = modelJSON['pk']
    df = DateFormat(submission.submission_time.astimezone(time_zone))
    message['time_str'] = df.format("h:i a")
    message = RedisMessage(json.dumps(message))
    redis_publisher.publish_message(message)
def event_creation(request, organization_id):
    """Process the creation of events"""
    #fill the form
    organization = Organization.objects.get(id=organization_id)
    form = EventForm(request.POST)
    #process and save
    if form.is_valid():
        event = form.save(commit=False)
        event.organization = organization
        event.save()
        #Get the date formats
        from_date = DateFormat(event.from_date)
        to_date = DateFormat(event.to_date)
        #return the Json of the data
        result = {
                'id' : event.id,
                'name': event.name,
                'description': event.description,
                'from': str(from_date.format(get_format('DATE_FORMAT'))),
                'to': str(to_date.format(get_format('DATE_FORMAT')))
                }
        return HttpResponse(json.dumps(result), content_type='application/json')
    return HttpResponse(json.dumps(form.errors))
Beispiel #58
0
 def serialize_for_ajax(self):
     """ Serializes the puzzle, team, time, and status fields for ajax transmission """
     message = dict()
     message['puzzle'] = self.puzzle.serialize_for_ajax()
     message['team_pk'] = self.team.pk
     try:
         # Will fail if there is more than one solve per team/puzzle pair
         # That should be impossible, but lets not crash because of it
         time = self.submission.submission_time
         df = DateFormat(time.astimezone(time_zone))
         message['time_str'] = df.format("h:i a")
     except:
         message['time_str'] = "0:00 am"
     message['status_type'] = "solve"
     return message
Beispiel #59
0
    def __init__(self,session_type,*args,**kwargs):
        super(InfoSessionForm,self).__init__(*args,**kwargs)
        cursor = connections['livewhale'].cursor()
        sql = """
            SELECT
                id,title,date_dt
            FROM
                livewhale_events
            WHERE
                id IN (
                    select id2 from livewhale_tags2any where id1={}
                )
            AND
                id IN (
                    select id2 from livewhale_tags2any where id1={}
                )
            AND
                date_dt > DATE(NOW())
            ORDER BY
                date_dt
        """.format(STYPES['information-session'], STYPES[session_type])
        cursor.execute(sql)
        # Wed. May 01, 2020 at 06pm (Master of Education & ACT Info Session)
        choices = [('','---choose a date---')]
        for event in cursor.fetchall():
            lc = localtime(pytz.utc.localize(event[2]))
            df = DateFormat(lc)
            day = df.format('D')
            date = df.format('M d, Y')
            time = df.format('h:ia')
            title = u'{}. {} at {} ({})'.format(
                day, date, time , force_text(event[1])
            )

            choices.append((event[0],title))
        self.fields['event'].choices = choices
Beispiel #60
0
def send_status_update(puzzle, team, status_type):
    # status_type should be either "solve" or "unlock"
    redis_publisher = RedisPublisher(facility='puzzle_status',
                                     users=[team.login_info.username, settings.ADMIN_ACCT])
    message = dict()
    message['puzzle_id'] = puzzle.puzzle_id
    message['puzzle_num'] = puzzle.puzzle_number
    message['puzzle_name'] = puzzle.puzzle_name
    message['team_pk'] = team.pk
    message['status_type'] = status_type
    if(status_type == 'solve'):
        time = team.solve_set.filter(puzzle=puzzle)[0].submission.submission_time
        df = DateFormat(time.astimezone(time_zone))
        message['time_str'] = df.format("h:i a")
    message = RedisMessage(json.dumps(message))
    redis_publisher.publish_message(message)