Ejemplo n.º 1
0
Archivo: views.py Proyecto: filipp/opus
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})
Ejemplo n.º 2
0
    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)
Ejemplo n.º 3
0
    def setUp(self):
        welcomeNote = Note()
        welcomeNote.name = "Welcome to Note Space!"
        welcomeNote.desc = "Introduction and Quick guide"
        welcomeNote.owner = "Note Space Team"
        welcomeNote.save()

        econNote = Note()
        econNote.name = "Basic Economics"
        econNote.subject = "Economics"
        econNote.desc = "This note is about demands, suplies and how market works."
        econNote.owner = "Susan"
        econNote.save()

        img1 = Image()
        img1.index = 1
        img1.note = econNote
        img1.image = SimpleUploadedFile(
            name='IMG_0809.JPG',
            content=open(
                "C:/Users/B/Desktop/NoteSpace/static/TestNotes/Econ/IMG_0809.JPG",
                'rb').read(),
            content_type='image/jpeg')
        img1.save()

        img2 = Image()
        img2.index = 2
        img2.note = econNote
        img2.image = SimpleUploadedFile(
            name='IMG_0810.JPG',
            content=open(
                "C:/Users/B/Desktop/NoteSpace/static/TestNotes/Econ/IMG_0810.JPG",
                'rb').read(),
            content_type='image/jpeg')
        img2.save()

        img3 = Image()
        img3.index = 3
        img3.note = econNote
        img3.image = SimpleUploadedFile(
            name='IMG_0811.JPG',
            content=open(
                "C:/Users/B/Desktop/NoteSpace/static/TestNotes/Econ/IMG_0811.JPG",
                'rb').read(),
            content_type='image/jpeg')
        img3.save()

        img4 = Image()
        img4.index = 4
        img4.note = econNote
        img4.image = SimpleUploadedFile(
            name='IMG_0812.JPG',
            content=open(
                "C:/Users/B/Desktop/NoteSpace/static/TestNotes/Econ/IMG_0812.JPG",
                'rb').read(),
            content_type='image/jpeg')
        img4.save()

        User.objects.create_user("smith", "*****@*****.**", "1234")
        self.browser = webdriver.Firefox()
    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"
            ))
Ejemplo n.º 5
0
def notes(request):
    if request.method == 'GET':
        notes = Note.objects.all()

        for i in range(len(notes)):
            if notes[i].title is None or len(notes[i].title) == 0:
                notes[i].title = notes[i].content[:MAX_SYMBOLS]

        title = request.query_params.get('string', None)
        if title is not None:
            notes_title = [
                notes.filter(title__icontains=title),
                notes.filter(content__icontains=title)
            ]
            res = []
            for i in notes_title:
                for j in i:
                    if j not in res:
                        res.append(j)
            notes = res

        note_serializer = NoteSerializer(notes, many=True)
        return JsonResponse(note_serializer.data, safe=False)
    elif request.method == 'POST':
        content = request.data.get('content')
        note = Note()
        note.content = content
        note.title = request.data.get('title')
        note.save()
        note_serializer = NoteSerializer(note)
        return JsonResponse(note_serializer,
                            safe=False,
                            status=status.HTTP_201_CREATED)
Ejemplo n.º 6
0
 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
Ejemplo n.º 7
0
    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 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)
Ejemplo n.º 9
0
 def post(self, request, *args, **kwargs):
     content = request.data.get('content')
     note = Note()
     note.content = content
     note.title = request.data.get('title')
     note.save()
     return Response(note)
Ejemplo n.º 10
0
    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)
Ejemplo n.º 11
0
    def test_database_canbe_query(self):
        note1 = Note()
        note1.id = 5
        note1.name = "for testing"
        note1.save()

        n = Note.objects.filter(id=5)[0]
        self.assertEqual(n.name, "for testing")
Ejemplo n.º 12
0
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')
Ejemplo n.º 13
0
def run():

    n = Note(title='example', content='This is a test.')

    n.save()


# def run():
#   print("Test")
Ejemplo n.º 14
0
 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
Ejemplo n.º 15
0
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('/')
Ejemplo n.º 16
0
 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
Ejemplo n.º 17
0
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!")
Ejemplo n.º 18
0
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')
Ejemplo n.º 19
0
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)
Ejemplo n.º 20
0
def new_note(request):
    if request.method == 'POST':
        if request.POST.get('title') and request.POST.get('body'):
            note = Note()
            note.user = request.user
            note.title = request.POST.get('title')
            note.body = request.POST.get('body')
            note.save()
            return HttpResponseRedirect(reverse(note_list))
        else:
            return render(request, 'notes.html')
    else:
        return render(request, 'notes.html')
Ejemplo n.º 21
0
	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)
Ejemplo n.º 22
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)
Ejemplo n.º 23
0
    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)
Ejemplo n.º 24
0
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'))
Ejemplo n.º 25
0
	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_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)
Ejemplo n.º 28
0
    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)
Ejemplo n.º 29
0
 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
Ejemplo n.º 30
0
    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")
Ejemplo n.º 31
0
    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.')
Ejemplo n.º 32
0
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)
Ejemplo n.º 33
0
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)
Ejemplo n.º 34
0
 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 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.")
Ejemplo n.º 36
0
    def test_database_can_search_by_similar(self):
        from django.db.models import Q

        note1_namesearch = Note()
        note1_namesearch.name = "django"
        note1_namesearch.save()

        note2_descsearch = Note()
        note2_descsearch.name = "writing unit test"
        note2_descsearch.desc = "for django"
        note2_descsearch.save()

        Tag_django = Tag()
        Tag_django.title = "django"
        Tag_django.save()

        note3_tagsearch = Note()
        note3_tagsearch.name = "Html Template Tags"
        note3_tagsearch.save()
        note3_tagsearch.tags.add(Tag_django)
        note3_tagsearch.save()

        note4_ownersearch = Note()
        note4_ownersearch.name = "FAQ"
        note4_ownersearch.owner = "Django official"
        note4_ownersearch.save()

        search_result = list(
            Note.objects.filter(
                Q(name__icontains="django") | Q(desc__icontains="django")
                | Q(tags__title__icontains="django")
                | Q(owner__icontains="django")))
        print(search_result)

        self.assertGreaterEqual(len(search_result), 4)

        self.assertIn(note1_namesearch, search_result)
        self.assertIn(note2_descsearch, search_result)
        self.assertIn(note3_tagsearch, search_result)
        self.assertIn(note4_ownersearch, search_result)

        search_result = Note.objects.filter(
            name__trigram_similar="django").filter(
                desc__trigram_similar="django")
Ejemplo n.º 37
0
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!")
Ejemplo n.º 38
0
 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
Ejemplo n.º 39
0
    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))
Ejemplo n.º 40
0
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('/')
Ejemplo n.º 41
0
    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)
Ejemplo n.º 42
0
def edit_note(request, note_id=None):
    context = {}

    note = None
    if note_id is not None:
        note = get_object_or_404(Note, id=note_id)
        context["title"] = "{} · Editing".format(note.title)

        if note.owner != request.user:
            return get_profile(request)
    else:
        context["title"] = "New note"
        context["active"] = "edit"

    context["note"] = note or {}

    if request.method == "POST":
        try:
            title = request.POST["title"]
            description = request.POST["description"]

            if note_id == 4:
                raise KeyError()
            elif note is None:
                note = Note(title=title,
                            description=description,
                            owner=request.user)
                note.save()

                return get_profile(request)
            else:
                note.title = title
                note.description = description
                note.save()

                return redirect("/note/{}/".format(note_id))
        except KeyError:
            context["error"] = "Fill in all the fields"

    return render(request, "edit_note.html", context)
Ejemplo n.º 43
0
    def setUp(self):
        user = self.create_new_user(self.username, EMAIL, self.password)
        sub_user = self.create_new_user('sub_user', EMAIL, self.password)

        client = APIClient()
        client.login(username=user.username, password=self.password)

        sub_client = APIClient()
        sub_client.login(username=sub_user.username, password=self.password)

        notes_name = ['note1', 'note2', 'note3']
        notes = []
        for note_name in notes_name:
            note = Note(user=user, title=note_name)
            note.save()
            notes.append(note)

        self.user = user
        self.sub_user = sub_user
        self.rest_client = client
        self.sub_client = sub_client
        self.notes = notes
    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 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)
Ejemplo n.º 46
0
def newNote(request):
    if 'username' not in request.session:
        return redirect("myLogin")
    if request.method == "POST":
        #obtain title and content
        title = request.POST.get("title")
        content = request.POST.get("content")
        user_made = request.session['username']
        random_id = ''.join(
            random.choices(string.ascii_uppercase + string.ascii_lowercase +
                           string.digits,
                           k=6))
        note = Note(title=title,
                    content=content,
                    note_id=random_id,
                    user_created=user_made)
        note.save()
        messages.add_message(request, messages.INFO, "New note added.")
        return redirect("myHome")

    return render(request, "newnote.html", {
        'username': request.session['username'],
        'form': NoteForm()
    })
Ejemplo n.º 47
0
Archivo: dummy.py Proyecto: itao/wnw
def init():
    print 'Existing database will be wiped, continue? (y/n)'
    choice = raw_input().strip()
    if choice == 'y':

        print 'Working...'

        # Wipe db
        clean()

        # Common variable
        pw = 'sesame'
        # FYI
        ACCOUNT_TYPES = {
            1: 'teacher',
            2: 'student',
            3: 'parent',
        }

        # Create teachers
        t = Teacher(first_name='Sesame', last_name='Teacher', email='*****@*****.**', user_type=1)
        t.save()
        t.set_password(pw)
        t.save()

        # Create classes
        for i in range(3):
            index = str(i+1)
            name = 'Class #' + index
            code = 'KLS' + index
            start = end = datetime.now().date()
            colour = "#" + index*6

            k = Klass(teacher=t, name=name, code=code, start=start, end=end, colour=colour)
            k.save()

        # Create students
        students = [
            {
                'first_name': 'Alton',
                'last_name': 'Lau',
                'email': '*****@*****.**'
            }, {
                'first_name': 'Marc',
                'last_name': 'Lo',
                'email': '*****@*****.**'
            }, {
                'first_name': 'Madigan',
                'last_name': 'Kim',
                'email': '*****@*****.**'
            }
        ]
        classes = Klass.objects.all()
        for i in range(3):
            s = students[i]
            s = Student(first_name=s['first_name'], last_name=s['last_name'], email=s['email'], user_type=2)
            s.save()
            s.set_password(pw)
            s.save()
            s.klasses = classes[:i+1]


        k = Klass.objects.all()[0]
        s = Student.objects.all()
        # Create notes
        for i in range(3):
            index = str(i+1)
            detail = 'This is note #' + index
            n = Note(klass=k, detail=detail)
            n.save()
            n.students = s[:i+1]
        print 'All done, goodbye!'
    else:
        print 'Fine, I see how it is.'