def edit(request, note_id=None): note = Note(user_id=1) if note_id: note = Note.objects.get(pk=note_id) if request.method == 'POST': form = NoteForm(request.POST, request.FILES) if not form.is_valid(): return render(request, 'edit.html', {'form': form, 'note': note}) note.title = form.cleaned_data.get('title') note.save() if request.FILES.get('attachment'): a = Attachment(note=note) a.content = request.FILES['attachment'] a.save() version = Version(note=note, user_id=1) version.content = form.cleaned_data.get('content') version.shared = form.cleaned_data.get('shared') version.save() return redirect(note) form = NoteForm(initial={ 'content': note.content, 'shared': note.shared, 'title': note.title }) return render(request, 'edit.html', {'form': form, 'note': note})
def test_a_user_opens_an_existing_note_for_printing_or_sharing(self): """ An existing note can be open in a tab for printing or sharing via url. Viewing does not require login and the url contains a slug instead of the note id. """ note = Note( title="Pisos termicos", summary= "Los pisos termicos permiten distintos tipos de cultivo segun la temperatura" ) note.save() Paragraph( description="Distintos tipos de cultivos", content= "se clasifican segun la altura sobre el nivel del mar editados", note=note).save() visit(self, reverse("show", kwargs={'slug': note.slug})) body = self.selenium.find_element_by_tag_name('body') self.assertTrue(has_content(body, "Pisos termicos")) self.assertTrue(has_content(body, "Distintos tipos de cultivos")) self.assertTrue( has_content( body, "se clasifican segun la altura sobre el nivel del mar editados" )) self.assertTrue( has_content( body, "Los pisos termicos permiten distintos tipos de cultivo segun la temperatura" ))
def post(self): user = users.get_current_user() jsonNotes = self.request.get("notes") if user and jsonNotes: notes = simplejson.loads(jsonNotes) for note in notes: # TODO: Validate the note pk = None if note.has_key("pk"): pk = note["pk"] if pk is not None: logging.error("Has primary key: %s" % pk) n = Note().get_by_id(int(pk)) else: logging.error("New note") # This is a new note. n = Note() n.user = user n.text = note["text"] n.left = int(note["left"]) n.top = int(note["top"]) n.width = int(note["width"]) n.height = int(note["height"]) n.put()
def save_note(message, note, element, story): if DiscordUser.objects.filter(user_id=message.author.id).exists(): user = DiscordUser.objects.get(user_id=message.author.id) if Story.objects.filter(owner=user, name=story).exists(): story = Story.objects.get(owner=user, name=story) if StoryElement.objects.filter(story=story, name=element).exists(): try: element = StoryElement.objects.get(story=story, name=element) note = Note(element=element, note=note) note.save() except MultipleObjectsReturned: elements = StoryElement.objects.filter( story=story, name=element) type_list = [ element.get_type_display() for element in elements ] raise MultipleObjectsReturned(type_list) else: raise ElementNotFoundError else: raise StoryNotFoundError else: raise UserNotCreatedError return element.name
def test_was_published_recently_with_old_note(self): """ was_published_recently() returns False for notes whose pub_date is older than 1 day. """ time = timezone.now() - datetime.timedelta(days=1, seconds=1) old_note = Note(pub_date=time) self.assertIs(old_note.was_published_recently(), False)
def test_was_published_recently_with_future_note(self): """ was_published_recently() returns False for notes whose pub_date is in the future. """ time = timezone.now() + datetime.timedelta(days=30) future_note = Note(pub_date=time) self.assertIs(future_note.was_published_recently(), False)
def test_was_published_recently_with_recent_note(self): """ was_published_recently() returns True for notes whose pub_date is within the last day. """ time = timezone.now() - datetime.timedelta( hours=23, minutes=59, seconds=59) recent_note = Note(pub_date=time) self.assertIs(recent_note.was_published_recently(), True)
def run(): n = Note(title='example', content='This is a test.') n.save() # def run(): # print("Test")
def create_note(self, user): new_note = Note(date=self.cleaned_data['date'], venue=self.cleaned_data['venue'], note=self.cleaned_data['note'], note_type=self.cleaned_data['note_type'], creator=user, customer=user.userprofile.customer) new_note.save() return new_note
def add_new_note(request): if request.method == 'POST': noteform = NoteForm(request.POST) if noteform.is_valid(): title = request.POST['title'] description = request.POST['description'] note = Note(user=request.user, title=title, description=description) note.save() return redirect('notes:index')
def _post_index(request): content = request.POST.get("content", False) if not content or len(content) == 0: message = {'class': 'error', 'content': 'Please supply a note'} return _get_index(request, message) else: note = Note(content=content, created_by=request.user) note.save() return HttpResponseRedirect('/')
def create_note(self, user): new_note = Note( date=self.cleaned_data['date'], venue=self.cleaned_data['venue'], note=self.cleaned_data['note'], note_type=self.cleaned_data['note_type'], creator=user, customer=user.userprofile.customer ) new_note.save() return new_note
def createNewNote(request): # if request.method == "POST": noteId = getNoteId() location = makeNoteLocation(request.POST['noteBody'], noteId) tags = splitNoteTags(request.POST["noteTags"]) mynote = Note(note_id = noteId, noteName = request.POST["noteName"], noteLocation = location, noteTags = tags, noteColor = request.POST["noteTags"], noteCreated = datetime.now(), noteEdited = datetime.now()) mynote.save() return HttpResponse("You saved a note!") else: return HttpResponse("Nope!")
def restore_all_notes(request): notes = TrashNote.objects.for_user(request.user) if request.method == 'POST': Note.untrash_all(notes) return redirect('trash:trash') # Render context = trash_context(request.user) context['notes'] = notes context['current_note_ids'] = ','.join([str(note.id) for note in notes]) return render(request, 'restore_all_notes.html', context)
def delete_all_notes(request): notes = TrashNote.objects.for_user(request.user) if request.method == 'POST': Note.delete_all(notes) return redirect('trash:trash') # Render context = trash_context(request.user) context['notes'] = notes context['current_note_ids'] = ','.join([str(note.id) for note in notes]) return render(request, 'delete_all_notes.html', context)
def save_data(request): if 'name' in request.GET and request.GET[ 'name'] and 'content' in request.GET and request.GET['content']: name = request.GET['name'] content = request.GET['content'] note = Note(name=name, content=content) note.save() return HttpResponse('Successful') else: return HttpResponse('Failed')
def delete_note(request, note_id): """Delete a note and redirect to the list of notes. Here, we entierly delete the note and it's revisions. DO NOT USE TO JUST REMOVE A REVISION, IT WILL DESTROY ALL INFORMATION RELATED TO THIS NOTE. """ note = Note.get_note(note_id) notes = Note.view("notes/by_root", startkey=note.root, endkey=[note.root, []]) for note in notes: note.delete() return redirect('notes:list')
def notes(request, id): if request.method == 'POST': data = request.data user = User.objects.get(pk=id) note = Note(user=user, title=data["title"], note=data["note"]) note.save() return JsonResponse({"message": "Data saved"}, status=200) else: note = Note.objects.filter(user=id) serialize = NoteDisplaySerializer(note, many=True) return Response(serialize.data)
def add_note(request): if request.method == 'POST': form = NoteForm(request.POST) if form.is_valid(): title = form.cleaned_data['title'] text = form.cleaned_data['text'] Note.create(title=title, text=text).save() return django.http.HttpResponseRedirect("/notes/") else: return render(request, 'notes/form_is_not_valid.html') else: form = NoteForm() return render(request, 'notes/add_note.html', {'form': form})
def add(request): try: content = request.POST['content'] except (KeyError): return render(request, 'notes/new.html', { 'error_message': _("Can't add new note."), }) else: content = content if content else _('Nothing') note = Note(content=content, user=request.user, edit_date=timezone.now()) note.save() return HttpResponseRedirect(reverse('notes:index'))
def test_note_updates_tags(self): """ Tests Tags are automatically updated based on Note content. """ note = Note(title='My first note', content='Noteworthy content for #pyladies') note.save() for i in range(3): if i == 0: note.content = '... but it can be improved. #workshop #python' elif i == 1: note.content = '... but it can be improved some more. #workshop #python' else: pass # test saving twice note.save() self.assertTrue(Tag.objects.get(keyword='workshop')) self.assertTrue(Tag.objects.get(keyword='python')) self.assertEqual(Tag.objects.filter(keyword='pyladies').count(), 0) self.assertEqual(Tag.objects.count(), 2) self.assertEqual(note.tags.count(), 2) self.assertEqual(Note.objects.get().tags.count(), 2)
def put(self, request, format = None): data = request.data print('==== PUT ======') print(data) note = Note() serializer = NoteSerializer(note, many = False, context = { 'request': request}) try: note = Note.objects.get(pk = data['id']) note.views = data['views'] note.save() serializer = NoteSerializer(note, many = False, context = { 'request': request}) return Response(serializer.data) except ObjectDoesNotExist: return Response(serializer.errors, status = status.HTTP_400_BAD_REQUEST)
def test_database_note_id_increte_automatically_without_declaration(self): note1 = Note() note1.save() note2 = Note() note2.save() self.assertEqual(note2.id - note1.id, 1)
def delete_notes(request, note_ids): # Validate notes note_id_array = note_ids.split(',') notes = validate_ownership_notes(request.user, note_id_array) if request.method == 'POST': Note.delete_all(notes) return redirect('trash:trash') # Render context = trash_context(request.user) context['notes'] = notes context['current_note_ids'] = note_ids return render(request, 'permanent_delete_notes.html', context)
def create_daterange_notes(self, user): end_date = self.cleaned_data['end_date'] date = self.cleaned_data['date'] if date == end_date: return self.create_note(user) else: for x in rrule(DAILY, dtstart=date, until=end_date): new_note = Note(date=x, venue=self.cleaned_data['venue'], note=self.cleaned_data['note'], note_type=self.cleaned_data['note_type'], creator=user, customer=user.userprofile.customer) new_note.save() return True
def test_can_get_review_mean_score(self): n = Note() n.save() review1 = Review() review1.note = n review1.score = 5 review1.save() review2 = Review() review2.note = n review2.score = 4 review2.save() self.assertEqual(round(n.mean_score, ndigits=2), 4.5)
def test_can_store_and_get_review(self): n = Note() n.save() review1 = Review() review1.note = n review1.author = "Author 1" review1.score = 5 review1.text = "very good" review1.save() self.assertEqual(n.reviews.all().count(), 1) self.assertIn(review1, n.reviews.all()) self.assertEqual(n.reviews.all()[0], review1) self.assertEqual(n.reviews.all()[0].text, "very good")
def update_note_tags(sender, instance, **kwargs): note_instance = instance # check if note has already been created if instance.pk: # Update tags if note content has changed old_note_instance = Note.objects.get(pk=note_instance.pk) if note_instance.content != old_note_instance.content: new_tags = set(Note.parsed_tags(note_instance.content)) old_tags = set([t.keyword for t in old_note_instance.tags.all()]) # Add tags new to the note tags_to_add = new_tags.difference(old_tags) tag_instances = [] for t in tags_to_add: tag_instance, created = Tag.objects.get_or_create(keyword=t) tag_instances.append(tag_instance) note_instance.tags.add(*tag_instances) # Remove tags no longer present in note tags_to_remove = old_tags.difference(new_tags) tags_to_remove_set = Tag.objects.filter(keyword__in=tags_to_remove) note_instance.tags.remove(*tags_to_remove_set.all()) remove_loose_tags(tag_queryset=tags_to_remove_set)
def test_create(note_session): note = Note(time_scope_id="2020-ww20.4", short_desc="status update") assert note.note_id is None note_session.add(note) note_session.commit() assert note.note_id is not None
def list_notes(request): """List all notes documents present on the couch DB. """ notes = Note.view('notes/heads') or None return render("list_notes.html", { "notes": notes, }, request)
def list_notes(request): """List all notes """ notes = Note.view('notes/all') return render("list_notes.html", { "notes": notes, })
def create_daterange_notes(self, user): end_date = self.cleaned_data['end_date'] date = self.cleaned_data['date'] if date == end_date: return self.create_note(user) else: for x in rrule(DAILY, dtstart=date, until=end_date): new_note = Note( date=x, venue=self.cleaned_data['venue'], note=self.cleaned_data['note'], note_type=self.cleaned_data['note_type'], creator=user, customer=user.userprofile.customer ) new_note.save() return True
def note2pdf_response(request: HttpRequest, note: Note) -> HttpResponse: # Source: https://stackoverflow.com/a/48697734 template = 'note2pdf.html' note.rendered_content = render_markdown(note.content) context = {'note': note} response = render_to_pdf_response(request, template, context) response['Content-Disposition'] = 'attachment; filename="note-%s.pdf"' % str(note.id) return response
def gen_random_notes(note_count): """Puts a set of random notes of given length into the db.""" user_count = User.objects.all().count() Note.objects.bulk_create([ Note(title=randomdata.random_title(), content=randomdata.random_text(), owner_id=random.randrange(1, user_count + 1)) for _ in xrange(note_count) ])
def show_tag(request, tag_name): """Display a list of notes related to a special tag. """ notes = Note.view("notes/by_tag", startkey=tag_name, endkey=tag_name) return render("list_notes.html", { "tag_name": tag_name, "notes": notes, }, request)
def import_notes(): notes = load_json("notes.json") notebooks = Notebook.objects.all() notebooksl = len(notebooks) - 1 tags = Tag.objects.all() tagsl = len(tags) - 1 for note in notes: new_note = Note() new_note.title = note['title'] new_note.text = note['text'] new_note.user = USER new_note.notebook = notebooks[randint(0, notebooksl)] amt_of_tags = randint(0, tagsl) new_note.save() for i in range(0, amt_of_tags): new_note.tags.add(tags[randint(0, tagsl)]) new_note.save() print("Imported Notes.")
def test_create_note(): db_init() tags = ['todo', 'reminder'] note = Note.create('note to self', tags=tags) tags_in_db = Tag.index() for tag in tags: assert tag in tags_in_db assert note in Tag.query.get(tag).notes assert note.tags == tags
def update_created_note_tags(sender, instance, created=False, **kwargs): note_instance = instance if created: tag_instances = [] # If Note is created, create associated Tags for t in Note.parsed_tags(note_instance.content): tag_instance, created = Tag.objects.get_or_create(keyword=t) tag_instances.append(tag_instance) note_instance.tags.add(*tag_instances)
def note2pdf_response(request: HttpRequest, note: Note) -> HttpResponse: # Source: https://stackoverflow.com/a/48697734 template = 'note2pdf.html' note.rendered_content = render_markdown(note.content) context = {'note': note} response = render_to_pdf_response(request, template, context) response[ 'Content-Disposition'] = 'attachment; filename="note-%s.pdf"' % str( note.id) return response
def save_note_by_type(message, note, element, type, story): if DiscordUser.objects.filter(user_id=message.author.id).exists(): user = DiscordUser.objects.get(user_id=message.author.id) if Story.objects.filter(owner=user, name=story).exists(): story = Story.objects.get(owner=user, name=story) if StoryElement.objects.filter(story=story, name=element, type=type).exists(): element = StoryElement.objects.get(story=story, name=element, type=type) note = Note(element=element, note=note) note.save() else: raise ElementNotFoundError else: raise StoryNotFoundError else: raise UserNotCreatedError return element.name
def test_post_one_note(self): # Arrange user = User.objects.create_user(username='******', email='*****@*****.**', password='******') note = Note(phrase="Hola", context="Hola amiga!", definition="Hi", language="ES", owner=user) # Act self.note_request_helper(mock_user=user) # Assert try: with transaction.atomic(): note.save() self.assertEqual(1, len(Note.objects.all())) self.assertEqual(note, Note.objects.all()[0]) finally: pass def test_remove_missing_user(): with self.assertRaises(ObjectDoesNotExist): User.objects.get(pk=1).delete() def test_remove_user(): # Arrange user = User.objects.create_user(username='******', email='*****@*****.**', password='******') result_qs = self.request_helper(mock_user=user) self.assertEqual(1, len(result_qs)) # Act User.objects.get(pk=1).delete() # Assert self.assertEqual(0, len(result_qs))
def test_api_can_add_review(self): sample_note = Note() sample_note.name = 'testing note' sample_note.save() note_id = sample_note.id response = self.client.post("/api/addreview/", data={ 'note_id': str(note_id), 'author': 'bobby', 'text': 'very good', 'score': '5' }, follow=True) self.assertEqual(response.json()["status"], "success") review = Review.objects.filter(author='bobby')[0] self.assertEqual(review.note, sample_note) self.assertEqual(review.author, 'bobby') self.assertEqual(review.text, 'very good') self.assertEqual(review.score, 5)
def edit(request, id=None): if request.method == 'GET': n = {} if id: n = Note.objects.get(pk=id) return render(request, 'notes/edit.html', { "note" : n }) elif request.method == 'POST': print('POST') print(request.POST) pk = request.POST['pk'] text = request.POST['text'] if pk: n = Note.objects.get(pk=pk) #TODO: error handling else: n = Note(text=text) n.text = text n.save() return HttpResponseRedirect('/')
def test_database_can_save_and_get_one_Note_multiple_images(self): n = Note() n.name = "test note" n.desc = "this is note for ..." n.save() n_id = n.id img1 = Image() img1.index = 1 img1.note = n img1.image = SimpleUploadedFile( name='1.jpg', content=open( "C:/Users/B/OneDrive/Documents/61FC8C1A-D1FE-4D09-ABE4-BE1689D03C8E.jpg", 'rb').read(), content_type='image/jpeg') img1.save() img2 = Image() img2.index = 2 img2.note = n img2.image = SimpleUploadedFile( name='1.jpg', content=open( "C:/Users/B/OneDrive/Documents/61FC8C1A-D1FE-4D09-ABE4-BE1689D03C8E.jpg", 'rb').read(), content_type='image/jpeg') img2.save() n = Note.objects.get(pk=n_id) images = Image.objects.filter(note=n) self.assertEqual(images.count(), 2)
def list_tags(request): """List all tags, with a ponderation, into a tag cloud """ tags = Note.view("notes/tags", group=True) factor = float(max([int(t['value']) for t in tags])) / 10 tags = [{ 'key': t['key'], 'value': int(round(float(t['value'])/factor)) } for t in tags] return render("list_tags.html", { 'tags': tags, }, request)
def test_saving_and_retrieving_notes(self): first_note = Note() first_note.contents = 'This could be my first note.' first_note.save() second_note = Note() second_note.contents = 'This could be the note written after the first note.' second_note.save() saved_notes = Note.objects.all() self.assertEqual(saved_notes.count(), 2) first_saved_note = saved_notes[0] second_saved_note = saved_notes[1] self.assertEqual(first_saved_note.contents, 'This could be my first note.') self.assertEqual(second_saved_note.contents, 'This could be the note written after the first note.')
def post(self, request, format = None): data = request.data note = Note() if data['title'] and data['content']: note.title = data['title'] note.content = data['content'] note.pub_date = timezone.now() + timezone.timedelta(hours=3) note.login = request.user note.save() serializer = NoteSerializer(note, many = False, context = { 'request': request}) return Response(serializer.data)
def index(request): """Lists all of the Notes in the Database""" list_of_notes = Note.objects.all().order_by('-last_update_date') print list_of_notes if len(list_of_notes) == 0: template = 'notes/create.html' note = Note(title='', content='') note.save() form = NotesForm() list_of_notes = Note.objects.all().order_by('-last_update_date') noteid = list_of_notes[0].id context = {'list_of_notes': list_of_notes, 'form':form, 'noteid': noteid} return render(request, template, context) else: target = list_of_notes[0] noteid = list_of_notes[0].id template = 'notes/base.html' if target.title == '': target.title = 'Write title here' if target.content == '': target.content = 'Write content here' form = NotesForm(initial={'title': target.title, 'content': target.content}) context = {'list_of_notes': list_of_notes, 'target': target, 'form':form, 'noteid': noteid} return render(request, template, context)
def test_loose_tags_removed_when_note_deleted(self): """ Tests 'loose' tags (i.e. Tags associated with no notes) are removed when Note is deleted. """ note = Note(title='My first note', content='Noteworthy content for #pyladies') note.save() note = Note(title='My second note', content='Noteworthy content for #workshop') note.save() Note.objects.all().delete() self.assertEqual(Tag.objects.count(), 0)
def create(request): list_of_notes = Note.objects.all().order_by('-last_update_date') template = 'notes/create.html' if len(list_of_notes) == 0: note = Note(title='', content='') note.save() elif not list_of_notes[0].title == '': note = Note(title='', content='') note.save() form = NotesForm() list_of_notes = Note.objects.all().order_by('-last_update_date') noteid = list_of_notes[0].id context = {'list_of_notes': list_of_notes, 'form':form, 'noteid': noteid} return render(request, template, context)
def create(request, course_key): ''' Receives an annotation object to create and returns a 303 with the read location. ''' note = Note(course_id=course_key, user=request.user) try: note.clean(request.body) except ValidationError as e: log.debug(e) return ApiResponse(http_response=HttpResponse('', status=400), data=None) note.save() response = HttpResponse('', status=303) response['Location'] = note.get_absolute_url() return ApiResponse(http_response=response, data=None)
def get(self): user = users.get_current_user() jsonResult = [] if user: # Retreiving notes query = Note.all() query.filter("user = "******"pk": note.key().id(), "text": note.text, "left": note.left, "top": note.top, "width": note.width, "height": note.height, } jsonResult.append(jsonNote) jsonResponseString = simplejson.dumps(jsonResult, separators=(",", ":")) self.response.out.write(jsonResponseString)
def add_note(request): if not request.user.is_authenticated(): return HttpResponseForbidden( '<a href="{0}" target="_blank">Login</a> required'.format(reverse("social:begin", args=("google",))) ) if request.method == "POST": form = Note.AddForm(request.POST) if form.is_valid(): n = Note() n.author = form.cleaned_data["author"] n.title = form.cleaned_data["title"] n.last_edit = datetime.datetime.now() n.save() # TODO(kazeevn) redo it in a better style return HttpResponse(u"<li><a href=/notes/{0}>{1}</a></li>".format(n.id, n.title)) else: return HttpResponseForbidden(form.errors.__unicode__()) else: return HttpResponseForbidden("POST, please!")
def test_note_creates_tags(self): """ Tests Tags are automatically created based on Note content. """ # check that tags are associated with saved object in database note = Note(title='My first note', content='Noteworthy content for #pyladies') note.save() self.assertEqual(Tag.objects.count(), 1) self.assertTrue(Tag.objects.get(keyword='pyladies')) self.assertEqual(Note.objects.get(pk=note.pk).tags.count(), 1) self.assertEqual(Tag.objects.get(keyword='pyladies').notes.count(), 1) # check tags are not duplicated and are grouped note = Note(title='My second note', content='Noteworthy content for #pyladies with the same hashtag.') note.save() self.assertEqual(Tag.objects.count(), 1) self.assertTrue(Tag.objects.get(keyword='pyladies')) self.assertEqual(Note.objects.get(pk=note.pk).tags.count(), 1) self.assertEqual(Tag.objects.get(keyword='pyladies').notes.count(), 2)
def add(request): note = Note.create(request.POST['description'], datetime.now()) note.save() return HttpResponseRedirect(reverse('notes:index'))
def remove(request, note_id): note = get_object_or_404(Note, pk=note_id) Note.delete(note) return HttpResponseRedirect(reverse('notes:index'))