コード例 #1
0
    def test_delete_house_with_note(self):
        user1 = User.objects.all()[0]
        house1 = House.objects.all()[0]
        note = Note(text="Test", user=user1, timestamp=time.time(), house=house1)
        note.save()
        self.assertTrue(len(Note.objects.all()) == 1)
        house1.delete()

        self.assertTrue(len(Note.objects.all()) == 1)
        self.assertTrue(Note.objects.all()[0].text == "Test")
コード例 #2
0
    def test_delete_house_with_note(self):
        user1 = User.objects.all()[0]
        house1 = House.objects.all()[0]
        note = Note(text="Test",
                    user=user1,
                    timestamp=time.time(),
                    house=house1)
        note.save()
        self.assertTrue(len(Note.objects.all()) == 1)
        house1.delete()

        self.assertTrue(len(Note.objects.all()) == 1)
        self.assertTrue(Note.objects.all()[0].text == "Test")
コード例 #3
0
ファイル: views.py プロジェクト: riefrn/moneydiary
def addnote(request):
    if request.method == 'POST':
        title = request.POST['title']

        created_date = timezone.now()
        updated_date = timezone.now()

        add_note = Note(title=title,
                        created_date=created_date, updated_date=updated_date)

        add_note.save()
        return redirect('backoffice-list-note')
    else:
        return render(request, 'backoffice/add-note.html', {})
コード例 #4
0
ファイル: routes.py プロジェクト: maxtwardowski/noter
def getnotes():
    if request.method == 'GET':
        notes = User.query.filter_by(
            email=request.headers.get('user')).first().notes
        notes_list = []
        for note in notes:
            notes_list.append({
                'id': note.id,
                'title': note.title,
                'content': note.content,
                'date_create': note.date_create,
                'date_edit': note.date_edit
            })
        return jsonify(notes_list)
    elif request.method == 'POST':
        newnote = Note(title=request.json.get('title'),
                       content=request.json.get('content'),
                       user_id=User.query.filter_by(
                           email=request.json.get('user')).first().get_id())
        db.session.add(newnote)
        db.session.commit()
        return jsonify({'message': 'success'})
    elif request.method == 'PATCH':
        note = Note.query.get(request.json.get('id'))
        setattr(note, 'title', request.json.get('title'))
        setattr(note, 'content', request.json.get('content'))
        setattr(note, 'date_edit', datetime.datetime.utcnow())
        db.session.commit()
        return jsonify({'message': 'success'})
    elif request.method == 'DELETE':
        note = Note.query.get(request.json.get('id'))
        db.session.delete(note)
        db.session.commit()
        return jsonify({'message': 'success'})
コード例 #5
0
 def make_object(self, data, **kwargs):
     """create a new Note from validated data"""
     if not data:
         return None
     return Note(
         title=data['title'],
         content=data['content'],
     )
コード例 #6
0
ファイル: notes.py プロジェクト: Bakaji/MyNotebook
class NoteDeleteAPIView(APIView):
    @staticmethod
    def delete(request: Request, collection_id, note_id):
        bad_response, collection = _check_request(request, collection_id)
        if bad_response:
            return bad_response
        if not (note := find_note(note_id)):
            return BadRequestResponse(['note not found'])
        if note.collection.collection_id != collection.collection_id:
            return BadRequestResponse(['note not in the collection'])
        Note.delete(note)
        return DeleteResponse('note', note_id)
コード例 #7
0
def add_notes(request):
    """
        text: required
    """
    data = json.loads(request.body.read().decode('utf-8'))

    if 'text' not in data or data['text'] == '' or not data['text']:
        return HTTPResponse({'text': 'required'}, status=400)

    if len(data['text']) > 1024:
        return HTTPResponse(
            {'text': 'string can not be greater than 1024 characters'},
            status=400)

    text = data['text']
    user_id = request.user.id

    note = Note(user=user_id, text=text)
    note.save()
    schema = NoteSchema()
    result = schema.dump(model_to_dict(note))  # Serializamos el objeto creado

    return HTTPResponse(result.data, status=201)
コード例 #8
0
ファイル: views.py プロジェクト: riefrn/moneydiary
def editnote(request, note_id):
    if request.method == 'POST':
        title = request.POST['title']

        updated_date = timezone.now()

        update_note = Note.objects.get(
            id=note_id)

        update_note.title = title

        update_note.updated_date = updated_date
        update_note.save()

        return redirect('backoffice-list-note')
    else:
        list_note = Note.get_detail_note(
            note_id)
        # print(list_note)
        return render(request, 'backoffice/edit-note.html', {'list_note': list_note, 'note_id': note_id, })
コード例 #9
0
def userpost(request):

    try:
        title, body, key = (str(request.POST['note_title']),
                            str(request.POST['note_body']),
                            str(request.POST['note_key']))
        if key:
            key = int(key)
            if key > 0:
                note = Note.objects.get(pk=key)
                note.title = title
                note.body = body
                note.save()
            else:  # Delete
                note = Note.objects.get(pk=abs(key))
                note.delete()

        else:
            Note(title=title, body=body, user=request.user).save()
        return True
    except Exception:
        return False
コード例 #10
0
def list_notes(request):
    notes = Note.select().where(Note.user == request.user.id)
    schema = NoteSchema(many=True)

    result = schema.dump(list(notes))
    return HTTPResponse({'results': result.data}, status=200)
コード例 #11
0
 def post(self, request, format=None):
     # trebuie sa verific ca e allow
     numeJurat = request.user
     nota = Note(jurat=numeJurat)
     serializer = NoteSerializer(nota, data=request.data)
     if serializer.is_valid():
         contestId = serializer.validated_data.get('contest_id')
         # verific daca apartine concursului si poate vota
         try:
             contest = Contest.objects.get(pk=contestId,
                                           juror__username=numeJurat)
         except Contest.DoesNotExist:
             return Response(status=401)
         pId = serializer.validated_data.get('participant_id')
         #verific daca participantul apartine concursului
         try:
             participant = Participant.objects.get(contests__id=contestId,
                                                   pk=pId)
         except Participant.DoesNotExist:
             return Response(status=404)
         print(participant.round)
         #verific daca parola a fost corecta
         jurat = Juror.objects.get(username=numeJurat)
         if jurat.allow == 0:
             return Response(status=401)
         # luam notele
         ritm = serializer.validated_data.get('ritm')
         coregrafie = serializer.validated_data.get('coregrafie')
         corectitudine = serializer.validated_data.get('corectitudine')
         componentaArtistica = serializer.validated_data.get(
             'componentaArtistica')
         # calculam notele
         procent = Grade.objects.get(contest_id_id=contestId)
         nota = procent.ritm * ritm
         nota = nota + procent.coregrafie * coregrafie
         nota = nota + procent.corectitudine * corectitudine
         nota = nota + procent.componentaArtistica * componentaArtistica
         nota = nota / 10
         print(nota)
         # facem update la nota veche
         notaVeche = participant.nota
         nota = nota + notaVeche
         # cati au votat participantul respectiv
         vote = participant.vote
         vote = vote + 1
         print(participant.vote)
         print(str(vote) + "dsadasd")
         # verific daca acel jurat a mai votat
         whoVoted = participant.whoVoted
         whoVotedPk = whoVoted.split()
         item = Juror.objects.get(contest__id=contestId, username=numeJurat)
         try:
             thing_index = whoVotedPk.index(str(item.id))
         except ValueError:
             thing_index = -1
         # daca nu a votat, il lasam sa voteze
         if thing_index == -1:
             Participant.objects.filter(contests__id=contestId,
                                        pk=pId).update(nota=nota)
             Participant.objects.filter(contests__id=contestId,
                                        pk=pId).update(vote=vote)
             whoVoted = whoVoted + " " + str(item.id)
             Participant.objects.filter(contests__id=contestId,
                                        pk=pId).update(whoVoted=whoVoted)
             return Response(serializer.data, status=201)
         return Response(
             status=401)  #nu are autorizatie sa mai voteze again
     return Response(serializer.errors, status=400)
コード例 #12
0
ファイル: notes_test.py プロジェクト: dschien/greendoors-web
    def createNote(self, user, text, house=None):
        note = Note(text=text, user=user, timestamp=time.time(), house=house)
        note.save()

        return note
コード例 #13
0
ファイル: scripts.py プロジェクト: andersravn/citystories
def get_notes(place):
    special_cases = {
        'Joh. Baunes Plads': 'Johannes Baunes Plads',
        'Marselisborg Gods': 'Marselisborg Gymnasium',
    }

    records_url = 'https://openaws.appspot.com/records?collection=1&locations='
    entities_url = 'https://openaws.appspot.com/entities/'

    records_response = requests.get(records_url + str(place.placeid))
    entities_response = requests.get(entities_url + str(place.placeid))

    records_data = records_response.json()
    entities_data = entities_response.json()
    note_type = ''
    lat = 0
    lon = 0
    place_lol = False

    if entities_data['result']['entity_type'][1] == 'Address':
        try:
            lat = str(entities_data['result']['latitude'])
            lon = str(entities_data['result']['longitude'])
        except KeyError:
            return
    elif entities_data['result']['entity_type'][1] == 'Place':
        if entities_data['result']['name'] == 'Joh. Baunes Plads':
            lat, lon = get_coords('Johannes Baunes Plads')
        elif entities_data['result']['name'] == 'Marselisborg Gods':
            lat, lon = get_coords('Marselisborg Gymnasium')
        elif entities_data['result']['name'] == 'Skejby Mark':
            lat, lon = get_coords('Herredsvej')
        elif entities_data['result']['name'] == 'Mindebro':
            lat, lon = 56.152618, 10.213938
        elif entities_data['result']['name'] == 'Solgaarden':
            lat, lon = 56.149237, 10.157762
        elif entities_data['result']['name'] == 'Bispetoften':
            lat, lon = 0, 0
        elif entities_data['result']['name'] == 'Aarhus Kunstbygning':
            lat, lon = get_coords('Kunsthal Aarhus')
        else:
            try:
                lat, lon = get_coords(entities_data['result']['name'])
            except IndexError:
                lat, lon = 0, 0

    # Tjekker om result objektet er tomt.
    try:
        records_data['result'][0]
    except IndexError:
        return

    for r in records_data['result']:
        if 'personalsedler' in r['description']['hierarchical_level'].lower():
            note_type = 'personal'
        else:
            note_type = 'emne'

        date = r['description'].get('from_date', '2017-01-01')
        year = date[:4]
        month = date[5:7]
        day = date[8:]
        analog_content = r.get('analog_content', 'none')
        media = False
        admin_data = r['administration'].get('admin_data', 'none')

        if admin_data is not 'none':
            media = admin_data.get('formidlingsegnet', 'none')

            if media is not 'none':
                media = r['administration']['admin_data']['formidlingsegnet']
            else:
                media = False

        # Tjekker efter fejlindtastning i måned.
        if month == '00':
            month = '01'

        # Tjekker efter fejlindtastning i dag.
        if day == '00':
            day = '01'

        if analog_content is not 'none':
            analog_content = r['analog_content']['storage_id']

        pnt = fromstr('POINT(' + str(lon) + ' ' + str(lat) + ')', srid=4326)

        note = Note(note_id=analog_content,
                    text_content=r['description']['textcontent'],
                    note_type=note_type,
                    from_date=datetime.date(int(year), int(month), int(day)),
                    media=media,
                    lat=lat,
                    lng=lon,
                    pnt=pnt,
                    place=place)
        note.save()
        place.notes_loaded = True
        place.save()
コード例 #14
0
    def post(self, request, format=None):
        # trebuie sa verific ca e allow
        jurat = request.user
        print(jurat)
        nota = Note(jurat=jurat)
        serializer = NoteSerializer(nota, data=request.data)
        if serializer.is_valid():
            contest_id = serializer.validated_data.get('contest_id')
            # verific daca apartine concursului si poate vota
            try:
                item = Juror.objects.get(contest__id=contest_id,
                                         username=jurat)
            except Juror.DoesNotExist:
                return Response(status=404)
            p_id = serializer.validated_data.get('participant_id')
            #verific daca participantul apartine concursului
            try:
                participant = Participant.objects.get(contests__id=contest_id,
                                                      pk=p_id)
            except Participant.DoesNotExist:
                return Response(status=404)

            ritm = serializer.validated_data.get('ritm')
            coregrafie = serializer.validated_data.get('coregrafie')
            corectitudine = serializer.validated_data.get('corectitudine')
            componentaArtistica = serializer.validated_data.get(
                'componentaArtistica')
            procent = Grade.objects.get(contest_id_id=contest_id)
            nota = procent.ritm * ritm + procent.coregrafie * coregrafie
            nota = nota + procent.corectitudine * corectitudine
            nota = nota + procent.componentaArtistica * componentaArtistica
            nota = nota / 10
            print(nota)

            nota_veche = participant.nota
            print(nota_veche)
            nota = nota + nota_veche
            vote = participant.vote
            vote = vote + 1
            print(str(vote) + "   ceve ")

            whoVoted = participant.whoVoted
            whoVotedPk = whoVoted.split()
            try:
                thing_index = whoVotedPk.index(str(item.pk))
            except ValueError:
                thing_index = -1

            voteJuror = item.vote + 1
            print(thing_index)

            if thing_index == -1:
                Participant.objects.filter(contests__id=contest_id,
                                           pk=p_id).update(nota=nota)
                Participant.objects.filter(contests__id=contest_id,
                                           pk=p_id).update(vote=vote)
                whoVoted = whoVoted + " " + str(item.pk)
                Participant.objects.filter(contests__id=contest_id,
                                           pk=p_id).update(whoVoted=whoVoted)
                Juror.objects.filter(contest__id=contest_id,
                                     username=jurat).update(vote=voteJuror)
                return Response(serializer.data, status=201)
            # sa poata vota o singura data un jurat trb sa faca aia cu vote
            # nu merge asa, fac un string cu pk
            # ii fac split si apoi verific daca e in vector
            # daca e nu poate sa voteze
            return Response(
                status=401)  #nu are autorizatie sa mai voteze again
        return Response(serializer.errors, status=400)
コード例 #15
0
from django.shortcuts import render
from api.models import Note
# Create your views here.

note = Note(title="First Note", body="This is certainly noteworthy")
note.save()
Note.objects.all()
コード例 #16
0
ファイル: manage.py プロジェクト: Hassankashi/django_REST
from api.models import Note

note = Note(name="Mahsa", family="Hassankashi")
note.save()
Note.objects.all()
コード例 #17
0
ファイル: views.py プロジェクト: riefrn/moneydiary
def listsnote(request):
    list_note = Note.get_list_note()
    return render(request, 'backoffice/backoffice-note.html', {'list_note': list_note})
コード例 #18
0
ファイル: notes_test.py プロジェクト: dschien/greendoors-web
    def createNote(self, user, text, house=None):
        note = Note(text=text, user=user, timestamp=time.time(), house=house)
        note.save()

        return note