def create_diary(data):

    validation = required(data, 'token', 'title', 'public', 'text')

    if not validation:
        return {
            "status": False,
            "error": "Token, title, public and text are required!",
        }

    user = Authentication.objects.get_user_from_token(data["token"])
    public = strtobool(data["public"])

    if user:
        diary = Diary(title=sanitize(data["title"]),
                      user=user,
                      is_public=public,
                      text=sanitize(data["text"]))
        diary.save()

        return {"status": True, "result": {"id": diary.id}}
    else:
        return {
            "status": False,
            "error": "Invalid authentication token.",
        }
Ejemplo n.º 2
0
    def test_get_diaries_for_people(self):
        expected_diary_list = [self.diary1, self.diary2, self.empty_diary]
        received_diary_list = Diary.get_diaries_for_people(self.person1)
        self.assertItemsEqual(expected_diary_list, received_diary_list)

        expected_diary_list = [self.diary1, self.diary2]
        received_diary_list = Diary.get_diaries_for_people(self.person1, self.person2)
        self.assertItemsEqual(expected_diary_list, received_diary_list)
Ejemplo n.º 3
0
    def test_get_diaries_for_people(self):
        expected_diary_list = [self.diary1, self.diary2, self.empty_diary]
        received_diary_list = Diary.get_diaries_for_people(self.person1)
        self.assertItemsEqual(expected_diary_list, received_diary_list)

        expected_diary_list = [self.diary1, self.diary2]
        received_diary_list = Diary.get_diaries_for_people(
            self.person1, self.person2)
        self.assertItemsEqual(expected_diary_list, received_diary_list)
Ejemplo n.º 4
0
def create(request):
    new_diary = Diary()
    new_diary.title = request.POST['title']
    new_diary.author = request.POST['author']
    new_diary.image = request.FILES['image']
    new_diary.body = request.POST['body']
    new_diary.todolist = request.POST['todolist']
    new_diary.pub_date = timezone.now()
    new_diary.save()
    return redirect('home')
Ejemplo n.º 5
0
 def test_get_diary_for_exact_people(self):
     self.assertEqual(
         self.diary1,
         Diary.get_diary_for_exact_people(self.person1, self.person2,
                                          self.person3))
     self.assertEqual(
         self.diary2,
         Diary.get_diary_for_exact_people(self.person1, self.person2,
                                          self.person4))
     self.assertEqual(self.empty_diary,
                      Diary.get_diary_for_exact_people(self.person1))
Ejemplo n.º 6
0
 def __to_diary(self, item) -> Diary:
     diary = Diary()
     diary.id = DiaryId(item['id'])
     diary.title = item['title']
     diary.pages = {}
     for lang, page in json.loads(item['pages']).items():
         diary.pages[Lang.value_of(lang)] = Page(
             page['note'],
             Lang.value_of(lang),
             datetime.utcfromtimestamp(page['posted_at']),
         )
     return diary
Ejemplo n.º 7
0
 def add(self,*args,**kwargs):
     now = datetime.now()
     today = now.strftime("%Y-%m-%d")
     if self.request.method == "POST":
         title = self.request.POST.get('title',today)
         content = self.request.POST.get('content')
         if title and content:
             diary = Diary()
             diary.title = title
             diary.content = content
             diary.save()
             return self.redirect('diary:index')
     return self.render('diary/add.html',{'today':today})
Ejemplo n.º 8
0
def DiaryManageAddView(request, username=''):

    user = User.objects.get(username=username)
    form = DiaryForm(request.POST or None)
    if form.is_valid():
        thisTitle = form.cleaned_data['title']
        thisContent = form.cleaned_data['content']
        thisUser = User.objects.get(username=username)

        diary = Diary(user=thisUser, title=thisTitle, content=thisContent)
        diary.save()

        return HttpResponseRedirect(URL_DASHBOARD(user.username))

    return HttpResponseRedirect(URL_DASHBOARD(username))
Ejemplo n.º 9
0
def DiaryManageAddView(request, username=''):

    user = User.objects.get(username=username)
    form = DiaryForm(request.POST or None)
    if form.is_valid():
        thisTitle = form.cleaned_data['title']
        thisContent = form.cleaned_data['content']
        thisUser = User.objects.get(username=username)

        diary = Diary(user=thisUser, title=thisTitle, content=thisContent)
        diary.save()

        return HttpResponseRedirect(URL_DASHBOARD(user.username))

    return HttpResponseRedirect(URL_DASHBOARD(username))
Ejemplo n.º 10
0
def dashboard(request):
    diaryList = Diary.objects.filter(author=request.user).order_by('title')

    if request.method == 'POST':
        form = DiaryCreationForm(request.POST)
        if form.is_valid():
            newDiary = Diary(title=form.cleaned_data['title'], 
                themePreference=form.cleaned_data['color'], author=request.user)
            newDiary.save()
            return redirect('diary', diary_id=newDiary.uuid)
    else:
        form = DiaryCreationForm()

    return render(request, 'user/dashboard.html', 
        {'diary_list': diaryList, 'form': form})
Ejemplo n.º 11
0
 def test_create(self):
     checkin = CheckinDetails.objects.create(creator=self.person4, rating=3, duration=30)
     created_diary = Diary.create(creator=self.person4, participants=[self.person1, self.person2, self.person4], checkins=checkin)
     self.assertIsInstance(created_diary, Diary)
     self.assertEqual(created_diary.creator, self.person4)
     self.assertItemsEqual(created_diary.participants.all(), [self.person1, self.person2, self.person4])
     self.assertItemsEqual(created_diary.checkins.all(), [checkin])
Ejemplo n.º 12
0
def diary(request):
    checkins_by_diary = OrderedDict()
    diary_list = sorted(
        list(Diary.get_diaries_for_people(request.user.person).all()), key=lambda x: x.datetime_created, reverse=True
    )
    for diary in diary_list:
        checkins_by_diary[diary] = sorted(list(diary.checkins.all()), key=lambda x: x.datetime_created, reverse=True)
    return render(request, "diary.html", locals())
Ejemplo n.º 13
0
    def test_diary_max_length(self):
        """
        Test that the max length of the field is equal or not.
        """

        diary = Diary(username='******')
        max_length = diary._meta.get_field('username').max_length
        self.assertEquals(max_length, 30)
Ejemplo n.º 14
0
def create(request):
    # 글을 작성할 경우 POST 방식
    if request.method == "POST":
        new_diary = Diary()
        new_diary.title = request.POST['title']
        new_diary.pub_date = timezone.datetime.now()
        new_diary.mood = request.POST['mood']
        new_diary.weather = request.POST['weather']
        new_diary.body = request.POST['body']
        new_diary.image = request.FILES['image']

        # db에 생성된 diary 객체 저장
        new_diary.save()
        return redirect('home')

    # 단순 create 페이지로 이동할 경우 GET 방식으로 들어감
    else:
        return render(request, 'new.html')
Ejemplo n.º 15
0
def checkin(request):
    this_person = request.user.person
    current_checkin = CheckinDetails(creator=this_person)
    checkin_form = CheckinForm(request.POST or None, instance=current_checkin)

    if request.method == 'POST':
        if checkin_form.is_valid():
            checkin_form.save()

            attached_diary = Diary.get_diary_for_exact_people(*list(current_checkin.participants.all()))
            if attached_diary:
                attached_diary.add_checkins_to_diary(current_checkin)
            else:
                Diary.create(creator=current_checkin.creator, participants=list(current_checkin.participants.all()), checkins=current_checkin)

            this_person_settings = Person.objects.get(id=this_person.id)

            return redirect('/diary/')
    csrf(request)
    return render(request, "checkin.html", locals())
Ejemplo n.º 16
0
 def test_create(self):
     checkin = CheckinDetails.objects.create(creator=self.person4,
                                             rating=3,
                                             duration=30)
     created_diary = Diary.create(
         creator=self.person4,
         participants=[self.person1, self.person2, self.person4],
         checkins=checkin)
     self.assertIsInstance(created_diary, Diary)
     self.assertEqual(created_diary.creator, self.person4)
     self.assertItemsEqual(created_diary.participants.all(),
                           [self.person1, self.person2, self.person4])
     self.assertItemsEqual(created_diary.checkins.all(), [checkin])
Ejemplo n.º 17
0
    def get_context(self, request):
        context = super(DiaryEventsTable, self).get_context(request)
        days = context['days']
        selected_type = context['selected_type']

        header = ['日期']
        rows = []
        table = {
            'header': header,
            'rows': rows,
        }
        max_index = 1
        for day in days:
            diary_query = Diary.objects.filter(date=day)
            if diary_query:
                diary = diary_query[0]
            else:
                diary = Diary(date=day)
            events = get_events_by_date(diary)
            events = [event for event in events if event.is_task]
            if selected_type:
                events = [
                    event for event in events
                    if event.event_type == selected_type
                ]
            if events:
                row = [diary.date]
                for event in events:
                    if event.event_template:
                        name = event.event_template.event
                    else:
                        name = event.event
                    if name not in header:
                        header.append(name)
                    index = header.index(name)
                    if index > max_index:
                        max_index = index
                    while len(row) <= index:
                        row.append('')
                    row[index] = event.is_done
                rows.append(row)
            for row in rows:
                while len(row) <= max_index:
                    row.append('')
        context.update({'table': table})
        return context
Ejemplo n.º 18
0
 def add(self, *args, **kwargs):
     now = datetime.now()
     today = now.strftime("%Y-%m-%d")
     if self.request.method == "POST":
         title = self.request.POST.get('title', today)
         content = self.request.POST.get('content')
         if title and content:
             diary = Diary()
             diary.title = title
             diary.content = content
             diary.save()
             return self.redirect('diary:index')
     return self.render('diary/add.html', {'today': today})
Ejemplo n.º 19
0
    def get_context(self, request, diary_date):
        diary_date = datetime.strptime(diary_date, DATE_FORMAT).date()
        diary_query = Diary.objects.filter(date=diary_date)
        generate_events = request.POST.get('generate_events',
                                           None) == 'generate_events'
        commit = True
        display_events = True
        today = date.today()
        is_today = diary_date == today
        if is_today:
            title = 'Diary, today'
        else:
            title = 'Diary, {}'.format(date.strftime(diary_date, '%Y-%m-%d'))
        diary = None
        if diary_query.exists():
            diary = diary_query[0]
        elif diary_date <= today or generate_events:
            diary = Diary.objects.create(date=diary_date)
        elif diary_date > today:
            diary = Diary(date=diary_date)
            commit = False
        if diary.id:
            diary.view_count += 1
            diary.save()
        hidden_events_count = 0
        tag = request.GET.get('tag', '')
        # 早于7天之前, 不自动创建events
        if diary_date <= today - timedelta(days=7) and not generate_events:
            commit = False
            display_events = False
        if not display_events and not diary.events_generated:
            events = []
            important_events = []
        else:
            events = get_events_by_date(diary, tag=tag, commit=commit)
            important_events = get_important_events_by_date(diary.date)
        tasks = [e for e in events if e.is_task]
        tasks_all_done = is_today and not [
            task for task in tasks if not task.is_done
        ]
        now = datetime.now()
        for event in events:
            event.hidden = False
            if tasks_all_done and getattr(event, 'is_done', False):
                event.hidden = True
            if today == diary_date and event.end_hour:
                if now > datetime(now.year, now.month, now.day,
                                  int(event.end_hour), int(event.end_min
                                                           or 0)):
                    event.hidden = True
            if getattr(event, 'hidden', False):
                hidden_events_count += 1

        events_by_groups = get_events_by_groups(events, is_today)
        if important_events:
            events_by_groups.append({
                'is_important': True,
                'group': '最近重要事项',
                'events': important_events
            })

        exercises_logs = ExerciseLog.objects.filter(date=diary_date)
        done_any_exercise = False
        if diary_date == today and not exercises_logs:
            exercises = Exercise.objects.all()
            for exercise in exercises:
                ex_log, created = ExerciseLog.objects.get_or_create(
                    exercise=exercise, date=diary_date)
            exercises_logs = ExerciseLog.objects.filter(date=diary_date)
        done_any_exercise = exercises_logs.filter(times__gt=0).exists()

        editting = request.GET.get('editting', False)

        warnings = []

        yesterday = today - timedelta(days=1)
        if not DiaryContent.objects.filter(diary__date=yesterday).exists():
            warnings.append('昨天还没记日记!')
        if now.hour > 19 and diary_date == today and not diary.contents.all(
        ).exists():
            warnings.append('今天还没记日记!')

        tip = None
        if request.user.id == 1:
            tip = get_random_tip()

        unread_info_count = Info.objects.filter(is_read=False).count()
        event_form = EventForm(initial={
            'event_date': diary.date,
            'group': 1,
            'is_task': True,
        })

        B_DAY = datetime(2013, 12, 21)
        age = diary_date - B_DAY.date()
        age_in_days = age.days
        age = age_format(age)

        tweets = Tweet.objects.filter(published__gte=diary_date,
                                      published__lt=diary_date +
                                      timedelta(days=1))

        context = {
            'title': title,
            'warnings': warnings,
            'tag': tag,
            'hide_header_footer': True,
            'hidden_events_count': hidden_events_count,
            'diary': diary,
            'weekday': WEEKDAY_DICT[str(diary.date.weekday())],
            'events': events,
            'events_by_groups': events_by_groups,
            'text_form': DiaryTextForm(),
            'image_form': DiaryImageForm(),
            'audio_form': DiaryAudioForm(),
            'event_form': event_form,
            'editting': editting,
            'tasks_all_done': tasks_all_done,
            'exercises_logs': exercises_logs,
            'done_any_exercise': done_any_exercise,
            'tip': tip,
            'is_today': is_today,
            'unread_info_count': unread_info_count,
            'age': age,
            'age_in_days': age_in_days,
            'tweets': tweets,
        }
        context.update(base_diary_context())
        return context
Ejemplo n.º 20
0
 def test_get_diary_for_exact_people(self):
     self.assertEqual(self.diary1, Diary.get_diary_for_exact_people(self.person1, self.person2, self.person3))
     self.assertEqual(self.diary2, Diary.get_diary_for_exact_people(self.person1, self.person2, self.person4))
     self.assertEqual(self.empty_diary, Diary.get_diary_for_exact_people(self.person1))
Ejemplo n.º 21
0
 def test_write(case):
     diary = Diary.create()
     page = diary.write('本日は晴天なり')
     case.assert_(isinstance(page, Page))
Ejemplo n.º 22
0
 def test_create(case):
     diary = Diary.create()
     case.assert_(isinstance(diary, Diary))
Ejemplo n.º 23
0
def diary(request):
    checkins_by_diary = OrderedDict()
    diary_list = sorted(list(Diary.get_diaries_for_people(request.user.person).all()), key=lambda x: x.datetime_created, reverse=True)
    for diary in diary_list:
        checkins_by_diary[diary] = sorted(list(diary.checkins.all()), key=lambda x: x.datetime_created, reverse=True)
    return render(request, "diary.html", locals())
Ejemplo n.º 24
0
def diary(request):
    global request_get_from
    global history

    date = recorded_dates = weekday = ""
    total_days = 0
    editor0 = editor1 = editor2 = editor3 = editor4 = editor5 = ""
    y_count = m_count = w_count = total_count = excepts = 0
    weekday_array = ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"]

    if request.method == "POST":
        if request.POST.get('history') is None:
            date = request.POST['date']
            weekday = request.POST['weekday']
            total_days = str(int(request.POST['total_days']) + 1)
            editor0 = request.POST['eidtor0'].strip()
            editor1 = request.POST['eidtor1'].strip()
            editor2 = request.POST['eidtor2'].strip()
            editor3 = request.POST['eidtor3'].strip()
            editor4 = request.POST['eidtor4'].strip()
            editor5 = request.POST['eidtor5'].strip()
            y_count = str(int(request.POST['y_count']) + 1)
            m_count = str(int(request.POST['m_count']) + 1)
            w_count = str(int(request.POST['w_count']) + 1)
            d = Diary(date=date, weekday=weekday, total_days=total_days, editor0=editor0, editor1=editor1,
                      editor2=editor2, editor3=editor3, editor4=editor4, editor5=editor5, y_count=y_count,
                      m_count=m_count, w_count=w_count)
            d.save()
            request_get_from = 1
        else:
            history = request.POST.get('history')
            request_get_from = 2

    if request.method == "GET":
        recorded_dates = getRecordedDates()
        if request_get_from == 1:
            today = getToday()
            (date, weekday, total_days, editor0, editor1, editor2, editor3, editor4, editor5,
             y_count, m_count, w_count, excepts) = getHistoryDiaryRecord(today)
            weekday = weekday_array[datetime.date.today().weekday()]
            total_count = getTotalCount(date)
            request_get_from = 1
        elif request_get_from == 2:
            (date, weekday, total_days, editor0, editor1, editor2, editor3, editor4, editor5,
             y_count, m_count, w_count, excepts) = getHistoryDiaryRecord(history)
            total_count = getTotalCount(history)
            request_get_from = 2
        else:
            today = getToday()
            (date, weekday, total_days, editor0, editor1, editor2, editor3, editor4, editor5,
             y_count, m_count, w_count, excepts) = getHistoryDiaryRecord(today)
            weekday = weekday_array[datetime.date.today().weekday()]
            if excepts == 1:
                date, total_days, editor0, editor1, editor2, y_count, m_count, w_count, excepts = getLastDirayRecord()
                excepts += 1
                if date != "":
                    dt = str(date)
                    last_day = datetime.date(int(dt[:4]), int(dt[5:7]), int(dt[8:10]))
                    diff_days = (datetime.date.today() - last_day).days
                    if diff_days >= 365:
                        editor0 = editor1 = editor2 = ""
                        y_count = m_count = w_count = 0
                    elif diff_days >= 28:
                        editor1 = editor2 = ""
                        m_count = w_count = 0
                    elif diff_days >= 7:
                        editor2 = ""
                        w_count = 0
            total_count = getTotalCount(today)
            request_get_from = 2
        request_get_from = 0
        context = {'date': history, 'weekday': weekday,
                   'total_days': total_days, 'request_get_from': request_get_from,
                   'y_count': y_count, 'm_count': m_count, 'w_count': w_count,
                   'editor0': editor0, 'editor1': editor1,
                   'editor2': editor2, 'editor3': editor3, 'editor4': editor4,
                   'editor5': editor5, 'total_count': total_count,
                   'excepts': excepts, 'recorded_dates': recorded_dates}
        ic(context)
        return render(request, 'diary.html', context=context)
    return render(request, 'diary.html')
Ejemplo n.º 25
0
def diary_page(request, diary_owner):
    if request.method == 'POST':
        diary_key = Diary.get_key_from_name(diary_owner)
        # get DB
        diary = Diary(parent=diary_key)
        # set author
        diary.author = diary_owner[0:diary_owner.find('@')]
        # set weahter
        diary.weather = "Don't remember"
        weather = request.POST.get('weather')
        if weather:
            diary.weather = weather
        # set content
        diary.content = request.POST.get('content')
        # set date
        diary.date = request.POST.get('diary_date')
        # put to DB
        diary.put()
        
        return HttpResponseRedirect('/')

    # get key
    diary_key = Diary.get_key_from_name(diary_owner)
    # make query for select data ordered dsec
    diary_query = Diary.all().ancestor(diary_key).order('-date')
    # get result set
    diaries = diary_query.fetch(2)
    
    # get user, if exist current user
    if users.get_current_user():
        # create logout url
        url = users.create_logout_url('/')
        url_linktext = 'Logout'
    else:
        # create login url
        return HttpResponseRedirect(users.create_login_url('/'))
        
    # set up values for use in template
    template_values = {
        'diaries': diaries,
        'diary_author': diary_owner[0:diary_owner.find('@')],
        'diary_owner': diary_owner,
        'url': url,
        'url_linktext': url_linktext,
    }
    
    return direct_to_template(request, 'diary/diary_page.html', template_values)
Ejemplo n.º 26
0
def diary(request):
    global request_get_from
    global history

    date = ""
    weekday = ""
    total_days = 0
    editor0 = ""
    editor1 = ""
    editor2 = ""
    editor3 = ""
    editor4 = ""
    editor5 = ""
    editor6 = ""
    editor7 = ""
    editor8 = ""
    y_count = 0
    m_count = 0
    w_count = 0
    total_count = 0
    excepts = 0
    recorded_dates = ""

    weekday_array = ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"]

    if request.method == "POST":
        if request.POST.get('history') == None:
            date = request.POST['date']
            weekday = request.POST['weekday']
            total_days = str(int(request.POST['total_days']) + 1)
            editor0 = request.POST['eidtor0'].strip()
            editor1 = request.POST['eidtor1'].strip()
            editor2 = request.POST['eidtor2'].strip()
            editor3 = request.POST['eidtor3'].strip()
            editor4 = request.POST['eidtor4'].strip()
            editor5 = request.POST['eidtor5'].strip()
            editor6 = request.POST['eidtor6'].strip()
            editor7 = request.POST['eidtor7'].strip()
            editor8 = request.POST['eidtor8'].strip()
            y_count = str(int(request.POST['y_count']) + 1)
            m_count = str(int(request.POST['m_count']) + 1)
            w_count = str(int(request.POST['w_count']) + 1)
            d=Diary(date=date,weekday=weekday,total_days=total_days,editor0=editor0,editor1=editor1,\
             editor2=editor2,editor3=editor3,editor4=editor4,editor5=editor5,editor6=editor6,\
             editor7=editor7,editor8=editor8,y_count=y_count,m_count=m_count,w_count=w_count)
            d.save()
            request_get_from = 1
        else:
            history = request.POST.get('history')
            request_get_from = 2

        #return HttpResponseRedirect('/diary/history/')

    if request.method == "GET":
        recorded_dates = getRecordedDates()
        if request_get_from == 1:
            request_get_from = 0

            today = getToday()
            (date, weekday, total_days, editor0, editor1, editor2, editor3,
             editor4, editor5, editor6, editor7, editor8, y_count, m_count,
             w_count, excepts) = getHistoryDiaryRecord(today)
            weekday = weekday_array[datetime.date.today().weekday()]
            total_count = getTotalCount(date)
            return  render_to_response('diary.html',{'request_get_from':1,'date':date,'weekday':weekday,'total_days':total_days,\
             'y_count':y_count,'m_count':m_count,'w_count':w_count,'editor0':editor0,'editor1':editor1,\
             'editor2':editor2,'editor3':editor3,'editor4':editor4,'editor5':editor5,'editor6':editor6,\
             'editor7':editor7,'editor8':editor8,'total_count':total_count,'recorded_dates':recorded_dates})
        elif request_get_from == 2:
            request_get_from = 0

            (date, weekday, total_days, editor0, editor1, editor2, editor3,
             editor4, editor5, editor6, editor7, editor8, y_count, m_count,
             w_count, excepts) = getHistoryDiaryRecord(history)
            total_count = getTotalCount(history)
            return  render_to_response('diary.html',{'request_get_from':2,'date':history,'weekday':weekday,'total_days':total_days,\
             'y_count':y_count,'m_count':m_count,'w_count':w_count,'editor0':editor0,'editor1':editor1,\
             'editor2':editor2,'editor3':editor3,'editor4':editor4,'editor5':editor5,'editor6':editor6,\
             'editor7':editor7,'editor8':editor8,'total_count':total_count,'excepts':excepts,'recorded_dates':recorded_dates})
        else:
            request_get_from = 0

            today = getToday()
            (date, weekday, total_days, editor0, editor1, editor2, editor3,
             editor4, editor5, editor6, editor7, editor8, y_count, m_count,
             w_count, excepts) = getHistoryDiaryRecord(today)
            weekday = weekday_array[datetime.date.today().weekday()]
            if excepts == 1:
                (date, total_days, editor0, editor1, editor2, y_count, m_count,
                 w_count, excepts) = getLastDirayRecord()
                excepts += 1
                if date != "":
                    dt = date.encode('UTF-8')
                    last_day = datetime.date(int(dt[0:4]), int(dt[7:9]),
                                             int(dt[12:14]))
                    diff_days = (datetime.date.today() - last_day).days
                    if diff_days >= 365:
                        eidtor0 = ""
                        editor1 = ""
                        editor2 = ""
                        y_count = 0
                        m_count = 0
                        w_count = 0
                    elif diff_days >= 28:
                        editor1 = ""
                        editor2 = ""
                        m_count = 0
                        w_count = 0
                    elif diff_days >= 7:
                        editor2 = ""
                        w_count = 0
                    else:
                        pass
            total_count = getTotalCount(today)
            return render_to_response('diary.html',{'request_get_from':0,'date':today,'weekday':weekday,'total_days':total_days,\
             'y_count':y_count,'m_count':m_count,'w_count':w_count,'editor0':editor0,'editor1':editor1,\
             'editor2':editor2,'editor3':editor3,'editor4':editor4,'editor5':editor5,'editor6':editor6,\
             'editor7':editor7,'editor8':editor8,'total_count':total_count,'excepts':excepts,'recorded_dates':recorded_dates})
    return render_to_response('diary.html')
Ejemplo n.º 27
0
def diary(request):
	global request_get_from;
	global history;

	date="";
	weekday="";
	total_days=0;
	editor0="";
	editor1="";
	editor2="";
	editor3="";
	editor4="";
	editor5="";
	editor6="";
	editor7="";
	editor8="";
	y_count=0;
	m_count=0;
	w_count=0;
	total_count=0;
	excepts=0;
	recorded_dates="";


	weekday_array=["星期一", "星期二", "星期三", "星期四", "星期五", "星期六","星期日"]

	if request.method=="POST":
		if request.POST.get('history')==None:
			date=request.POST['date']
			weekday=request.POST['weekday']
			total_days=str(int(request.POST['total_days'])+1)
			editor0=request.POST['eidtor0']
			editor1=request.POST['eidtor1']
			editor2=request.POST['eidtor2']
			editor3=request.POST['eidtor3']
			editor4=request.POST['eidtor4']
			editor5=request.POST['eidtor5']
			editor6=request.POST['eidtor6']
			editor7=request.POST['eidtor7']
			editor8=request.POST['eidtor8']
			y_count=str(int(request.POST['y_count'])+1)
			m_count=str(int(request.POST['m_count'])+1)
			w_count=str(int(request.POST['w_count'])+1)
			d=Diary(date=date,weekday=weekday,total_days=total_days,editor0=editor0,editor1=editor1,\
				editor2=editor2,editor3=editor3,editor4=editor4,editor5=editor5,editor6=editor6,\
				editor7=editor7,editor8=editor8,y_count=y_count,m_count=m_count,w_count=w_count)
			d.save()
			request_get_from=1;
		else:
			history=request.POST.get('history')
			request_get_from=2;

		#return HttpResponseRedirect('/diary/history/')

	if request.method=="GET":
		recorded_dates=getRecordedDates()
		if request_get_from==1:
			request_get_from=0

			today=getToday()
			(date,weekday,total_days,editor0,editor1,editor2,editor3,editor4,editor5,editor6,editor7,editor8,y_count,m_count,w_count,excepts)=getHistoryDiaryRecord(today)
			weekday=weekday_array[datetime.date.today().weekday()]
			total_count=getTotalCount(date)
			return  render_to_response('diary.html',{'request_get_from':1,'date':date,'weekday':weekday,'total_days':total_days,\
				'y_count':y_count,'m_count':m_count,'w_count':w_count,'editor0':editor0,'editor1':editor1,\
				'editor2':editor2,'editor3':editor3,'editor4':editor4,'editor5':editor5,'editor6':editor6,\
				'editor7':editor7,'editor8':editor8,'total_count':total_count,'recorded_dates':recorded_dates})
		elif request_get_from==2:
			request_get_from=0

			(date,weekday,total_days,editor0,editor1,editor2,editor3,editor4,editor5,editor6,editor7,editor8,y_count,m_count,w_count,excepts)=getHistoryDiaryRecord(history)
			total_count=getTotalCount(history)
			return  render_to_response('diary.html',{'request_get_from':2,'date':history,'weekday':weekday,'total_days':total_days,\
				'y_count':y_count,'m_count':m_count,'w_count':w_count,'editor0':editor0,'editor1':editor1,\
				'editor2':editor2,'editor3':editor3,'editor4':editor4,'editor5':editor5,'editor6':editor6,\
				'editor7':editor7,'editor8':editor8,'total_count':total_count,'excepts':excepts,'recorded_dates':recorded_dates})
		else:
			request_get_from=0

			today=getToday()
			(date,weekday,total_days,editor0,editor1,editor2,editor3,editor4,editor5,editor6,editor7,editor8,y_count,m_count,w_count,excepts)=getHistoryDiaryRecord(today)
			weekday=weekday_array[datetime.date.today().weekday()]
			if excepts==1:
				(date,total_days,editor0,editor1,editor2,y_count,m_count,w_count,excepts)=getLastDirayRecord()
				excepts+=1
				if date!="":
					dt=date.encode('UTF-8')
					last_day=datetime.date(int(dt[0:4]),int(dt[7:9]),int(dt[12:14]))
					diff_days=(datetime.date.today()-last_day).days
					if diff_days>365:
						eidtor0=""
						editor1=""
						editor2=""
						y_count=0
						m_count=0
						w_count=0
					elif diff_days>30:
						editor1=""
						editor2=""
						m_count=0
						w_count=0
					elif diff_days>7:
						editor2=""
						w_count=0
					else:
						pass
			total_count=getTotalCount(today)
			return render_to_response('diary.html',{'request_get_from':0,'date':today,'weekday':weekday,'total_days':total_days,\
				'y_count':y_count,'m_count':m_count,'w_count':w_count,'editor0':editor0,'editor1':editor1,\
				'editor2':editor2,'editor3':editor3,'editor4':editor4,'editor5':editor5,'editor6':editor6,\
				'editor7':editor7,'editor8':editor8,'total_count':total_count,'excepts':excepts,'recorded_dates':recorded_dates})
	return  render_to_response('diary.html')
Ejemplo n.º 28
0
    def get_context(self, request):
        event_types = EVENT_TYPES
        selected_type = request.GET.get('event_type', None)

        today = date.today()
        default_start = self.get_default_start()
        default_end = self.get_default_end()
        form = EventsRangeForm(initial={
            'start': default_start,
            'end': default_end
        })
        if request.GET:
            form = EventsRangeForm(request.GET)
            form.is_valid()
            start = form.cleaned_data.get('start', None) or default_start
            default_end = start + timedelta(days=42)
            end = form.cleaned_data.get('end', None) or default_end
        else:
            start = default_start
            end = default_end

        dates_shortcuts = [
            [
                '一周以前',
                today - timedelta(days=7),
            ],
            [
                '一月以前',
                today - timedelta(days=30),
            ],
        ]

        current_day = start
        days = []
        days_and_events = []

        while current_day < end:
            days.append(current_day)
            current_day += timedelta(days=1)
        for day in days:
            diary_query = Diary.objects.filter(date=day)
            if diary_query:
                diary = diary_query[0]
            else:
                diary = Diary(date=day)
            events = get_events_by_date(diary)
            if selected_type:
                events = [
                    event for event in events
                    if event.event_type == selected_type
                ]
            events_by_groups = get_events_by_groups(events, is_today=False)
            if events:
                days_and_events.append({
                    'day':
                    day,
                    'diary':
                    diary,
                    'weekday':
                    WEEKDAY_DICT[str(day.weekday())],
                    'events':
                    events,
                    'events_by_groups':
                    events_by_groups,
                })

        context = {
            'title': '日记 - 事件列表',
            'hide_header_footer': True,
            'days': days,
            'days_and_events': days_and_events,
            'event_types': event_types,
            'selected_type': selected_type,
            'form': form,
            'dates_shortcuts': dates_shortcuts,
        }
        return context