def index(request):
    category_list = Category.objects.order_by('-likes')[:5]
    page_list = Page.objects.order_by('-views')[:5]

    context_dict = {'categories': category_list, 'pages': page_list}

    visits = request.session.get('visits')
    if not visits:
        visits = 1
    reset_last_visit_time = False

    last_visit = request.session.get('last_visit')
    if last_visit:
        last_visit_time = datetime.strptime(last_visit[:-7], "%Y-%m-%d %H:%M:%S")

        if (datetime.now() - last_visit_time).days > 0:
            # ...reassign the value of the cookie to +1 of what it was before...
            visits = visits + 1
            # ...and update the last visit cookie, too.
            reset_last_visit_time = True
    else:
        # Cookie last_visit doesn't exist, so create it to the current date/time.
        reset_last_visit_time = True

    if reset_last_visit_time:
        request.session['last_visit'] = str(datetime.now())
        request.session['visits'] = visits
    context_dict['visits'] = visits

    response = render(request, 'rango/index.html', context_dict)

    return response
Exemple #2
0
    def setUp(self):
        estimate_data = {
            "name": "estimate1",
            "hours": 1
        }

        estimate = Estimate.objects.create(**estimate_data)
        estimate.save()

        client = Client.objects.create()

        project_data = {
            "name": "Project Name",
            "description": "this is the description of the project",
            "client": client,
            "start_date": datetime.now(),
            "deadline": datetime.now(),
            "service": "servicename",
        }

        project = Project.objects.create(**project_data)
        project.save()

        data = {
            "title": 'Task Title',
            "status": Task.READY,
            "estimate": estimate,
            "project": project,
            "description": "this is the description of the project",
        }
        self.task = Task.objects.create(**data)
Exemple #3
0
    def process_request2(self, request):
        user = None
        if request.path.startswith('/css') or request.path.startswith('/fav'):
            return
        #request.session.set_test_cookie()
        if request.user.id is not None and request.user.id>0:
            user = request.user.id
        try:
            sess=UserSession.objects.get(user__id=user)
            sess.session_key=request.session.session_key
            sess.time = datetime.now()
            sess.save()
        except:
            if request.session.session_key is None or len(request.session.session_key) >40:
                session_key = request.COOKIES.get(settings.SESSION_COOKIE_NAME, None)
                s = SessionStore(session_key)
                s['last_login'] = datetime.isoformat(datetime.now())
                s.save()
                request.COOKIES['last_login'] =  s['last_login']
            else:
                s = request.session

            sess,created=UserSession.objects.get_or_create(user_id=user,session_key=s.session_key,board_id=None,thread_id=None)
            sess.time = datetime.now()
            sess.session_key=s.session_key
            sess.save()
            request.session = s

        d = timedelta(seconds=3600)
        deldate = datetime.now()-d
        UserSession.objects.filter(time__lt=deldate).delete()
        # delete all sessions that are not in the sessiontable
        UserSession.objects.raw('DELETE from users_usersession WHERE session_key not in (SELECT d.session_key FROM django_session d)')
Exemple #4
0
def date_formatter(value, tooltip, small):
    try:
        value = datetime(value.year, value.month, value.day,
                         value.hour, value.minute, value.second)
    except AttributeError:
        return value
    except ValueError:
        return value

    if getattr(value, 'tzinfo', None):
        now = datetime.now(LocalTimezone(value))
    else:
        now = datetime.now()
    now = now - timedelta(0, 0, now.microsecond)
    if value > now:
        return "Dans le futur"
    else:
        delta = now - value
        # Natural time for today, absolute date after.
        # Reverse if in tooltip
        if (delta.days == 0) != tooltip:
            return naturaltime(value)
        elif small:
            return date(value, 'd/m/y à H\hi')
        else:
            return date(value, 'l d F Y à H\hi')
Exemple #5
0
def date_formatter(value, tooltip, small):
    """
    Format a date to an human readable string.

    :param value: Date to format.
    :param bool tooltip: if `True`, format date to a tooltip label.
    :param bool small: if `True`, create a shorter string.
    :return:
    """
    try:
        value = datetime(value.year, value.month, value.day,
                         value.hour, value.minute, value.second)
    except (AttributeError, ValueError):
        # todo : Check why not raise template.TemplateSyntaxError() ?
        return value

    if getattr(value, 'tzinfo', None):
        now = datetime.now(LocalTimezone(value))
    else:
        now = datetime.now()
    now = now - timedelta(microseconds=now.microsecond)

    if value > now:
        return __DATE_FMT_FUTUR
    else:
        delta = now - value
        # Natural time for today, absolute date after.
        # Reverse if in tooltip
        if (delta.days == 0) != tooltip:
            return naturaltime(value)
        else:
            return date(value, __ABS_DATE_FMT_SMALL if small else __ABS_DATE_FMT_NORMAL)
Exemple #6
0
    def create_user(email):
        user = YackUser()
        user.email = email
        user.quota = 0
        user.name = ""
        user.code = ""
        user.creation_date = datetime.now()
        user.is_admin = False; 

        #Create fisrt admin
        if user.id == 1:
            user.is_admin = True;
            user.quota = -1;
        
        # This save the object
        user.generate_auth_token()
        
        
        #Create root YackPack
        pack = YackPack()
        pack.owner = user;
        pack.creation_date = datetime.now()
        pack.is_public = True;
        pack.save()
        user.pack = pack;
        user.save()    
        
        return user
Exemple #7
0
    def save(self, force_insert=False, force_update=False, using=None,
             update_fields=None):
        if self.date_posted is None:
            self.date_posted = datetime.now()

        self.title_slug = slugify(self.title)
        self.date_last_edited = datetime.now()

        super(Post, self).save(force_insert, force_update, using, update_fields)
Exemple #8
0
    def save(self, *args, **kwargs):
        self.slug = slugify(self.title)

        if not self.created:
            self.created = datetime.now()

        if self.status.id == 1:
            self.published = datetime.now()

        super(Content, self).save(*args, **kwargs)
Exemple #9
0
def getPeriodosDecorridos(anoIngresso, periodoIngresso):
    mesAtual = datetime.now().month
    anoAtual = datetime.now().year

    periodosAnoAtual = getPeriodo(mesAtual)

    # desconsiderar periodoAtual
    numPeriodosDecorridos = (anoAtual - anoIngresso) * 4 - (periodoIngresso - 1) + (periodosAnoAtual - 1)

    return numPeriodosDecorridos
    def create_location(name, longitude, latitude, date=None, date_time=None):
        if date is None:
            date = datetime.now().date()

        if date_time is None:
            date_time = datetime.now()

        location = Location(name=name, location=Point(longitude, latitude), date=date, date_time=date_time)

        location.save()

        return location
Exemple #11
0
def setup_event_tests():
    Eestecer.objects.create_superuser(
        "*****@*****.**",
        "test",
        first_name="specific")
    user = Eestecer.objects.create_user(
        "*****@*****.**",
        "test",
        first_name="random")
    user.save()
    outg = Eestecer.objects.create_user(
        "*****@*****.**",
        "outgoing",
        first_name="outgoing")
    outg.save()
    inc = Eestecer.objects.create_user(
        "*****@*****.**",
        "incoming",
        first_name="incoming")
    inc.save()
    tm = Team.objects.create(name='test',
                             founded=1986,
                             website="http://eestec.ch",
                             address=u"AMIV an der ETH Zuerich\nEESTEC LC Zurich\nCAB "
                                     u"E37\nUniversitätsstrasse 6\n8092 "
                                     u"Zürich\nSwitzerland")
    tm.save()
    tm.users.add(inc)
    tm.privileged.add(inc)
    tm.save()
    to = Team.objects.create(name='outtest',
                             founded=1986,
                             website="http://eestec.ch",
                             address=u"AMIV an der ETH Zuerich\nEESTEC LC Zurich\nCAB "
                                     u"E37\nUniversitätsstrasse 6\n8092 "
                                     u"Zürich\nSwitzerland")
    to.save()
    to.users.add(user, outg)
    to.privileged.add(outg)
    to.save()
    ev = Event.objects.create(name="T4T",
                              description="Cool thing",
                              start_date=datetime.now(),
                              category="workshop",
                              scope="international",
                              deadline=datetime.now() + timedelta(days=1),
    )
    ev.save()
    ev.organizing_committee.add(tm)
    ap = Application.objects.create(target=ev, applicant=user)
    ap.save()
Exemple #12
0
def create_or_update_switches(aggregate, switches):
    """Create or update the switches in aggregate C{aggregate} with switches in C{switches}.
    
    C{switches} is a dict mapping datapath ids to list of ports.
    
    """

    active_switch_ids = []
    active_iface_ids = []
    for dpid, ports in switches.items():
        switch, _ = create_or_update(
            OpenFlowSwitch,
            filter_attrs=dict(
                datapath_id=dpid,
            ),
            new_attrs=dict(
                aggregate=aggregate,
                name=dpid,
                available=True,
                status_change_timestamp=datetime.now(), 
            )
        )
        active_switch_ids.append(switch.id)
        
        for port in ports:
            # update the interfaces for this switch
            iface, _ = create_or_update(
                OpenFlowInterface,
                filter_attrs=dict(
                    switch__datapath_id=dpid,
                    port_num=port,
                ),
                new_attrs=dict(
                    aggregate=aggregate,
                    name="Port %s" % port,
                    switch=switch,
                    available=True,
                    status_change_timestamp=datetime.now(), 
                ),
            )
            active_iface_ids.append(iface.id)
            
    # make all inactive switches and interfaces unavailable.
    OpenFlowInterface.objects.filter(
        aggregate=aggregate).exclude(id__in=active_iface_ids).update(
            available=False, status_change_timestamp=datetime.now())
        
    OpenFlowSwitch.objects.filter(
        aggregate=aggregate).exclude(id__in=active_switch_ids).update(
            available=False, status_change_timestamp=datetime.now())
Exemple #13
0
def add_history(sender, **kwargs):
    instance = kwargs.get('instance')
    if not instance or not instance.id:
        return
    if instance.employer:
        device = Device.objects.get(id=instance.id)
        old_employer = device.employer
        if instance.employer != old_employer:
            History.objects.create(
                old_employer=old_employer,
                employer=instance.employer, device=instance)
            instance.date_action = datetime.now()
            instance.employer.date_action = datetime.now()
            instance.employer.save()
Exemple #14
0
 def show_mail_compose(self, request):
     try:
         if request.is_ajax():
             mail_sent_complete = False
             if request.method == 'POST':
                 form = ComposeMailForm(request.POST)
                 if form.is_valid():
                     new_mail = Message()
                     user = request.user
                     new_mail.id_sender = user
                     user2 = User.objects.get(id= form.cleaned_data['user_id'])
                     new_mail.id_receiver = user2
                     new_mail.datetime = datetime.now()
                     new_mail.id_conversation = 1
                     new_mail.text = form.cleaned_data['text']
                     new_mail.subject = form.cleaned_data['subject']
                     new_mail.save()
                     form = ComposeMailForm()
                     mail_sent_complete = MAILSENTCOMPLETE
             else: 
                 form = ComposeMailForm()
             week = {0:'Lunes',1:'Martes',2:'Miércoles',3:'Jueves',4:'Viernes',5:'Sábado',6:'Domingo'}
             month = {0: 'Enero', 1:'Febrero',2:'Marzo',3:'Abril',4:'Mayo',5:'Junio',6:'Julio',7:'Agosto',8:'Septiembre',9:'Octubre',10:'Noviembre',11:'Diciembre'}
             date_time = week[datetime.today().weekday()] + " " + str(datetime.today().day) + "/" + month[datetime.today().month - 1] + " " + str(datetime.today().year)
             c = { 'form': form , 'date_t':date_time, 'mail_sent_complete' : mail_sent_complete}
             c.update(csrf(request))
             return render_to_response('user_send_mail.html', c)
         else: return HttpResponseRedirect("/usuarios/profile/mail")
         
     except Exception as e: return self.show_error(e)
Exemple #15
0
    def test_is_edited_should_be_true_on_blogpost_created_one_min_ago(self):
        created_long_ago_blogpost = create_dummy_blogpost_posted_at_datetime(
            "one-min-ago", datetime.now() - timedelta(minutes=1))

        self.assertTrue(created_long_ago_blogpost.is_edited())

        created_long_ago_blogpost.delete()
Exemple #16
0
    def get_auth_token(self):
        if not self.auth_token:
            self.generate_auth_token()
        elif self.auth_token_validity < datetime.now():
            self.generate_auth_token()

        return self.auth_token
Exemple #17
0
def direct_messages_details(request, sender_id):
    """
    method to accept new directmessage.
    accepts only post request.
    :param request:
    :return:
    """
    if request.method == "POST":
        # look for posted text
        message_content = request.POST.get("text", False)
        if (not message_content) or len(message_content) < 1:
            # if there is no text or the text is too short redirect and show error
            messages.error(request, "Kein Text angegeben")
            return HttpResponseRedirect(reverse("home"))
        # create a new direct message and fill in data, then save it, if successful
        message_var = Directmessage()
        message_var.creator = request.user
        message_var.created = datetime.now()
        message_var.text = message_content
        try:
            message_var.receiver = User.objects.get(username=sender_id)
        except ObjectDoesNotExist:
            messages.error(request, "Den Empfaenger gibt es nicht")
            return HttpResponseRedirect(reverse("home"))
        message_var.save()
        return HttpResponseRedirect("%s?active_conversation=%s" % (reverse("all_chats"), message_var.receiver.username))
Exemple #18
0
def __send_system__message__(receiver, message, level="info"):
    """
    convenience method for sending system messages/notifications
    :param receiver: the id of the receiver
    :param message: the message content
    :param level: the level, currently supported are one of: info, news, danger
    :return:
    """
    system_user = User.objects.get(username="******")
    try:
        receiver = User.objects.get(pk=receiver)
    except ObjectDoesNotExist:
        # this should not happen, as we are sending notifications only after successful operations,
        # so the user was found before, but not yet.
        # seems to be an internal error or the user just deleted his account
        # TODO log internen fehler
        return
    sysMsg = Directmessage(creator=system_user, created=datetime.now(), receiver=receiver)
    level_msgs = {
        "info": "I%s",
        "news": "N%s",
        "danger": "D%s"
    }
    try:
        sysMsg.text = level_msgs[level] % message
    except KeyError:
        sysMsg.text = level_msgs["info"] % message
    sysMsg.save()
Exemple #19
0
    def save(self, *args, **kwargs):
        try:
            self.slug = slugify(self.name)
            geocoder = Geocoder()
            address = self.address
            results, status_code = geocoder.geocode({'address': self.name})
            self.lat, self.lng = results[0]['geometry']['location']['arg']
        except:
            pass

        super(Team, self).save(*args, **kwargs)
        privileged, created = Group.objects.get_or_create(name=self.slug + "_privileged")
        privileged.save()
        privileged.user_set = self.privileged()
        privileged.save()
        assign_perm('change_team', privileged, self)
        if not self.pk:
            a = Event.objects.create(
                name=str(self.slug + " recruitment"),
                scope="local",
                category="recruitment",
                description="We are always recruiting and welcoming new people.",
                start_date=datetime.now()
            )
            a.save()
            a.organizing_committee = [self]
Exemple #20
0
def showNewsByTitle(request, newsTitle):
    """Returns single news with all of category based on the 'newsTitle'"""
    news = News.objects.get(url=u"%s.html" % newsTitle)

    if request.POST:
        data = request.POST.copy()
        data["news"] = news.id
        data["datetime"] = datetime.now()
        form = CommentsForm(data)

        if form.is_valid():
            if hashlib.sha1(request.POST["token"]).hexdigest() == request.session["token_news_%s" % news.id]:
                form.save()

            else:
                del data["token"]
                form = CommentsForm(data)

                return render_to_response(
                    "news.html",
                    {"news": news, "form": form, "tokenValid": "0"},
                    context_instance=RequestContext(request),
                )

            return HttpResponseRedirect(u"%s.html" % newsTitle)

    else:
        form = CommentsForm()

    return render_to_response(
        "news.html",
        {"news": news, "form": form, "error": form._get_errors(), "tokenValid": "1"},
        context_instance=RequestContext(request),
    )
Exemple #21
0
def get_lease(request, term=1):
    response_data = dict()

    term = int(term)
    if term > 10:
        term = 10

    search = BoardLease.objects.filter(end_date__gte=safe_datetime.now())

    if search.count() > 0:
        response_data['result'] = 'failure'
        response_data['reason_code'] = 'in_use'
    else:
        m = md5.new()
        m.update(unicode(datetime.now().microsecond.__str__))
        lease_code = m.hexdigest()

        lease_expiry = datetime.now() + timedelta(seconds=term * 60)
        new_lease = BoardLease(board_lease_code=lease_code, is_active=True, start_date=datetime.now(), end_date=lease_expiry, creation_date=datetime.now())
        new_lease.save()

        response_data['result'] = 'success'
        response_data['lease_code'] = lease_code
        response_data['lease_expiry'] = str(lease_expiry)

    return HttpResponse(json.dumps(response_data), mimetype="application/json")
Exemple #22
0
 def save(self,**kwargs):
     """
     Automatic update the created_at date time
     """
     if not self.id:
         self.created_at = datetime.now()
     super(TestUrl, self).save(**kwargs)
Exemple #23
0
 def personne(self, alll=False):
     self.listpers = []
     login = "******"
     if alll:
         ADRR = [None, "klqekljsqdjlqksjdq"]
         LIEU = [None, "lqsdkjqsdkj"]
         DATE = [None, datetime.now()]
         PROM = [None, 2012]
         n = 121212121
         NUMB = [None, n]
         EMAILl = [None, "*****@*****.**"]
         
         for adresse in ADRR:
             for lieuDeNaissance in LIEU:
                 for dateDeNaissance in DATE:
                     for promotion in PROM:
                         for numeroDeTel in NUMB:
                             for email in EMAILl:
                                 for sexe in SEXE:
                                     for typeP in TYPE:
                                         nom = "mdr"
                                         prenom = "mdr2"
                                         login = login + "l"
                                         mdp = "smdkqsmldkqslmdkqmlsdk"
                                         repo = addPersonne(self.puser, nom, prenom, login, mdp, sexe[0], typeP[0], adresse, promotion, dateDeNaissance, lieuDeNaissance, numeroDeTel, email)
                                         self.assertFalse(type(repo) is str)
                                         self.listpers.append(repo)
                                         
     else:
         self.listpers.append(addPersonne(self.puser, "jean", "jean", login, "1234567", SEXE[1][0], TYPE[1][0]))
     deux=addPersonne(self.puser, "jean", "jean", login, "1234567", SEXE[1][0], TYPE[1][0])                             
     self.assertTrue(type(deux) is str)
Exemple #24
0
def get_current_lease(lease_code):
    search = BoardLease.objects.filter(end_date__gte=safe_datetime.now())
    search.filter(board_lease_code=lease_code)
    try:
        return search.get()
    except BoardLease.DoesNotExist:
        return None
Exemple #25
0
def format_date_time(dt):
  if not dt:
    return ''
  if not isinstance(dt, (datetime, old_datetime)):
    raise ValueError(u'can not format a incorrect datetime')

  now = datetime.now()
  time_str = dt.strftime('%H:%M')
  diff = now - dt
  if diff.days == 0:
    if diff.seconds < 60:
      return u'%s秒前' % diff.seconds
    if diff.seconds < 3600:
      return u'%s分钟前' % (diff.seconds / 60)
    return u'%s个小时前' % (diff.seconds / 3600)
  else:
    diff = now.date() - dt.date()

  if diff.days == 1:
    return u'昨天 ' + time_str
  elif diff.days == 2:
    return u'前天' + time_str
  elif diff.days < 15:
    return u'%s天前' % diff.days
  else:
    return dt.strftime('%y-%m-%d %H:%M')
Exemple #26
0
def main(request, page):
    active_lans = LAN.objects.filter(end_date__gte=datetime.now())
    if len(active_lans) > 0:
        articles = Article.objects.filter(relevant_to__in=active_lans).order_by('-pinned', '-pub_date')
    else:
        return redirect('archive')

    paginator = Paginator(articles, 10)  # Articles per page
    streams = Stream.objects.filter(active=True).order_by('-pk')[:1]

    try:
        articles = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        articles = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        articles = paginator.page(paginator.num_pages)
    except Exception:
        # If no page is given, show the first
        articles = paginator.page(1)

    if len(streams) > 0:
        return render(request, 'news/news.html', {'articles': articles, 'page': page, 'stream': streams[0],
                                                  'languages': settings.LANGUAGES})
    else:
        return render(request, 'news/news.html', {'articles': articles, 'page': page, 'languages': settings.LANGUAGES})
Exemple #27
0
    def get(self, request, id=None):
        dining_list = DiningList.get_latest()

        if id == None:
            if dining_list.owner is not None and datetime.now().time() > dining_list.closing_time:
                messages.error(request, "De eetlijst is al geclaimed. Vraag aan de kok/bestuur of je er nog af mag.")
                return redirect("dining:index")

            if dining_list.user_in_list(request.user):
                if dining_list.owner == request.user:
                    dining_list.owner = None
                    dining_list.save()
                dining_list.remove_user(request.user)
                messages.success(request, "Je bent uitgeschreven van deze eetlijst")
            else:
                messages.error(request, "Je staat nog niet op deze eetlijst")
        else:
            if request.user == dining_list.owner:
                part = DiningParticipation.objects.get(id=id)
                part.mail("Je bent verwijderd van de eetlijst",
                          "De kok gaat koken met een van de items op jouw \"Haal me van de eet-lijst\" items. Hierdoor ben je van de eetlijst afgehaald.")

                messages.success(request, u"{0} is van de eetlijst afgegooid.".format(part.user.get_full_name()))
                part.delete()
            else:
                messages.error(request, "Je hebt hier geen rechten voor!")

        return redirect("dining:index")
Exemple #28
0
    def render(self, context, instance, placeholder):
        
        start_time = datetime.now()
        if instance.show_today == True:
            start_time = start_time.replace(hour=0, minute=0, second=0)
        else:
            start_time = start_time -timedelta(hours=1)
            
        if instance.instances == 0:
            # show all
            events = instance.calendar_plug.occurrences_after(start_time)
        else:
            events=list()
            loops = instance.instances
            for object in instance.calendar_plug.occurrences_after(start_time):
                loops = loops -1
                events.append(object)  
                if loops == 0:
                    break

        context.update({
            'events':events,
            'object':instance,
            'placeholder': placeholder,
            'instances': instance.instances
        })
        return context
    def save_model(self, request, newsletter, form, change):
        newsletter.save()
        workgroups = []
        if not newsletter.pk and not request.user.is_superuser \
               and USE_WORKGROUPS:
            workgroups = request_workgroups(request)

#        if newsletter.content.startswith('http://'):
#            if CAN_USE_PREMAILER:
#                try:
#                    premailer = Premailer(newsletter.content.strip())
#                    newsletter.content = premailer.transform()
#                except PremailerError:
#                    self.message_user(request, _('Unable to download HTML, due to errors within.'))
#            else:
#                self.message_user(request, _('Please install lxml for parsing an URL.'))
        clusters = Cluster.objects.filter(publish=True).exclude(id='services')
        quote = Quote.objects.order_by('?')[0]
        smlinks = Socialmedialink.objects.all()
        context = {'newsletter': newsletter,
                    'domain': Site.objects.get_current().domain,
                    'CLUSTERS':clusters,
                    'QUOTE':quote,
                    'SOCIALMEDIALINKS':smlinks,
                    'location':Location.objects.get(town='amsterdam'),
                    'YEAR': datetime.now().year,
                    'MEDIA_URL': settings.MEDIA_URL,}
        newsletter.content = get_content(newsletter, context)
        newsletter.save()

        if not request.user.has_perm('newsletter.can_change_status'):
            newsletter.status = form.initial.get('status', Newsletter.DRAFT)

        for workgroup in workgroups:
            workgroup.newsletters.add(newsletter)
Exemple #30
0
def report_message(request, message_id):
    """
    Report a circlemessage with given <message_id>, if that exists.
    If that does not exist, then an error for the user is returned and he gets redirected to home.
    If that message exists,
        then the report will be created, if an reason (report.text) was given.
            The report is saved then.
        if there is no reason, an error will be created and the user is redirected to home.
    :param request:
    :param message_id:
    :return:
    """
    try:
        reported_message = Circle_message.objects.get(pk=message_id)
    except Exception:
        messages.error(request, "Die Nachricht existiert nicht")
        return HttpResponseRedirect(reverse("home"))
    if request.method == "POST":
        report = CircleMessageReport()
        report.reported_message = reported_message
        report.text = request.POST.get("text", False)
        if not report.text or len(report.text) < 1:
            messages.error(request, "Keine Begruendung angegeben")
            return HttpResponseRedirect(reverse("home"))
        report.creator = request.user
        report.created = datetime.now()
        report.save()
        messages.success(request, "Nachricht wurde gemeldet")
        return HttpResponseRedirect(reverse("home"))
    reported_profile = Profile.objects.get(pk=reported_message.creator.pk)
    return render(request, "logged_in/report_post.html",
                  {"profile": reported_profile, "circlemessage": reported_message})
Exemple #31
0
def confirm_account(request, username, key):
    context = base(req=request)
    confirm_obj = get_object_or_404(UserConfrimationKeys,
                                    user__username=username,
                                    key=key,
                                    expired_date__gte=datetime.now(),
                                    expired=False)
    confirm_obj.expired = True
    confirm_obj.user.is_active = True
    confirm_obj.user.save()
    confirm_obj.save()
    # next_url = request.GET.get('next_url')
    # if next_url:
    #     pass
    # else:
    context['message'] = _('Your account has been confirmed successfully')
    response = render(request, 'base-user/confirm.html', context=context)
    return response
Exemple #32
0
 def test_details_returns_correct_html(self):
     request = HttpRequest()
     request.method = 'GET'
     generic_window_view = WindowDetailView()
     generic_window_view.request = request
     generic_window_view.kwargs = {'slug': self.window.slug}
     response = generic_window_view.dispatch(request)
     self.assertEqual(response.status_code, 200)
     now = datetime.now().replace(microsecond=0)
     expected_html = render_to_string(
         'windows/window_detail.html', {
             'window': self.window,
             'timestamp': now
         },
         context_instance=RequestContext(request))
     self.assertEqual(response.rendered_content.decode(), expected_html)
     # Check last update timestamp format
     self.assertContains(response, now.strftime('%Y-%m-%d @ %H:%M:%S'))
Exemple #33
0
 def get_or_assign_number(self):
     """
     Set a unique number to identify this Order object. The first 4 digits represent the
     current year. The last five digits represent a zero-padded incremental counter.
     """
     if self.number is None:
         epoch = datetime.now().date()
         epoch = epoch.replace(epoch.year, 1, 1)
         aggr = Order.objects.filter(number__isnull=False,
                                     created_at__gt=epoch).aggregate(
                                         models.Max('number'))
         try:
             epoc_number = int(str(aggr['number__max'])[4:]) + 1
             self.number = int('{0}{1:05d}'.format(epoch.year, epoc_number))
         except (KeyError, ValueError):
             # the first order this year
             self.number = int('{0}00001'.format(epoch.year))
     return self.get_number()
Exemple #34
0
 def get(self, request):
     current_month = datetime.now().month
     user = request.user
     Clothes = Expenses.objects.filter(user=user,
                                       date__month=current_month,
                                       category=26)
     clothes = 0.0
     for g in Clothes:
         clothes += float(g.amount)
     Shoes = Expenses.objects.filter(user=user,
                                     date__month=current_month,
                                     category=27)
     shoes = 0.0
     for r in Shoes:
         shoes += float(r.amount)
     summ = shoes + clothes
     ctx = {'sum': summ, 'clothes': clothes, 'shoes': shoes}
     return render(request, 'noname/clothes.html', ctx)
class X_news(models.Model):
    '''校学生会的新闻'''
    title = models.CharField(max_length=100)
    body = models.TextField()
    image = models.ImageField(upload_to='static/xxsh/xnews')
    video = models.CharField(max_length=200, blank=True)
    exc_editor = models.CharField(max_length=20, default='本新闻执行编辑')
    duty_editor = models.CharField(max_length=20, default='本新闻责任编辑')
    view_num = models.IntegerField(default=0)
    datetime = models.DateTimeField(default=datetime.now())
    department = models.ForeignKey(Department)

    class Meta:
        verbose_name = u'校学生会新闻'
        verbose_name_plural = u'校学生会新闻'

    def __unicode__(self):
        return self.title
Exemple #36
0
 def get(self, request):
     last_login = '******'
     if request.session.get('last_login', False):
         last_login = datetime.strptime(request.session.get('last_login'), '%Y-%m-%d %H:%M:%S')
         time_elasped = datetime.now() - last_login
         if time_elasped.seconds > 3600:
             # its been more than hour
             logout(request)
             last_login = '******'
         else:
             pass
     else:  # you are not logged in
         pass
     top_list = Topic.objects.all().order_by('id')[:10]
     return render(request, 'myapp/index.html', {
         'top_list': top_list,
         'last_login': last_login,
     })
Exemple #37
0
def wallet_api_view(request):
    """
        Recibe un token.
        Devuelve la billetera correspondiente a un usuario.
    """

    if request.method == 'POST':
        result = ''
        try:
            token = AuthToken.objects.get(token_key=request.data['token'][:8])
            if token.expiry > datetime.now(timezone.utc):
                wallet_id = Wallet.objects.get(user_id=token.user_id)
                if wallet_id:
                    result = wallet_id.id
        except Exception:
            return Response(str(result), status=status.HTTP_200_OK)

        return Response(str(result), status=status.HTTP_200_OK)
class Information(models.Model):
    datetime = models.DateTimeField(default=datetime.now())
    view_num = models.IntegerField(default=0)
    title = models.CharField(max_length=100)
    image = models.ImageField(upload_to='static/xxsh/information',
                              default=None,
                              blank=True,
                              null=True)
    body = models.TextField()
    exc_editor = models.CharField(max_length=20, default='本公告执行编辑')
    duty_editor = models.CharField(max_length=20, default='本公告责任编辑')

    class Meta:
        verbose_name = u'公告'
        verbose_name_plural = u'公告'

    def __unicode__(self):
        return self.title
Exemple #39
0
def collect_about_data():
    response = get_response('guilds')
    if response.ok:
        data = response.json()
        cache.set('about_monitoring', {
            'data': data,
            'last_update': datetime.now()
        })
        about = About.objects.filter(name=data['Name'])
        if about:
            about = about[0]
            about.alliance = data['AllianceTag']
            about.member_count = data['MemberCount']
            about.death_fame = data['DeathFame']
            about.kill_fame = data['killFame']
            about.guild_id = data['Id']
            about.alliance_id = data['AllianceId']
            about.save()
 def get_bill(self, request, pk):
     order = get_object_or_404(Orders.objects.all(), pk=pk)
     bill = {
         "title":
         order.product.name,
         "price":
         order.product.price,
         "discount":
         f"{order.product.discount} %",
         "amount_to_pay":
         amount_to_pay(order.product.discount, order.product.price),
         "date_order":
         order.date_created_order.strftime("%d-%m-%Y %H:%M:%S"),
         "date_bill":
         datetime.now().strftime("%d-%m-%Y %H:%M:%S")
     }
     serializer = BillsSerializer(bill, many=False)
     return Response(serializer.data)
Exemple #41
0
def add_youtube(request):
    meta = {
        'title': 'Dodaj film',
    }
    if request.method == 'POST':
        form = YouTubeForm(request.POST)
        if form.is_valid():
            name = form.cleaned_data['name']
            video_id = form.cleaned_data['video_id']
            try:
                YouTube.objects.get(video_id=video_id)
                return render(
                    request, 'service/youtube_form.html', {
                        'form': form,
                        'info':
                        ['red', 'Podany film już jest w naszej bazie!']
                    })
            except ObjectDoesNotExist:
                YouTube.objects.create(name=name,
                                       video_id=video_id,
                                       add_date=datetime.now(),
                                       accepted=False)
                send_mail(
                    'Nowy film: ' + name,
                    'Dodano nowy film do bazy danych',
                    '*****@*****.**',
                    ['*****@*****.**'],
                    fail_silently=False,
                )
                return render(
                    request, 'service/youtube_form.html', {
                        'form':
                        form,
                        'info': [
                            'green',
                            'Film został dodany! Oczekuje na akceptację'
                        ]
                    })
    else:
        form = YouTubeForm()
    return render(request, 'service/youtube_form.html', {
        'form': form,
        'meta': meta_generator(meta)
    })
Exemple #42
0
class AccessRule(models.Model):
    post = models.ForeignKey(Post, blank=True)
    group = models.ForeignKey(KGroup, blank=True)
    VISIBILITY_CHOICES = (
        ('BUS', 'Busy Only'),
        ('ALL', 'All'),
        ('MOD', 'Modify'),
    )
    visibility = models.CharField(max_length=3, choices=VISIBILITY_CHOICES)
    order = models.PositiveIntegerField()

    RESPONSE_CHOICES = (
        ('CONFIRM', 'Confirm'),
        ('DECLINE', 'Decline'),
        ('REMOVED', 'Removed'),
        ('NO_RESP', 'No response'),
    )

    # receiver_response is set to NO_RESP when an AccessRule is created/ when an event is shared.
    # NO_RESP requires the receiver of the event to respond to the creation request.
    # receiver_response needs to be set to NO_RESP when ever the owner of the event modifies the
    # specs of the event
    receiver_response = models.CharField(max_length=7,
                                         choices=RESPONSE_CHOICES,
                                         default='NO_RESP')

    # If just setting the precedence, the owner of the event may not want whoever the event is shared with to
    # get a notification of the sharing.
    # But the current implementation is that we notify whoever we shared with whenever we share
    # Also used when the originator updates the post content
    notify_receiver = models.BooleanField(default=False)

    # When a receiver of the event modifies it, this field should be
    notify_owner = models.BooleanField(default=False)

    # The receiver of the post can set notification for this event that is shared with her/him
    notification_email = models.BooleanField(default=False)
    notify_when = models.DateTimeField(default=datetime.now())

    # For the originator to approve or reject
    approve_change = models.BooleanField(default=False)

    def __unicode__(self):
        return '{0},{1}'.format(self.post.content, self.group.name)
Exemple #43
0
    def get_context_data(self, **kwargs):
        context = super(LobbyStatus, self).get_context_data(**kwargs)

        # get current lobbies from cache
        lobbies = [cache.get(bot) for bot in cache.get('bots', [])]

        # list of all members in all lobbies
        members = itertools.chain(*[lobby['members'] for lobby in lobbies])
        members = Player.objects.filter(dota_id__in=members)

        # get players info from db
        for lobby in lobbies:
            players_num = total_mmr = 0
            for team in lobby['teams']:
                for slot, player in enumerate(team):
                    print('slot: %s   player: %s' % (slot, player))
                    try:
                        player = next(p for p in members
                                      if p.dota_id == str(player['dota_id']))
                        team[slot] = player
                        players_num += 1
                        total_mmr += player.dota_mmr
                    except (TypeError, StopIteration):
                        # empty slot or unregistered player, it's fine
                        pass
            lobby['free_slots'] = 10 - players_num
            if players_num > 0:
                lobby['average_mmr'] = total_mmr // players_num

        # calc duration for started games
        for lobby in lobbies:
            if lobby['state'] == 'game':
                lobby['game_duration_mins'] = (
                    datetime.now() - lobby['game_start_time']).seconds // 60

        context.update({
            'lobbies':
            lobbies,
            'lobbies_ready':
            sum(lobby['state'] == 'ready' for lobby in lobbies),
            'lobbies_game':
            sum(lobby['state'] == 'game' for lobby in lobbies),
        })
        return context
Exemple #44
0
def car_out(request):
    if request.method == 'GET':
        car_nos = Parking.objects.filter(Cat_status=True)
        return render(request, 'car_out.html', context=locals())
    elif request.method == 'POST':
        car_no = request.POST.get('car_no')
        print(car_no)
        # car_rm = Parking.objects.filter(P_Car_no=car_no).first()
        car_rm = Parking.objects.filter(Cat_status=True).get(
            P_Car_no__Car_no=car_no)
        # print(car_rm)
        car_w = Car_w.objects.get(Car_w_no=car_rm.P_Car_w_no.Car_w_no)
        car_w.Car_w_status = True
        car_w.save()
        intime = car_rm.In_time
        outtime = datetime.now()
        car_rm.Out_time = outtime
        intime_str = intime.strftime("%Y-%m-%d %H:%M:%S")
        outtime_str = outtime.strftime("%Y-%m-%d %H:%M:%S")
        intime_f = intime.timestamp()
        outtime_f = outtime.timestamp()
        alltime = outtime_f - intime_f
        alltime = int(alltime / 60 + 1)
        time_hour = int(alltime / 60)
        time_min = alltime - time_hour * 60
        pri_time = int(alltime / 60 + 1)
        Money = pri_time * car_rm.P_price
        car_rm.P_Money = Money
        car_rm.All_time = alltime
        car_rm.Cat_status = False
        car_rm.save()

        print(intime, outtime)
        print(type(intime))
        hourtime = alltime / 60 + 1
        context = {
            'car_no': car_no,
            'intime': intime,
            'outtime': outtime,
            'alltime': hourtime,
            'money': Money,
        }
        # print(type(car_no), car_no)
        return render(request, 'pay.html', context=locals())
 def _create_blog_article_page(
     self,
     blog_index_page=None,
     title="Simple Article Title",
     page_title="Simple Article Title",
     date=datetime.now(),
     body=None,
     author=None,
     read_time=7,
     table_of_contents=False,
     recommended_articles=None,
     views=0,
     cover_photo=None,
     article_photo=None,
     is_main_article=False,
 ):
     if body is None:
         block = StreamBlock([(ArticleBodyBlockNames.MARKDOWN.value,
                               MarkdownBlock())])
         body = StreamValue(
             block,
             [(ArticleBodyBlockNames.MARKDOWN.value, "Hello, World")])
     if author is None:
         author = BossFactory()
     blog_article_page = BlogArticlePage(
         title=title,
         page_title=page_title,
         date=date,
         body=body,
         author=author,
         read_time=read_time,
         table_of_contents=table_of_contents,
         recommended_articles=recommended_articles,
         views=views,
         cover_photo=cover_photo,
         article_photo=article_photo,
         is_main_article=is_main_article,
     )
     if blog_index_page is None:
         blog_index_page = self._get_newest_blog_index_page()
     blog_index_page.add_child(instance=blog_article_page)
     blog_article_page.save()
     return blog_article_page
Exemple #46
0
def ResponderSugestao(request, id):
    try:# Verificar se usuario esta logado
        if request.session['nomesugestao']:
            pass
    except KeyError:
        return redirect(r('Login'))

    #Preencher Formulário

    sugestao = Sugestao.objects.get(id=id)#Buscar dados da sugestão a ser alterada

    #criar instancia do formulário preencido
    form = SugestaoEdicaoForm(initial={'descricao': sugestao.descricao})
    #Verifica se vieram dados pelo post
    if request.method == 'POST':
        form = SugestaoEdicaoForm(request.POST)
        if form.is_valid():# se dados do formulário são válidos, salva os dados na linha abaixo
            resposta = Resposta(descricao=request.POST['descricao'], datahora=datetime.now(), sugestao=Sugestao.objects.get(id=id), pessoa=Pessoa.objects.get(usuario=request.session['userl']))
            resposta.save()

            # Send email
            # Preparação de contexto
            contexto = form.cleaned_data
            contexto['id'] = resposta.sugestao.id
            contexto['senha'] = resposta.sugestao.senha
            contexto['pessoa'] = resposta.pessoa.nome
            contexto['titulo'] = "A Sugestão "+str(resposta.sugestao.id) +" foi respondida"

            # tenta recuperar o email do criador da sugestão
            mail = resposta.sugestao.pessoa.email
            if mail == 'Não informado':
                mail = ''
            # Envio da msg
            _send_email('Sugestão '+ str(resposta.sugestao.id),
                [settings.DEFAULT_FROM_EMAIL, ],
                sugestao.setor.email, mail,
                'sugerir/resposta_email.html',
                contexto)

            messages.success(request, 'Resposta salva com sucesso!')
            return redirect(r('DetalharSugestao', str(sugestao.id), resposta.sugestao.senha))

    return render(request, 'sugerir/cadastro_sugestao.html', {'URL': 'ResponderSugestao', 'err': '','id': id, 'form': form, 'itemselec': 'HOME', 'titulo': 'Responder Sugestão'})
Exemple #47
0
def initComplet():
    from aula.apps.alumnes.models import Alumne,  Curs
    from aula.apps.incidencies.models import Sancio, Expulsio, Incidencia
    from aula.apps.presencia.models import Impartir, ControlAssistencia, NoHaDeSerALAula
    from aula.apps.baixes.models import Feina
    from aula.apps.horaris.models import Horari, Festiu
    from aula.apps.aules.models import ReservaAula
    from aula.apps.tutoria.models import Tutor, TutorIndividualitzat, CartaAbsentisme

    from django.db.models import Q
    
    try:
        avui=datetime.now()
        
        #Modifica data per evitar restricció per antiguitat
        Incidencia.objects.update(dia_incidencia=avui.date())
        Incidencia.objects.all().delete()
        Expulsio.objects.all().delete()
        Sancio.objects.all().delete()
        ControlAssistencia.objects.all().delete()
        Feina.objects.all().delete()
        Impartir.objects.all().delete()
        Horari.objects.all().delete()
        Festiu.objects.all().delete()
        ReservaAula.objects.all().delete()

        NoHaDeSerALAula.objects.all().delete()

        CartaAbsentisme.objects.all().delete()

        Tutor.objects.all().delete()
        TutorIndividualitzat.objects.all().delete()

    except Exception as e:
        return ["Error:"+str(e)]

    # Esborra usuaris alumne sense alumne associat
    User.objects.filter(username__startswith='almn',alumne__isnull=True).delete()

    # Elimina dates d'inici i final de curs
    Curs.objects.all().update(data_inici_curs=None, data_fi_curs=None)
    
    return []
class FixServer(models.Model):
    name = models.CharField(max_length=100,
                            default=None,
                            null=True,
                            blank=True)
    title = models.CharField(max_length=100,
                             default=None,
                             null=True,
                             blank=True)
    text = models.TextField(default=None, null=True)
    image = models.ImageField(upload_to='static/xxsh/Fixserver',
                              default=None,
                              blank=True,
                              null=True)
    datetime = models.DateTimeField(default=datetime.now())

    class Meta:
        verbose_name = u'后勤报修'
        verbose_name_plural = u'后勤报修'
Exemple #49
0
 def get(self, request):
     current_month = datetime.now().month
     user = request.user
     Things = Expenses.objects.filter(user=user,
                                      date__month=current_month,
                                      category=31)
     things = 0.0
     for g in Things:
         things += float(g.amount)
     Extras = Expenses.objects.filter(user=user,
                                      date__month=current_month,
                                      category=32)
     extras = 0.0
     for r in Extras:
         extras += float(r.amount)
     School = Expenses.objects.filter(user=user,
                                      date__month=current_month,
                                      category=33)
     school = 0.0
     for s in School:
         school += float(s.amount)
     Games = Expenses.objects.filter(user=user,
                                     date__month=current_month,
                                     category=34)
     games = 0.0
     for _ in Games:
         games += float(_.amount)
     Nanny = Expenses.objects.filter(user=user,
                                     date__month=current_month,
                                     category=35)
     nanny = 0.0
     for i in Nanny:
         nanny += float(i.amount)
     summ = things + extras + school + games + nanny
     ctx = {
         'sum': summ,
         'things': things,
         'extras': extras,
         'school': school,
         'games': games,
         'nanny': nanny
     }
     return render(request, 'noname/child.html', ctx)
Exemple #50
0
 def p_time_ago(self):
     if self.created:
         now_time = int(time.mktime(datetime.now().replace(tzinfo=utc).timetuple()))
         created = int(time.mktime(self.created.timetuple()))
         seconds = (now_time - created) - 19800
         if seconds > 86400:
             day = self.created.day
             suffix = {1: "st", 2: "nd", 3: "rd"}\
                 .get(day if (day < 20) else (day % 10), 'th')
             return format(self.created, "%d{0} %b{1}".format(suffix, ' %Y' \
                 if localtime(now()).year != self.created.year else ''))
         elif (seconds > 3600) and (seconds < 86400):
             hours = seconds / 3600
             return str(math.floor(hours)).zfill(2) + ' hrs ago'
         elif (seconds > 60) and (seconds < 3600):
             minutes = seconds / 60
             return str(math.floor(minutes)).zfill(1) + ' mins ago'
         else:
             return 'Just now'
Exemple #51
0
def getMailsList(mail, num=None, dies=15):
    '''
    Retorna la llista dels identificadors de correus rebuts al 
    servidor mail des del número num (no inclós) o els últims dies indicats.
    Es farà servir per al fetch de cada correu.
    mail connexió al servidor imaplib.IMAP4_SSL
    num en bytes, numeració a partir de la qual volem els correus (num no inclòs)
    dies enter, si num es None fa servir aquests dies per obtenir els correus
    
    Retorna la llista (pot ser buida) o None en cas d'error.
    
    '''

    if mail:
        # Prepara el command corresponent
        if num:
            #  rang mails  'num:*'  Ex:  2000:*   1:*
            cmd = str(int(num) + 1) + ':*'
        else:
            #  desde data Ex: '(SENTSINCE "2-Feb-2020")'
            months = [
                "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep",
                "Oct", "Nov", "Dec"
            ]
            data = datetime.now() - timedelta(days=dies)
            data = str(data.day) + "-" + months[data.month - 1] + "-" + str(
                data.year)
            cmd = '(SENTSINCE "' + data + '")'
        #print(cmd)
        try:
            _, dades = mail.search(None, cmd)
            mail_ids = dades[0]
            id_list = mail_ids.split()
            if num and id_list and len(id_list) > 0:
                ultim = id_list[len(id_list) - 1]
                if ultim > num:
                    # Comprova que n'hi han nous emails
                    return id_list
            else:
                return id_list
        except:
            return None
    return None
Exemple #52
0
 def test_create_series_for_archived_type_fails(self):
     url = '/api/activity-series/'
     recurrence = rrule.rrule(
         freq=rrule.WEEKLY,
         byweekday=[0, 1]  # Monday and Tuesday
     )
     start_date = self.group.timezone.localize(datetime.now().replace(hour=20, minute=0))
     self.client.force_login(user=self.member)
     response = self.client.post(
         url, {
             'activity_type': self.archived_activity_type.id,
             'max_participants': 5,
             'place': self.place.id,
             'rule': str(recurrence),
             'start_date': start_date
         },
         format='json'
     )
     self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.data)
Exemple #53
0
 def test_pickup_series_create_activates_group(self):
     url = '/api/pickup-date-series/'
     recurrence = rrule.rrule(
         freq=rrule.WEEKLY,
         byweekday=[0, 1]  # Monday and Tuesday
     )
     start_date = self.group.timezone.localize(datetime.now().replace(hour=20, minute=0))
     pickup_series_data = {
         'max_collectors': 5,
         'place': self.place.id,
         'rule': str(recurrence),
         'start_date': start_date
     }
     self.group.status = GroupStatus.INACTIVE.value
     self.group.save()
     self.client.force_login(user=self.member)
     self.client.post(url, pickup_series_data, format='json')
     self.group.refresh_from_db()
     self.assertEqual(self.group.status, GroupStatus.ACTIVE.value)
Exemple #54
0
    def checked_claims(self):
        """
        Creates and returns a dictionary of `jwt.JWT` claims that will be checked for presence and validity
        """
        issue_date = datetime.now()
        self.activation_date = issue_date if not self.activation_date else self.activation_date
        self.expiry_period = TOKEN_EXPIRY if self.expiry_period is None else self.expiry_period

        expiry_date = self.activation_date + self.expiry_period
        activation_secs = int(self.activation_date.strftime('%s'))
        expiry_secs = int(expiry_date.strftime('%s'))
        assert (expiry_secs > activation_secs
                ), 'Expiration date must be a date later than activation date'
        return {
            'nbf': activation_secs,
            'exp': expiry_secs,
            'iat': int(issue_date.strftime('%s')),
            'sub': self.subject,
        }
Exemple #55
0
    def register_report(self, postValues):
        """
        we assume we will not register a child without a report, and a report without a child
        :param postValues:
        :return:
        """
        report = None
        params = postValues.copy()

        if params.get('child'):

            try:
                report = DailyChildReport.objects.get(id = params.get('report_id'))
                day_price = params.get('day_price')
            except DailyChildReport.DoesNotExist:
                report = DailyChildReport( day_price = params.get('day_price'),
                                            date_created=datetime.now(),
                                            day = datetime.today()
                                        )
            try:
                child = ChildService.get_child(child = params.get('child'))
                if not child:
                    raise CriticalError({'message': "Report was not saved, child not found. Try again."})
                repas = RepasService.register_repas(postValues)
                if not repas:
                    raise CriticalError({'message': "Report was not saved, repas was not saved. Try again."})
                principal = PrincipalService.get_principal(principal_id=params.get('principal'))
                if not principal:
                    raise CriticalError({'message': "Report was not saved, accueillante was not saved. Try again."})
                report.child = child
                report.accueillante = principal
                report.repas = repas
                report.save()
                activities = params.get('activities')
                for act in activities:
                    self.add_activity(report, act)
                if report.activities.count() == 0:
                    raise CriticalError({'message': "The activities were not saved. Try again."})
            except Exception:
                raise CriticalError({'message': "Unkwon Error while saving child daily report. Try again or contact system admin "})

        return report
Exemple #56
0
def sell_item(request):
    # Collecting Data
    serializer = SellItemSerializers(data=request.data)
    if serializer.is_valid():
        name = serializer.data.get("name")
        number = serializer.data.get("number")

        try:
            # If we had multiple item, sell the first one
            temp = Item.objects.filter(name=name)
            item = temp[0]
        except:
            return Response(status=status.HTTP_404_NOT_FOUND)
        try:
            # Check Is Number Positive
            new_number = item.number - number
            print("sell nubmer: " + str(item.number))
            print("new nubmer: " + str(new_number))
            if new_number < 0:
                print("error, you cant sell that much")
                return Response(data={"response": "you can not sell that much"}, status=status.HTTP_406_NOT_ACCEPTABLE)

            # Update number of item
            old_item = Item.objects.filter(name=name).update(number=new_number)
        except:
            return Response(status=status.HTTP_409_CONFLICT)
        # Set Response
        if old_item:
            # Save the Log
            log = Log.objects.create(
                text="{} {} عدد فروخته شد.".format(name, number),
                type="sell",
                date=datetime.now()
            )
            log_response = log.save()
            print("log_response: {}".format(log_response))
            return Response(data={"response": "success"}, status=status.HTTP_200_OK)
        else:
            return Response(status=status.HTTP_404_NOT_FOUND)

    else:
        return Response(data=serializer.errors, status=status.HTTP_406_NOT_ACCEPTABLE)
Exemple #57
0
def make_meme(title, filename, top_string="", bottom_string=""):
    img = Image.open(filename)
    image_size = img.size
    font_size = int(image_size[1] / 5)
    font = ImageFont.truetype("/Library/Fonts/Impact.ttf", font_size)
    top_text_size = font.getsize(top_string)
    bottom_text_size = font.getsize(bottom_string)
    while top_text_size[0] > image_size[0] - 20 or bottom_text_size[
            0] > image_size[0] - 20:
        font_size = font_size - 1
        font = ImageFont.truetype("/Library/Fonts/Impact.ttf", font_size)
        top_text_size = font.getsize(top_string)
        bottom_text_size = font.getsize(bottom_string)

    top_text_position_x = (image_size[0] / 2) - (top_text_size[0] / 2)
    top_text_position_y = 0
    top_text_position = (top_text_position_x, top_text_position_y)

    bottom_text_position_x = (image_size[0] / 2) - (bottom_text_size[0] / 2)
    bottom_text_position_y = image_size[1] - bottom_text_size[1]
    bottom_text_position = (bottom_text_position_x, bottom_text_position_y)

    draw = ImageDraw.Draw(img)

    outline_range = int(font_size / 15)
    for x in range(-outline_range, outline_range + 1):
        for y in range(-outline_range, outline_range + 1):
            draw.text((top_text_position[0] + x, top_text_position[1] + y),
                      top_string, (0, 0, 0),
                      font=font)
            draw.text(
                (bottom_text_position[0] + x, bottom_text_position[1] + y),
                bottom_string, (0, 0, 0),
                font=font)

    draw.text(top_text_position, top_string, (255, 255, 255), font=font)
    draw.text(bottom_text_position, bottom_string, (255, 255, 255), font=font)

    filename_slug = slugify(title + "-" + str(datetime.now()))
    filename_slug = filename_slug + ".png"
    img.filename = filename_slug
    return img
Exemple #58
0
    def post(self, request):
        studentid = request.POST['student-ID']
        val = float(request.POST['val'])
        plac = request.POST.get('place', False)
        studentList = Student.objects.filter(student_id=studentid)
        for row in studentList:
            cardid = row.card_id
        card = Card.objects.get(card_id=cardid)
        card_balance = card.balance
        ctx = {}

        student = Student.objects.get(card_id=cardid)
        consume_today = ConsumeRecord.objects.filter(
            card_id=cardid, time__day=datetime.now().day)
        # 计算今日消费额
        consume_today_sum = 0.0
        for single_consume in consume_today:
            consume_today_sum += single_consume.value
        consume_today_sum += val
        # name = student.name
        # college = student.college
        # balance = card.balance

        if len(studentList) > 0:
            if (card_balance - val) > 0:
                if consume_today_sum < 100:
                    ConsumeRecord.objects.create(value=val,
                                                 location=plac,
                                                 card_id=cardid)
                    card.balance = card_balance - val
                    card.save()
                    ctx['rlt'] = "消费成功"
                    return render(request, 'consump.html', ctx)
                else:
                    ctx['rlt'] = "今日消费额度达到上限"
                    return render(request, 'consump.html', ctx)
            else:
                ctx['rlt'] = "余额不足"
                return render(request, 'consump.html', ctx)
        else:
            ctx['rlt'] = "学号错误"
            return render(request, 'consump.html', ctx)
Exemple #59
0
    def post(self, request, event_id):
        user = request.user
        person = get_person_by_user(user)
        event = get_event_by_id(event_id)
        form = EventForm(instance=event, data=request.POST)
        if form.is_valid():
            event = form.save(commit=False)
            event.person = person
            event.created_at = datetime.now()
            event.save()
            return redirect(reverse('profil-events'))
        else:
            form = EventForm(instance=event)
            context = {
                'person': person,
                'form': form,
                'navigation_items': navigation.navigation_items(navigation.NAV_EVENEMENT),

            }
            return render(request, 'persons/events/my_events_form.html', context)
def send_emails(email_recievers):
    subject = "Daily Article Report"
    from_email = 'Kroon Studio'
    today_data = datetime.now()
    month = today_data.strftime("%B")
    year = today_data.strftime("%Y")

    for user, artcls in email_recievers.items():
        to = user.email
        text_content = 'Text'
        html_content = render_to_string('report_email.html', {
            'user': user,
            'articles': artcls,
            'month': month,
            'year': year
        })

        msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
        msg.attach_alternative(html_content, "text/html")
        msg.send()