Exemple #1
0
def new_note(request):
    if request.method == 'POST' and 'b2' in request.POST :
        form = NewNote(request.POST)
        if form.is_valid():
            new = Note()
            new.owner = request.session['username']
            new.head = form.cleaned_data["heading"]
            new.content = form.cleaned_data["content"]
            con = Markdown()
            new.md = con.convert(new.content)
            new.save()
            return HttpResponseRedirect("./")
    if request.method == 'POST' and 'b1' in request.POST :
        form = NewNote(request.POST)
        if form.is_valid():
            con=Markdown()
            request.session['temp'] = con.convert(form.cleaned_data['content'])

            return HttpResponseRedirect('preview')
    data = [i for i in Note.objects.all() if i.owner == request.session['username']]

    context = dict()
    context['data'] = data
    context['form'] = NewNote()
    context['username'] = request.session['username']
    temp = loader.get_template('notes/newnote.html')
    return HttpResponse(temp.render(context, request))
Exemple #2
0
def finish_plan_api():
    pk = flask.request.form.get('pk')
    user_id = flask.session['user_id']
    plan = Plan.fetchone(pk=pk)
    if not plan:
        raise error.PlanNoteFound()

    plan_log = PlanLog()
    plan_log.user_id = user_id
    plan_log.plan_id = plan.pk
    plan_log.create_at = datetime.now()
    plan_log.update_at = datetime.now()
    plan_log.is_enable = 1
    plan_log.save(commit=False)

    for item in plan.plan_items:
        note = Note()
        note.kind_id = item.kind.pk
        note.user_id = user_id
        note.quantity = item.quantity
        note.plan_log_id = plan_log.pk
        note.create_at = datetime.now()
        note.update_at = datetime.now()
        note.save()

    return {'pk': pk}
Exemple #3
0
def publish_note(request):

    if request.POST['flag'] == 'index':

        id = request.POST['userid']
        pub = Publisher.objects.filter(id=id)[0]
        return render(request, 'edit.html', {'pub': pub})
    else:

        username = request.POST['id']
        title = request.POST['title']
        content = request.POST['content']
        flag = request.POST['flag']
        timer = time.strftime("%Y-%m-%d %X", time.localtime())

        note = Note(title=title,
                    time=timer,
                    content=content,
                    publisher_id=username)
        note.save()
        #待修改
        #增刷新个人主页帖子window.location.reload;
        return HttpResponse(
            '<script type="text/javascript">alert("发布成功");window.history.go(-2);</script>'
        )
Exemple #4
0
def index(request):
    if request.GET:
        new_data = ''
        data = request.GET.get('text')
        if 'shifr' == request.GET.get('command'):
            step = int(request.GET.get('code'))
        else:
            step = -int(request.GET.get('code'))
        capital_letters = [chr(letter) for letter in range(65, 91)]
        capital_letters_step = [capital_letters[(i+step+26) % 26] for i in range(0, 26)]
        low_letters = [chr(letter) for letter in range(97, 123)]
        low_letters_step = [low_letters[(i+step+26) % 26] for i in range(0, 26)]
        for letter in data:
            if letter in capital_letters:
                new_data += capital_letters_step[(ord(letter)-65) % 26]
            elif letter in low_letters:
                new_data += low_letters_step[(ord(letter)-97) % 26]
            else:
                new_data += letter
        note = Note(shifr=request.GET.get('text'), ROT=int(request.GET.get('code')), label=request.GET.get('label'))
        note.save()

        return HttpResponse(JsonResponse({'text': new_data }))
    else:
        form = ShifrForm()
        context = {
            'form': form,
        }
        return render(request, 'content.html', context)
Exemple #5
0
def index():
    if request.method == 'POST' and request.form.get('content'):
        note = Note(content=request.form['content'])
        Note.save(note)
        return redirect(url_for('index'))

    notes = Note.list_public()
    return render_template('index.html', notes=notes)
Exemple #6
0
def handle_uploaded_json_file(f, user):
    
    def convert_date(str_date):
        new_str = str_date.replace('+00:00','')
        try:
            new_dt = datetime.strptime(new_str, '%Y-%m-%d %H:%M:%S.%f')
        except ValueError:
            new_dt = datetime.strptime(new_str, '%Y-%m-%d %H:%M:%S')
        return new_dt
    
    with open('notes.json', 'wb+') as destination:
        for chunk in f.chunks():
            destination.write(chunk)
        f.close()
    with open('notes.json', 'r') as fh:
        json_data = json.load(fh)
        fh.close()
    
    version, notes = json_data
    
    # for user in User.objects.all():
        # if not Folder.)objects.filter(user = user, name = "Main").exists():
            # folder = Folder(name="Main", user = user)
            # folder.save()
        # if not Folder.objects.filter(user = user, name = ")Trash").exists():
            # folder = Folder(name="Trash", user = u)ser)
            # folder.save()  
          
    for note in notes:
        created_at = convert_date(note['created_at'])
        title = note['title']
        username = note['user']

        # TODO: If user is blank we need to assign to a default user.  For now just skip.
        # Its technically a database integrity violation anyway.
        if username is None: continue

        user = User.objects.get(username = username)        

        if not Note.objects.filter(title = title, 
                               created_at = created_at).exists():
            new_note = Note()
            new_note.title =  title
            new_note.created_at = created_at
            new_note.modified_at = convert_date(note['modified_at'])
            new_note.note_type = note['post_type'] 
            new_note.note = note['note']
            foldr = note['folder']
            
            
            try:
                folder = Folder.objects.get(name = foldr, user = user)
            except Folder.DoesNotExist:
                folder = Folder(name = foldr, user = user)
                folder.save()
            new_note.folder = folder
            new_note.user = user
            new_note.save()
Exemple #7
0
def note_add(request, event_id):
    event = get_object_or_404(Event, pk=event_id)
    if request.method == 'POST': # If the form has been submitted...
        form = NoteForm(request.POST) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            note = Note(event=event, user=request.user, note = form.cleaned_data['note'])
            note.save()
            messages.success(request, _("Saved note"))
    return HttpResponseRedirect(reverse('event', args=[event.id]))
Exemple #8
0
def index(request):

    if request.method == 'POST':
        title = request.POST['title']
        text = request.POST['text']
        note = Note(title=title, text=text)
        note.save()
    else:
        return render(request, 'webApp/index.html')
Exemple #9
0
 def save(self, account):
     cd = self.cleaned_data
     note = Note(amount=cd['amount'],
                 timestamp=cd['timestamp'],
                 description=cd['description'],
                 category=cd['category'],
                 account=account)
     note.save()
     account.balance = account.balance + cd['amount']
     account.save()
 def add_note(self, message, user):
     if message:
         note = Note(activity=self.object)
         note.message = message
         note.user = user
         note.save()
         messages.success(self.request, 'Note added successfully.')
         return True
     else:
         messages.error(self.request, 'Message cannot be empty.')
         return False
Exemple #11
0
 def save(self, account):
     cd = self.cleaned_data
     note = Note(
         amount=cd['amount'],
         timestamp=cd['timestamp'],
         description=cd['description'],
         category=cd['category'],
         account=account
     )
     note.save()
     account.balance = account.balance + cd['amount']
     account.save()
Exemple #12
0
def createNote(request):

    username = request.POST['username']
    note = request.POST['note']

    date_time = helpers.get_datetime(note)

    newNote = Note(user=username, text_body=note, time=date_time)# TODO: START and EXPIRATION date objects
    newNote.save()

    # SHOULD REDIRECT TO LOGIN PAGE
    return redirect("index")
 def test_book_autodelete(self):
     note1 = Note(text='text')
     note1.save()
     note2 = Note(text='text')
     note2.save()
     book = Book(title='title')
     book.save()
     book.notes.add(*[note1, note2])
     note1.delete()
     self.assertTrue(Book.objects.all())
     note2.delete()
     self.assertFalse(Book.objects.all())
Exemple #14
0
def write_note(request):
    try:
        note = request.POST.get('note')
        email = request.user.email
        location = request.POST.get('location')
        artboard = ArtBoard.objects.get(location=location)
        new_note = Note(email=email, note=note, artboard=artboard)
        new_note.save()
        redirection = '/exegesis/svg/?url=' + location
        return redirect(redirection)
    except:
        print sys.exc_info()
        return render(request, 'wrong.html')
Exemple #15
0
def add():
    new_user = User(name=request.form['name'],
                    password=request.form['password'])

    new_note = Note(date=datetime.utcnow(),
                    comment="User " + new_user.name + " was added.")
    LogCount.added = LogCount.added + 1
    LogCount.save()

    sqldb.session.add(new_user)
    sqldb.session.commit()
    new_note.save()
    return redirect(url_for('index'))
Exemple #16
0
def delete():
    to_delete_id = request.form['del_id']
    to_delete = User.query.filter_by(id=to_delete_id).first()

    new_note = Note(date=datetime.utcnow(),
                    comment="User " + to_delete.name + " was deleted.")
    LogCount.deleted = LogCount.deleted + 1
    LogCount.save()

    sqldb.session.delete(to_delete)
    sqldb.session.commit()
    new_note.save()
    return redirect(url_for('index'))
Exemple #17
0
def create(request):
    NoteForm = get_note_form(request)
    form = NoteForm()
    if request.method == 'POST':
        form = NoteForm(request.POST)
        if form.is_valid():
            if request.user.is_authenticated():
                author = request.user
            else:
                if 'email' in form.cleaned_data:
                    users_list = User.objects.filter(
                        email=form.cleaned_data['email'])
                    if len(users_list) > 0:
                        author = users_list[0]
                    else:
                        user = User()
                        user.username = form.cleaned_data['email']
                        user.email = form.cleaned_data['email']
                        user.save()
                        author = user
            note = Note(
                text=form.cleaned_data['text'],
                type=form.cleaned_data['type'],
                pub_date=datetime.datetime.now(),
                author=author,
            )
            if 'public' in form.cleaned_data:
                note.public = True
            note.save()
            save_bookmark_to_note(request, note)
            send_note_email(note, 'http://' + request.get_host())
            if request.is_ajax:
                _note = note.as_json()
                _note['url'] = request.get_host() + reverse(detail,
                                                            args=(note.id, ))
                if request.user.is_authenticated() and (
                        note.author == request.user or user.is_staff):
                    _note['editable'] = True
                return HttpResponse(json.dumps(_note), 'application/json')
            return HttpResponseRedirect(reverse(detail, args=(note.id, )))
    if request.is_ajax():
        return HttpResponse(
            json.dumps({
                "form":
                render_to_string("notes/form.html", {
                    "form": form,
                },
                                 context_instance=RequestContext(request))
            }), 'application/json')
    return render_to_response('notes/form_page.html', {'form': form},
                              context_instance=RequestContext(request))
Exemple #18
0
def gen(count, dicts, get_string_function):
    user = User.objects.all()[0]
    date_now = now()
    total = count

    while 0 < count:
        stdout.write("%d\r" % (total - count))
        stdout.flush()
        count -= 1
        note = Note()
        note.user = user
        note.pub_date = date_now
        note.title = get_string_function(dicts, randrange(20, 100))
        note.body = get_string_function(dicts, randrange(500, 1000))
        note.save()
Exemple #19
0
    def test_evaluated_queryset_as_argument(self):
        "#13227 -- If a queryset is already evaluated, it can still be used as a query arg"
        n = Note(note='Test1', misc='misc')
        n.save()
        e = ExtraInfo(info='good', note=n)
        e.save()

        n_list = Note.objects.all()
        # Evaluate the Note queryset, populating the query cache
        list(n_list)
        # Use the note queryset in a query, and evalute
        # that query in a way that involves cloning.
        try:
            self.assertEquals(ExtraInfo.objects.filter(note__in=n_list)[0].info, 'good')
        except:
            self.fail('Query should be clonable')
    def test_evaluated_queryset_as_argument(self):
        "#13227 -- If a queryset is already evaluated, it can still be used as a query arg"
        n = Note(note='Test1', misc='misc')
        n.save()
        e = ExtraInfo(info='good', note=n)
        e.save()

        n_list = Note.objects.all()
        # Evaluate the Note queryset, populating the query cache
        list(n_list)
        # Use the note queryset in a query, and evalute
        # that query in a way that involves cloning.
        try:
            self.assertEquals(
                ExtraInfo.objects.filter(note__in=n_list)[0].info, 'good')
        except:
            self.fail('Query should be clonable')
Exemple #21
0
    def create(user_first_name, user_last_name, movie, note):
        """ Create a new note """
        notation = Note(user_first_name=user_first_name,
                        user_last_name=user_last_name,
                        movie=movie,
                        note=note)

        return notation.save()
Exemple #22
0
def create(request):
    # TODO Receive a `timestamp` parameter and return all the
    #      notes that is modified after `timestamp`. Because
    #      in rare cases uses open the same page multiple times
    #      , and if we just return the note just added we would
    #      miss some notes submitted in other pages.
    if request.method == 'POST':
        form = NewNoteForm(request.POST)
        if form.is_valid():
            note = Note(author=request.user,
                        content=form.cleaned_data['content'])
            note.save()

            data = [note.get_serializable()]
            return HttpResponse(simplejson.dumps(data),
                                mimetype='application/json')
    return HttpResponse('false', mimetype='application/json')
Exemple #23
0
    def create(user, notebook_id, title, content):
        """ Create a new note """

        if len(title) > 32:
            return UnprocessableEntity(description="NOTE_TITLE_MAX_LENGTH")

        current_time = int(time.time())
        note = Note(notebook_id=notebook_id,
                    title=title,
                    content=content,
                    user_id=user.id,
                    created_at=current_time,
                    updated_at=current_time)

        note.save()

        return note.transform()
Exemple #24
0
def _ajax(request):
    """Wrapper"""
    if not request.is_ajax():
        return {'status': 403}
        
    a = request.POST.get('a')
    if a not in ['move', 'edit', 'delete', 'new']:
        return {'status': 403}
    
    if a in ['move', 'edit', 'delete']:
        n = request.POST.get('note')
        id = int(n[5:])
        note = get_object_or_404(Note, pk=id)
        try:
            note = Note.objects.get(pk=id)
        except ObjectDoesNotExist:
            return {'status': 403}

    if a in ['edit', 'new']:
        content = request.POST.get('content')

    if a == 'move':
        st = request.POST.get('section')
        if st not in STATES:
            return {'status': 403}
        note.state = st
    elif a == 'delete':
        note.delete()
        return {'status': 200}
    elif a == 'new':
        p = request.POST.get('project')
        p = get_object_or_404(Project, id=p)
        note = Note(
            content=content,
            author=request.user,
            project=p)
        note.save()
        return {
            'status': 200,
            'content': _note(note)
        }
    else:
        note.content = content
    note.save()
    return {'status': 200}
Exemple #25
0
def create_note_api():
    kind_id = flask.request.form.get('kind_id')
    quantity = flask.request.form.get('quantity')
    content = flask.request.form.get('content')
    user_id = int(flask.session['user_id'])

    # Check kind owner
    note_kind = NoteKind.fetchone(pk=kind_id, user_id=user_id)
    if not note_kind:
        raise error.KindNotExistError()

    note = Note()
    note.kind_id = kind_id
    note.user_id = user_id
    note.content = content
    note.quantity = quantity
    note.save()
    return {'pk': note.pk}
Exemple #26
0
def note_list(request, username=None):
	try:
		author = User.objects.get(username=username)
		notes = Note.objects.filter(author_id=author.id)
		# add a new note
		if request.method == 'POST':
			title = request.POST['title']
			content = request.POST['content']
			content_excerpts = content[:200]
			note_initial = {
				'title': title, 
				'content': content,
			}
			# check title's length
			if len(title) > 128:
				note_form = NoteForm(initial=note_initial)
				context_dict = {'message': u'标题字数过多,请不要超过 128 个字符', 'form': note_form}
				return render(request, 'site/add_note.html', context_dict)
			else:
				# add a note
				note = Note(
					author_id = author.id,
					title = title,
					content = content,
					content_excerpts = content_excerpts,
				)
				note.save()
				return redirect('note_list', username=username)
		
		context_dict = {'notes': notes, 'author': author}
		return render(request, 'site/note_list.html', context_dict)

	except OperationalError:
		note_form = NoteForm(initial=note_initial)
		context_dict = {'message': u'对不起,你所输入的符号(如表情符号)暂不支持', 'form': note_form}
		return render(request, 'site/add_note.html', context_dict)

	except User.DoesNotExist:
		raise Http404("Not exists.")

	except Note.DoesNotExist:
		raise Http404("Not exists.")
Exemple #27
0
def update():
    to_update_id = request.form['upd_id']
    to_update = User.query.filter_by(id=to_update_id).first()
    old_username = to_update.name
    to_update.name = request.form['upd_name']
    to_update.password = request.form['upd_comment']

    if old_username == to_update.name:
        new_note = Note(date=datetime.utcnow(),
                        comment="Users " + old_username +
                        " password was updated")
    else:
        new_note = Note(date=datetime.utcnow(),
                        comment="User " + old_username + " was updated to " +
                        to_update.name)
    LogCount.edited = LogCount.edited + 1
    LogCount.save()

    sqldb.session.commit()
    new_note.save()
    return redirect(url_for('index'))
Exemple #28
0
def notes():
    print(request.method)
    if request.method == 'GET':
        result = [note.export_data() for note in Note.objects.all()]
        return jsonify({"success": True, "results": result})

    if request.method == 'POST':

        print(request.json)

        try:
            note = Note()
            note.import_data(request.json)
            note.save()
        except Exception as ex:
            return jsonify({
                "success": False,
                "message": "cannot save note : " + str(ex)
            })

        return jsonify({"success": True, "results": str(note.id)})
Exemple #29
0
def add_note():
    """Add a note."""
    form = ArticleForm()
    if request.method == 'POST':
        if form.validate_on_submit():
            # Get the right number - the article ID
            number = 1
            notes = Note.all().order('-number')
            if notes.count() > 0:
                number = notes[0].number + 1

            note = Note(
                number=number,
                title=form.title.data,
                content=form.content.data,
                tags=form.tags.data,
            )
            note.save()
            return redirect(note.get_absolute_url())
    action_url = url_for('add_note')
    return render_template('add_note.html', form=form, action_url=action_url)
Exemple #30
0
def new_note(request):
    if request.method == 'GET':
        context = {'suppress_menu':True}
        return render(request, 'cloud_notes/new.html', context)
    elif request.method == 'POST':
        if "cancel" in request.POST:
            return redirect('cloud_notes.views.list')
        else:
            form = NoteForm(request.POST)
            context = {'form':form}
            
            if form.is_valid():
                # do stuff
                # ...
                if 'notes_folder' in request.session:
                    fldr = Folder.objects.get(pk=request.session['notes_folder'], user=request.user)
                else:
                    fldr = Folder.objects.get(name="Main", user=request.user)
                
                # Don't allow user to inadvertently create note in Trash
                if fldr.name == 'Trash':
                    fldr = Folder.objects.get(name="Main", user=request.user)
                
                
                obj = Note()
                obj.title = form.cleaned_data['title']
                obj.note = form.cleaned_data['note']
                obj.post_type = 'note'
                obj.created_at = datetime.utcnow()
                obj.modified_at = datetime.utcnow()
                obj.user = request.user
                obj.folder = fldr
                obj.save()
                
                return redirect('cloud_notes.views.list')
            else:
                print form.errors
                return render(request, 'cloud_notes/new.html', context)
Exemple #31
0
class NoteTest(TestCase):
    def setUp(self):
        self.user = User.objects.create_user('tester',
                                             'tester')
        self.note = Note(author=self.user, content='#test#')
        self.note.save()

    def test_author(self):
        self.assertEqual(self.note.author, self.user)
        self.assertEqual(self.user.notes.get(), self.note)

    def test_get_serializable(self):
        note_dict = self.note.get_serializable()
        self.assertEqual(note_dict['id'], self.note.id)
        self.assertEqual(note_dict['content'], self.note.content.html)
        from django.utils.dateformat import format
        self.assertEqual(note_dict['modified'], 
                         format(self.note.modified, 'n月j日 G:s'))
        self.assertEqual(note_dict['timestamp'],
                         self.note.modified.strftime('%Y-%m-%d %H:%M:%S.%f'))

    def test_update_tags(self):
        orig_tags = self.note.tags.all()
        self.assertTrue(Tag.objects.get(content='test') in orig_tags)
        self.note.content = '#new test# ok #a third one#'
        self.note.save()
        new_tags = self.note.tags.all()
        self.assertFalse(Tag.objects.get(content='test') in new_tags)
        self.assertTrue(Tag.objects.get(content='new test') in new_tags)
        self.assertTrue(Tag.objects.get(content='a third one') in new_tags)

    def test_content_conversion(self):
        list_url = reverse('note.views.list')
        self.note.content = '#Tag:># message #Tag2#'
        self.note.save()
        self.assertEqual(self.note.content.html,
                        '<a href="'+list_url+
                        '?tags=Tag%3A%3E">#Tag:&gt;#</a> message <a href="'+
                        list_url+'?tags=Tag2">#Tag2#</a>')
def profile(slug):
    #variables
    form = NoteForm(request.form)

    notes = Note.objects.all()

    for note in current_user.notes:
        for t in note.tags:
            tagJ = ""
            join = tagJ.join(note.tags)
            print join

    if request.method == 'POST':
        try:
            form = NoteForm(request.form)

            if form.validate() == False:
                flash("Something went wrong.", 'danger')
                return render_template('profile.html',
                                       form=form,
                                       search_form=SearchForm(request.form),
                                       delete_quote=deleteQuoteForm(
                                           request.form))

            if form.validate_on_submit():
                form_urlLink = form.URLLink.data

                if form.URLLink.data != '':
                    if not URl_Regex.match(form_urlLink):
                        flash('Invalid URL adress', 'danger')
                        return render_template(
                            "profile.html",
                            form=form,
                            search_form=SearchForm(request.form),
                            regex="Invalid URL adress",
                            delete_quote=deleteQuoteForm(request.form))

                tags = form.tags.data
                tagList = tags.split(",")

                note = Note(content=form.content.data,
                            tags=tagList,
                            URLLink=form.URLLink.data)
                note.save()

                current_user.notes.append(note)
                current_user.save()

                flash('Quote saved successfully.', 'success')
                return render_template('profile.html',
                                       form=form,
                                       search_form=SearchForm(request.form),
                                       delete_quote=deleteQuoteForm(
                                           request.form))

        except ValidationError:
            flash('UPPPS! Tags or Url was wrong', 'danger')
            return render_template('profile.html',
                                   form=form,
                                   search_form=SearchForm(request.form),
                                   delete_quote=deleteQuoteForm(request.form))

    return render_template("profile.html",
                           title=current_user.name + "'s Quotes",
                           form=form,
                           search_form=SearchForm(request.form),
                           delete_quote=deleteQuoteForm(request.form))
Exemple #33
0
def recover_note(pk):
    note = Note.query.get_or_404(pk)
    note.archived = False
    Note.save(note)
    return redirect(url_for('index'))
Exemple #34
0
def archive_note(pk):
    note = Note.query.get_or_404(pk)
    note.archived = True
    Note.save(note)
    return redirect(url_for('index'))