Beispiel #1
0
def jsonTeacherCrud(request):

    # Display/Filter is only on GET
    if request.is_ajax() and request.method == 'GET':
        id = request.GET.get('id', None)
        action = request.GET.get('action', None)

        if (action == "filter"):
            dictData = Teacher.objects.filter(id=id).values()
        else:
            dictData = Teacher.objects.all().values()
        #print dictData
        jsonData = json.dumps(list(dictData))
        return HttpResponse(jsonData, content_type='application/json')

    # CRUD is only on POST
    if request.is_ajax() and request.method == 'POST':
        action = request.POST.get('action', None)

        #ADD
        if (action == "add"):
            codeAfm = request.POST.get('codeAfm', None)
            codeGrad = request.POST.get('codeGrad', None)
            codeSpec = request.POST.get('codeSpec', None)
            surname = request.POST.get('surname', None)
            name = request.POST.get('name', None)

            try:
                record = Teacher(
                    codeAfm=codeAfm,
                    codeGrad=codeGrad,
                    codeSpec=codeSpec,
                    surname=surname,
                    name=name,
                ).save()
                #'Αδυναμία εισαγωγής | τροποποίησης | διαγραφής | εγγραφής.'
                msg = "Επιτυχής εισαγωγή εγγραφής!"
                helperMessageLog(request, msg, tag='info')
            except DatabaseError:
                transaction.rollback()
                msg = "Αδυναμία εισαγωγής εγγραφής!"
                helperMessageLog(request, msg, tag='error')

            dictData = Teacher.objects.filter(id=record.id).values()
            jsonData = json.dumps(dictData)
            return HttpResponse(jsonData, content_type='application/json')

        #DELETE
        if (action == "delete"):
            id = request.POST.get('id', None)

            try:
                record = Teacher.objects.filter(id=id)
                record.delete()
                msg = "Επιτυχής διαγραφή εγγραφής!"
                helperMessageLog(request, msg, tag='info')
            except DatabaseError:
                transaction.rollback()
                msg = "Αδυναμία διαγραφής εγγραφής!"
                helperMessageLog(request, msg, tag='error')
            return HttpResponse(msg, content_type='application/json')

        #UPDATE
        elif (action == "update"):
            id = request.POST.get('id', None)
            codeAfm = request.POST.get('codeAfm', None)
            codeGrad = request.POST.get('codeGrad', None)
            codeSpec = request.POST.get('codeSpec', None)
            surname = request.POST.get('surname', None)
            name = request.POST.get('name', None)

            try:
                record = Teacher.objects.filter(id=id)
                record.update(
                    codeAfm=codeAfm,
                    codeGrad=codeGrad,
                    codeSpec=codeSpec,
                    surname=surname,
                    name=name,
                )
                #'Αδυναμία εισαγωγής | τροποποίησης | διαγραφής | εγγραφής.'
                msg = "Επιτυχής τροποποίηση εγγραφής!"
                helperMessageLog(request, msg, tag='info')
            except DatabaseError:
                transaction.rollback()
                msg = "Αδυναμία τροποποίησης εγγραφής!"
                helperMessageLog(request, msg, tag='error')

            dictData = record.values()
            jsonData = json.dumps(list(dictData))
            return HttpResponse(jsonData, content_type='application/json')

    # DEFAULT on View
    else:
        dictData = Teacher.objects.all().values()
        jsonData = json.dumps(list(dictData))
        #print jsonData
        return HttpResponse(jsonData, content_type='application/json')
Beispiel #2
0
def jsonFolderCrud(request):

    dictData = []
    # GET * SELECT
    if request.is_ajax() and request.method == 'GET':
        action = request.GET.get('action', None)

        if (action == "filter"):
            LessonID = request.GET.get('LessonID', None)
            #dictData = Folder.objects.get(LessonID=LessonID).graders.all().values()   #OK
            dictData = Folder.objects.filter(LessonID=LessonID).values()
            jsonData = json.dumps(list(dictData))
            #print jsonData
            return HttpResponse(jsonData, content_type='application/json')

    # POST INS.UPD.DEL
    if request.is_ajax() and request.method == 'POST':
        action = request.POST.get('action', None)

        #INSERT COMMAND (need related LessonID ) | only add C type folders
        if (action == "add"):  # on LessonID
            LessonID = request.POST.get('LessonID', None)
            no = request.POST.get('no', None)
            books = request.POST.get('books', None)  #.title()
            codeType = request.POST.get('codeType', None)
            #status = request.POST.get('status', None)
            print 'Data:', no, books, codeType
            # Apaitoume oi fakeloi na exoun synexomeh arithmisi
            # akoma kai gia diafortikous typous
            # px fA/fANA. Ayto to allazoume efkola an theloume
            # TO kanoume giati volevei sta reports
            # alliws tha kanoume aali coding ...
            #no = Lesson.objects.get(id=LessonID).getNextFolderNo(codeType)

            try:  #with transaction.atomic():
                lesson = Lesson.objects.get(id=LessonID)
                no = lesson.getNextFolderNo(
                    -1)  # count F(AB) / even for F(ANA)
                print 'Data(new):', no, books, codeType
                record = Folder(LessonID_id=LessonID,
                                no=no,
                                books=books,
                                codeType=codeType)
                record.save()
                record.codeBarcode = '%04d-%010d' % (int(LessonID),
                                                     int(record.id))
                record.save()
                # Need to Update Lesson Data HERE aka mum Books, Folders etc.
                if codeType == '0':  # F(A)
                    print "F(A)"
                    #lesson.update(booksAB=booksAB+books,  booksABFolders=booksABFolders+1)
                    lesson.booksAB = lesson.booksAB + int(books)
                    lesson.booksABFolders = lesson.booksABFolders + 1
                    lesson.save()
                elif codeType == '1':  # F(B)
                    #lesson.booksAB += books
                    #lesson.booksABFolders += 1
                    pass
                elif codeType == '2':  # F(ANA)
                    lesson.booksC = lesson.booksC + int(books)
                    lesson.booksCFolders = lesson.booksCFolders + 1
                    lesson.save()

                msg = "Επιτυχής εισαγωγή εγγραφής!"
                helperMessageLog(request, msg, tag='info')
                #messages.info(request, msg, fail_silently=True)
            except DatabaseError:
                transaction.rollback()
                msg = "Αδυναμία εισαγωγής εγγραφής!"
                helperMessageLog(request, msg, tag='error')
                #messages.error(request, msg, fail_silently=True)

            #dictData = Lesson.objects.filter(id=record.id).values()
            #print dictData
            #jsonData = json.dumps(list(dictData))
            jsonData = json.dumps({'msg': msg})
            return HttpResponse(jsonData, content_type='application/json')

        # UPDATE
        if (action == "update"):
            id = request.POST.get('id', None)
            no = request.POST.get('no', None)
            books = request.POST.get('books', None)
            codeType = request.POST.get('codeType', None)
            #lexType = request.POST.get('lexType', None)
            #CodeStatus = request.POST.get('CodeStatus ', None)
            #CodeLocation = request.POST.get('CodeLocation', None)
            #print "FOLDER-UPDATE %s - %s - codeType:%s lexType:%s" %(no, books, codeType, lexType)

            try:  #with transaction.atomic():
                record = Folder.objects.filter(id=id)
                record.update(
                    no=no,
                    books=books,
                    codeType=codeType,
                )
                msg = "Επιτυχής τροποποίηση εγγραφής!"
                helperMessageLog(request, msg, tag='info')
                #messages.info(request, msg, fail_silently=True)
            except DatabaseError:
                transaction.rollback()
                msg = "Αδυναμία τροποποίησης εγγραφής!"
                helperMessageLog(request, msg, tag='error')
                #messages.error(request, msg, fail_silently=True)

            #Folder.objects.filter(id=id).update(isCoordinator = helperStr2Bool(isCoordinator), isgraderC = helperStr2Bool(isgraderC), status = status, )
            # return Lesson record
            #dictData = record.values()
            #jsonData = json.dumps(list(dictData))
            jsonData = json.dumps({'msg': msg})
            #print jsonData
            return HttpResponse(jsonData, content_type='application/json')

        #DELETE COMMAND
        if (action == "delete"):
            id = request.POST.get('id', None)
            try:
                record = Folder.objects.get(id=id)
                # update related lesson
                lesson = Lesson.objects.get(id=record.LessonID.id)
                print "codeType:%s" % (record.codeType)
                print "lesson:%d" % (lesson.id)
                if record.codeType == 0:  # F(A)
                    print "delete codeType:%s" % (record.codeType)
                    #lesson.update(booksAB=booksAB+books,  booksABFolders=booksABFolders+1)
                    lesson.booksAB = lesson.booksAB - int(record.books)
                    lesson.booksABFolders = lesson.booksABFolders - 1
                    lesson.save()
                elif record.codeType == 1:  # F(B)
                    pass
                elif record.codeType == 2:  # F(ANA)
                    print "delete codeType:%s" % (record.codeType)
                    lesson.booksC = lesson.booksC - int(record.books)
                    lesson.booksCFolders = lesson.booksCFolders - 1
                    lesson.save()

                record.delete()
                msg = "Επιτυχής διαγραφής Φακέλου (%s) !" % (record)
                helperMessageLog(request, msg, tag='info')

                #messages.info(request, msg, fail_silently=True)
            except IntegrityError:
                transaction.rollback()
                msg = "Αδυναμία διαγραφής Φακέλου (%s) !" % (record)
                helperMessageLog(request, msg, tag='error')
                #messages.error(request, msg, fail_silently=True)
            jsonData = json.dumps({'msg': msg})
            return HttpResponse(jsonData, content_type='application/json')

    #"Default SELECT(*) "
    dictData = Folder.objects.all().values()
    #print dictData
    jsonData = json.dumps(list(dictData))
    return HttpResponse(jsonData, content_type='application/json')
Beispiel #3
0
def jsonSpecialtyCrudv0(request):

    if request.is_ajax() and request.method == 'GET':
        id = request.GET.get('id', None)
        action = request.GET.get('action', None)

        if (action == "filter"):
            dictData = SchoolToGrade.objects.filter(id=id).values()
        else:
            dictData = SchoolToGrade.objects.all().values()
        #print dictData
        jsonData = json.dumps(list(dictData))
        return HttpResponse(jsonData, content_type='application/json')

    if request.is_ajax() and request.method == 'POST':
        action = request.POST.get('action', None)

        #ADD
        if (action == "add"):
            code = request.POST.get('code', None)
            name = request.POST.get('name', None)

            try:
                record = Specialty(code=code, name=name)
                record.save()
                #'Αδυναμία εισαγωγής | τροποποίησης | διαγραφής | εγγραφής.'
                msg = "Επιτυχής εισαγωγή εγγραφής!"
                helperMessageLog(request, msg, tag='info')
            except DatabaseError:
                transaction.rollback()
                msg = "Αδυναμία εισαγωγής εγγραφής!"
                helperMessageLog(request, msg, tag='error')

            dictData = Specialty.objects.filter(id=record.id).values()
            jsonData = json.dumps(dictData)
            return HttpResponse(jsonData, content_type='application/json')

        #DELETE
        if (action == "delete"):
            id = request.POST.get('id', None)

            try:
                record = Specialty.objects.filter(id=id)
                record.delete()
                #'Αδυναμία εισαγωγής | τροποποίησης | διαγραφής | εγγραφής.'
                msg = "Επιτυχής διαγραφή εγγραφής!"
                helperMessageLog(request, msg, tag='info')
            except DatabaseError:
                transaction.rollback()
                msg = "Αδυναμία διαγραφής εγγραφής!"
                helperMessageLog(request, msg, tag='error')
            return HttpResponse(result, content_type='application/json')

        #UPDATE
        elif (action == "update"):
            id = request.POST.get('id', None)
            code = request.POST.get('code', None)
            name = request.POST.get('name', None)

            try:
                record = Specialty.objects.filter(id=id)
                record.update(
                    code=code,
                    name=name,
                )
                #'Αδυναμία εισαγωγής | τροποποίησης | διαγραφής | εγγραφής.'
                msg = "Επιτυχής τροποποίηση εγγραφής!"
                helperMessageLog(request, msg, tag='info')
            except DatabaseError:
                transaction.rollback()
                msg = "Αδυναμία τροποποίησης εγγραφής!"
                helperMessageLog(request, msg, tag='error')

            dictData = record.values()
            #print dictData
            jsonData = json.dumps(list(dictData))
            return HttpResponse(jsonData, content_type='application/json')
        else:
            dictData = 'POST action Not Found'
            jsonData = json.dumps(dictData)
            return HttpResponse(jsonData, content_type='application/json')
            #raise Http404
    # DEFAULT
    else:
        dictData = Specialty.objects.all().values()
        jsonData = json.dumps(list(dictData))
        #print jsonData
        return HttpResponse(jsonData, content_type='application/json')
Beispiel #4
0
def jsonLessonCrud(request):

    #Handle Mesages
    #messages.success(request, 'All items on this page have free shipping.',fail_silently=False)
    #messages.warning(request, 'All items on this page have free shipping.',fail_silently=True) #OK

    # Display on GET
    if request.is_ajax() and request.method == 'GET':
        id = request.GET.get('id', None)
        action = request.GET.get('action', None)

        if (action == "filter"):
            dictData = Lesson.objects.filter(id=id).values()
        else:
            dictData = Lesson.objects.all().values()
        #print dictData
        jsonData = json.dumps(list(dictData))
        return HttpResponse(jsonData, content_type='application/json')

    # CRUD on POST
    if request.is_ajax() and request.method == 'POST':
        action = request.POST.get('action', None)
        #dictData = Lesson.objects.all().values()

        #ADD
        if (action == "add"):
            #Fakeloi 1o 2o xeri (AB)
            #booksAB = models.IntegerField(default=0, blank=False)
            #booksABFolders = models.IntegerField(default=0, blank=False)
            #booksC = request.POST.get('booksC', None)
            #booksCFolders = request.POST.get('booksCFolders', None)
            category = request.POST.get('category', None)
            name = request.POST.get('name', None)
            type = request.POST.get('type', None)

            try:
                record = Folder(category=category, name=name, type=type)
                record.save()
                msg = "Επιτυχής εισαγωγή Φακέλου (%s) !" % (record)
                helperMessageLog(request, msg, tag='info')
            except IntegrityError:
                transaction.rollback()
                msg = "Αδυναμία εισαγωγής Φακέλου (%s) !" % (record)
                helperMessageLog(request, msg, tag='error')
            #jsonData = json.dumps({'msg': msg})
            # return record
            dictData = Lesson.objects.filter(id=record.id).values()
            jsonData = json.dumps(dictData)
            return HttpResponse(jsonData, content_type='application/json')

        # UPDATE
        elif (action == "update"):
            id = request.POST.get('id', None)
            #Fakeloi 1o 2o xeri (AB)
            #booksAB booksABFolders
            booksC = request.POST.get('booksC', None)
            booksCFolders = request.POST.get('booksCFolders', None)
            category = request.POST.get('category', None)
            name = request.POST.get('name', None)
            type = request.POST.get('type', None)

            try:
                #'Αδυναμία εισαγωγής | τροποποίησης | διαγραφής | εγγραφής.'
                record = Lesson.objects.filter(id=id)
                record.update(
                    booksC=booksC,
                    booksCFolders=booksCFolders,
                    category=category,
                    name=name,
                    type=type,
                )
                msg = "Επιτυχής τροποποίηση Φακέλου (%s) !" % (record)
                helperMessageLog(request, msg, tag='info')
            except IntegrityError:
                transaction.rollback()
                msg = "Αδυναμία τροποποίησης Φακέλου (%s) !" % (record)
                helperMessageLog(request, msg, tag='error')

            # return Lesson record
            dictData = record.values()
            jsonData = json.dumps(list(dictData))
            #print jsonData
            return HttpResponse(jsonData, content_type='application/json')

        #DELETE
        if (action == "delete"):
            id = request.POST.get('id', None)
            record = Lesson.objects.filter(id=id)
            try:
                #'Αδυναμία εισαγωγής | τροποποίησης | διαγραφής | εγγραφής.'
                record.delete()
                msg = "Επιτυχής διαγραφή Φακέλου (%s) !" % (record)
                helperMessageLog(request, msg, tag='info')
            except IntegrityError:
                transaction.rollback()
                msg = "Αδυναμία διαγραφής Φακέλου (%s) !" % (record)
                helperMessageLog(request, msg, tag='error')
            return HttpResponse(result, content_type='application/json')
        # else: No POST Default

    # DEFAULT
    else:
        dictData = Lesson.objects.all().values()
        jsonData = json.dumps(list(dictData))
        #print jsonData
        return HttpResponse(jsonData, content_type='application/json')
Beispiel #5
0
def jsonFileCSVImportTeacher(request):

    responseData = []
    status = 'Success'
    #errorsFound = True
    if request.is_ajax():
        actionP = request.POST.get('action', 'error')
        filename = request.POST.get('jqxinputFileName', '')
        #idxName = request.POST.get('jqxinputIdxName', '')
        #idxFirstRow = request.POST.get('jqxinputFirstRow', '')
        print actionP, filename  #, idxName, idxFirstRow

        #2.CHECK-IMPORT
        #3.DO-IMPORT
        #filename = 'uploads/LessonsCSV.csv'
        if (actionP == 'checkimport') or (actionP == 'doimport'):
            ext = filename.split('.')[-1]
            if ext not in ['xls', 'xlsx', 'csv']:
                #return "File %s is not CSV, XLS, XLSX" % ( filename)
                #errorData.append("File %s is not CSV, XLS, XLSX" % (filename) )
                raise Http404

            dataReader = csv.reader(open(filename, mode='r'),
                                    delimiter=',',
                                    quotechar='"')
            next(dataReader, None)  # skip the headers
            (msg, tag) = ('', 'info')
            for row in dataReader:  #exclude 1st row
                if (len(row) == 0):  # skips null lines
                    continue
                #t = Teacher(name='Βασίλης', surname='Τζουμάκας', codeAfm = '10000000', codeGrad = '02000000', codeSpec = 'ΠΕ19-01',)
                codeAfm, surname, name, codeSpec, codeGrad, phoneMob, phoneHom = row[
                    0], row[1], row[2], row[3], row[4], row[5], row[6],
                codeAfmIsNull = True if codeAfm == '' else False
                surnameIsNull = True if surname == '' else False
                nameIsNull = True if name == '' else False
                codeGradIsNull = True if codeGrad == '' else False
                codeSpecIsNull = True if codeSpec == '' else False
                phoneMobIsNull = True if phoneMob == '' else False
                phoneHomIsNull = True if phoneHom == '' else False

                teacherExists = False if Teacher.objects.filter(
                    codeAfm=codeAfm).count() == 0 else True
                if codeAfmIsNull or codeGradIsNull or nameIsNull or surnameIsNull or teacherExists:
                    (status, tag) = ('error', 'error')
                else:
                    (status, tag) = ('OK', 'info')
                    if (actionP == 'doimport'):  # Now, do Import in DB
                        try:
                            print "TEACHER IMPORT:", codeAfm, surname, name, codeGrad, codeSpec, codeSpec, phoneMob, phoneHom
                            Teacher(codeAfm = codeAfm, codeGrad = codeGrad, codeSpec = codeSpec, surname = surname, name = name,\
                                    phoneMob=phoneMob, phoneHom=phoneHom).save()
                            (status, msg,
                             tag) = ('OK', "Επιτυχής εισαγωγή εγγραφής!",
                                     'info')
                        except DatabaseError:
                            (status, msg,
                             tag) = ('error', "Αδυναμία εισαγωγή εγγραφής!",
                                     'error')

                responseData.append ( {'codeAfm': codeAfm, 'codeGrad': codeGrad, 'codeSpec': codeSpec, 'surname': surname , 'name': name,\
                        'phoneMob':phoneMob, 'phoneHom':phoneHom, 'status': status })

            # page ajax
            helperMessageLog(request, msg, tag)

            dictData = {'status': status, 'data': responseData}
            #print dictData
            jsonData = json.dumps(dictData)
            return HttpResponse(jsonData, content_type='application/json')
    else:
        raise Http404
Beispiel #6
0
def jsonFileCSVImportSpecialty(request):

    responseData = []
    status = 'ΟΚ! ΔΕΝ παρουσιάστηκαν Σφάλματα!'
    #errorsFound = True
    if request.is_ajax():
        actionP = request.POST.get('action', 'error')
        filename = request.POST.get('jqxinputFileName', '')
        print actionP, filename  #, idxName, idxFirstRow

        #2.CHECK-IMPORT #3.DO-IMPORT
        #filename = 'uploads/LessonsCSV.csv'
        if (actionP == 'checkimport') or (actionP == 'doimport'):
            ext = filename.split('.')[-1]
            if ext not in ['xls', 'xlsx', 'csv']:
                #return "File %s is not CSV, XLS, XLSX" % ( filename)
                #errorData.append("File %s is not CSV, XLS, XLSX" % (filename) )
                raise Http404

            dataReader = csv.reader(open(filename, mode='r'),
                                    delimiter=',',
                                    quotechar='"')
            next(dataReader, None)  # skip the headers
            (msg, tag) = ('', 'info')
            for row in dataReader:  #exclude 1st row
                if (len(row) == 0):  # skips null lines
                    continue
                code, name, = row[0], row[1]
                #print schoolCode, schoolName, schoolDdeCode, schoolDdeName,
                codeIsNull = True if code == '' else False
                nameIsNull = True if name == '' else False
                specialtyExists = False if Specialty.objects.filter(
                    code=code).count() == 0 else True
                if codeIsNull or nameIsNull or specialtyExists:
                    (status, tag) = ('error', 'error')
                else:
                    (status, tag) = ('OK', 'info')
                    if (actionP == 'doimport'):  # Now, do Import in DB
                        try:
                            Specialty(
                                code=code,
                                name=name,
                            ).save()
                            print "SPECIALTY IMPORT:", code, name
                            (status, msg,
                             tag) = ('OK', "Επιτυχής εισαγωγή εγγραφής!",
                                     'info')
                        except DatabaseError:
                            (status, msg,
                             tag) = ('error', "Αδυναμία εισαγωγή εγγραφής!",
                                     'error')
                #
                responseData.append({
                    'code': code,
                    'name': name,
                    'status': status
                })

            # page ajax
            helperMessageLog(request, msg, tag)
            dictData = {'status': status, 'data': responseData}
            #print dictData
            jsonData = json.dumps(dictData)
            return HttpResponse(jsonData, content_type='application/json')
    else:
        raise Http404
Beispiel #7
0
def jsonFileCSVImportSchoolToGrade(request):

    responseData = []
    status = 'ΟΚ! ΔΕΝ παρουσιάστηκαν Σφάλματα!'
    #errorsFound = True
    if request.is_ajax():
        actionP = request.POST.get('action', 'error')
        filename = request.POST.get('jqxinputFileName', '')
        print actionP, filename  #, idxName, idxFirstRow

        #2.CHECK-IMPORT #3.DO-IMPORT
        #filename = 'uploads/LessonsCSV.csv'
        if (actionP == 'checkimport') or (actionP == 'doimport'):
            ext = filename.split('.')[-1]
            if ext not in ['xls', 'xlsx', 'csv']:
                #return "File %s is not CSV, XLS, XLSX" % ( filename)
                #errorData.append("File %s is not CSV, XLS, XLSX" % (filename) )
                raise Http404

            dataReader = csv.reader(open(filename, mode='r'),
                                    delimiter=',',
                                    quotechar='"')
            next(dataReader, None)  # skip the headers
            (msg, tag) = ('', 'info')
            for row in dataReader:  #exclude 1st row
                if (len(row) == 0):  # skips null lines
                    continue
                schoolCode, schoolName, schoolType, schoolTypeLex, schoolDdeCode, schoolDdeName, = row[
                    0], row[1], row[2], row[3], row[4], row[5]
                schoolAddress, schoolCity, schoolTk = row[6], row[7], row[8]
                #print schoolCode, schoolName, schoolDdeCode, schoolDdeName,
                codeIsNull = True if schoolCode == '' else False
                nameIsNull = True if schoolName == '' else False
                ddeCodeIsNull = True if schoolDdeCode == '' else False
                ddeNameIsNull = True if schoolDdeName == '' else False

                schoolExists = False if SchoolToGrade.objects.filter(
                    code=schoolCode).count() == 0 else True

                # Dry run
                if codeIsNull or nameIsNull or ddeCodeIsNull or schoolExists:
                    (status, tag) = ('error', 'error')

                    #status = 'Παρουσιάστηκαν Σφάλματα!'
                    # grid msg
                else:
                    (status, tag) = ('OK', 'info')

                    # Import in DB
                    if (actionP == 'doimport'):
                        try:
                            SchoolToGrade(
                                code=schoolCode,
                                name=schoolName,
                                type=schoolType,
                                ddeCode=schoolDdeCode,
                                ddeName=schoolDdeName,
                                address=schoolAddress,
                                city=schoolCity,
                                tk=schoolTk,
                            ).save()
                            print "SCHOOL-TO-GRADE  IMPORT:", schoolCode, schoolName, schoolDdeCode, schoolDdeName
                            (status, msg,
                             tag) = ('OK', "Επιτυχής εισαγωγή εγγραφής!",
                                     'info')
                        except DatabaseError:
                            (status, msg,
                             tag) = ('error', "Αδυναμία εισαγωγή εγγραφής!",
                                     'error')

                #responseData.append ( {'name': schoolName, 'type': lessonType , 'status': status })
                responseData.append ( {'code': schoolCode, 'name': schoolName , 'type': schoolType,\
                    'ddeCode': schoolDdeCode, 'ddeName': schoolDdeName,\
                    'address': schoolAddress, 'city': schoolCity, 'tk': schoolTk, 'status': status })

            # page ajax
            helperMessageLog(request, msg, tag)

            dictData = {'status': status, 'data': responseData}
            #print dictData
            jsonData = json.dumps(dictData)
            return HttpResponse(jsonData, content_type='application/json')
    else:
        raise Http404
Beispiel #8
0
def jsonFileCSVImportLesson(request):

    responseData = []
    status = 'Success'
    #errorsFound = True
    if request.is_ajax():
        actionP = request.POST.get('action', 'error')
        filename = request.POST.get('jqxinputFileName', '')
        #idxName = request.POST.get('jqxinputIdxName', '')
        #idxFirstRow = request.POST.get('jqxinputFirstRow', '')
        print actionP, filename  #, idxName, idxFirstRow

        #2.CHECK-IMPORT
        #3.DO-IMPORT
        #filename = 'uploads/LessonsCSV.csv'
        if (actionP == 'checkimport') or (actionP == 'doimport'):
            ext = filename.split('.')[-1]
            if ext not in ['xls', 'xlsx', 'csv']:
                #return "File %s is not CSV, XLS, XLSX" % ( filename)
                #errorData.append("File %s is not CSV, XLS, XLSX" % (filename) )
                raise Http404

            dataReader = csv.reader(open(filename, mode='r'),
                                    delimiter=',',
                                    quotechar='"')
            #dataReader = csv.reader(codecs.open(csv_filepathname, ‘rU’, ‘utf-16’))
            next(dataReader, None)  # skip the headers
            (msg, tag) = ('', 'info')
            for row in dataReader:  #exclude 1st row
                if (len(row) == 0):  # skips null lines
                    continue
                #if row[0] != 'ΜΑΘΗΜΑ': # Ignore header
                #Lesson(name = lessonName).save()
                lessonName, lessonCategory, lessonType = row[0], row[1], row[2]
                nameIsNull = True if lessonName == '' else False
                categoryIsNull = True if lessonCategory == '' else False
                typeIsNull = True if lessonType == '' else False

                # check on Table constraint
                lessonExists = False if Lesson.objects.filter(
                    name=lessonName, category=lessonCategory,
                    type=lessonType).count() == 0 else True

                # Dry run
                if nameIsNull or categoryIsNull or typeIsNull or lessonExists:
                    (status, tag) = ('error', 'error')
                    #responseData.append ( {'name': lessonName, 'type': lessonType , 'status': 'error' })
                else:
                    (status, tag) = ('OK', 'info')
                    #responseData.append ( {'name': lessonName, 'type': lessonType , 'status': 'success' })
                    #msg = msg + ('Lesson (%s) with type (%s) has errors!' %(lessonName, lessonType))

                    # Import in DB
                    if (actionP == 'doimport'):
                        try:
                            Lesson(name=lessonName,
                                   category=lessonCategory,
                                   type=lessonType).save()
                            status = 'OK'
                            msg = "Επιτυχής εισαγωγή εγγραφής!"
                        except DatabaseError:
                            (status, tag) = ('error', 'error')

                responseData.append({
                    'name': lessonName,
                    'category': lessonCategory,
                    'type': lessonType,
                    'status': status
                })
                """
                if nameIsNull or categoryIsNull or lessonExists:
                    status = 'error'
                    tag = 'error'
                    #msg = msg + ('Lesson (%s) with type (%s) has errors!' %(lessonName, lessonType))
                    responseData.append ( {'name': lessonName, 'type': lessonType , 'status': 'error' })
                else:
                    responseData.append ( {'name': lessonName, 'type': lessonType , 'status': 'success' })
                    #msg = msg + ('Lesson (%s) with type (%s) has errors!' %(lessonName, lessonType))

                    if (actionP =='doimport'):         # Now, do Import in DB 
                        try: 
                            Lesson(name = lessonName, category = lessonCategory, type = lessonType).save()
                            msg = "Επιτυχής εισαγωγή εγγραφής!"                 
                            #helperMessageLog(request, msg, tag='info')
                        except DatabaseError:
                            #msg = "Αδυναμία εισαγωγής εγγραφής!"
                            tag = 'error'
                            msg = msg + ('Αδυναμία εισαγωγής εγγραφής (%s)!' %(lessonName))
                            #helperMessageLog(request, msg, tag='error')
                """

            helperMessageLog(request, msg, tag)
            dictData = {'status': status, 'data': responseData}
            #print dictData
            jsonData = json.dumps(dictData)
            #print jsonData
            return HttpResponse(jsonData, content_type='application/json')
    else:
        raise Http404