Ejemplo n.º 1
0
def add_4(request):
    teacher=Teacher(
    id=2,
    tea_name="张老师"
    )
    teacher.save()
    return HttpResponse("添加成功")
Ejemplo n.º 2
0
    def handle(self, *args, **options):
        number_teachers = options['number_teacher']

        try:
            for _ in range(number_teachers):
                Teacher.generate_teacher()
        except Exception as ex:
            raise CommandError(f'Data added fail! {ex}')
        self.stdout.write(
            self.style.SUCCESS(f'Data added successfully! {number_teachers}'))
Ejemplo n.º 3
0
def create_teacher_user():
    base_user = User.objects.create_user(email="*****@*****.**",
                                         password="******")
    base_user.teacher_status = True

    teacher = Teacher(name='test teacher',
                      department='CD',
                      phone=9828127640,
                      user=base_user)
    return teacher
Ejemplo n.º 4
0
def generate_teachers(request):
    amount = int(request.GET['amount'])
    lst = []
    if amount > 200:
        amount = 5
    for _ in range(amount):
        a = Teacher.generate_teacher()
        lst.append(a.Teacher_first_name)
        lst.append('<br>')
    return HttpResponse(f'generated {amount} teachers: <br> {lst}')
Ejemplo n.º 5
0
def managerTeach(request):
    if request.method == 'GET':
        return render(request, 'manager/teachdashboard.html')
    else:
        email = request.POST.get('email')
        name = request.POST.get('name')
        password = getRandomPassword()
        user = Account(email=email,
                       password=make_password(password),
                       is_teacher=True,
                       is_manager=False)
        user.save()
        msg = f'{name}, Your Account is created successfully, to log into your account \n please use \n email: {email} \n password : {password}'
        Mail(subject='Account Created', message=msg, recipient_list=[email])
        teacher = Teacher(name=name, user_id=user.id)
        teacher.save()
        messages.success(
            request, "Account created successfully please do check your email")
        return redirect('managerTeach')
Ejemplo n.º 6
0
def download_excel_data(request):
    user = user_models.User.objects.get(username=request.user.username)
    if user.has_perm('teacher.view_teacher'):
        # content-type of response
        response = HttpResponse(content_type='application/ms-excel')

        #decide file name
        response[
            'Content-Disposition'] = 'attachment; filename="teacher_master.xls"'

        #creating workbook
        wb = xlwt.Workbook(encoding='utf-8')

        #adding sheet
        ws = wb.add_sheet("teacher")

        # Sheet header, first row
        row_num = 0

        font_style = xlwt.XFStyle()
        # headers are bold
        font_style.font.bold = True

        #column header names, you can use your own headers here
        columns = [
            'Sr.No', 'Name', 'Mobile Number', 'Email Id', 'Date of Birth',
            'Address'
        ]

        #write column headers in sheet
        for col_num in range(len(columns)):
            ws.write(row_num, col_num, columns[col_num], font_style)

        # Sheet body, remaining rows
        font_style = xlwt.XFStyle()

        #get your data, from database or from a text file...
        data = teacher.list_teachers_data(
            request)  #dummy method to fetch data.
        for my_row in data:
            row_num = row_num + 1
            ws.write(row_num, 0, str(row_num), font_style)
            ws.write(row_num, 1, my_row['teacher_name'], font_style)
            ws.write(row_num, 2, my_row['teacher_desc'], font_style)
            ws.write(
                row_num, 3,
                user_models.User.objects.get(
                    pk=user_models.UserProfile.objects.get(
                        pk=my_row['created_by']).user_id).first_name,
                font_style)
            ws.write(row_num, 4, my_row['created_at'], font_style)
        wb.save(response)
        return response
    else:
        return render(request, 'forbidden_page.html')
Ejemplo n.º 7
0
def manager_teacherview(request):
    if request.method == 'GET':
        return render(request, 'manager/manager_teacherview.html')
    else:
        email = request.POST.get('email')
        name = request.POST.get('name')
        contact = request.POST['contact']
        password = randomPassword()
        user = Account(email=email,
                       password=make_password(password),
                       is_teacher=True,
                       is_manager=False,
                       is_student=False)
        user.save()
        msg = f'{name}, your account is created successfully \n use the following credential to login \n email:{email} \n password:{password}'
        Mail(subject='Account created', message=msg, recipient_list=[email])
        teacher = Teacher(name=name, contact=contact, user_id=user.id)
        teacher.save()
        messages.add_message(request, messages.SUCCESS,
                             'Teacher Account is created successfully')
        return redirect('manager_teacherview')
	def post(self, request, format='json'):
		serializer = UserSerializer(data=request.data)
		if serializer.is_valid():
			#print("Valid")
			user = serializer.save()
			if user:
				if request.data["isStudent"] == 1:
					new_student = Student(user=user, contact_no=request.data["contact_no"])
					new_student.save()
				elif request.data["isStudent"] == 0:
					new_teacher = Teacher(user=user, contact_no=request.data["contact_no"])
					new_teacher.save()
				else:
					return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

				token = Token.objects.create(user=user)
				json = serializer.data
				json['token'] = token.key
				return Response(json, status=status.HTTP_201_CREATED)

		return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Ejemplo n.º 9
0
        def save(self):
            super(RegisterView.RegisterForm, self).save()
            message = u'Tên người đăng ký: %s\nNgày sinh: %s\nĐiện thoại người đăng ký: %s\nEmail người đăng ký: %s\n' % (self.cleaned_data['name'],
                    self.cleaned_data['birthday'],
                    self.cleaned_data['phone'],
                    self.cleaned_data['email'],)
            send_email(u'Đăng kí tài khoản mới', message,
                    to_addr=['*****@*****.**'])
            first_name, last_name = Person.extract_fullname(
                    self.cleaned_data['name'])

            teacher = Teacher(
                    first_name=first_name,
                    last_name=last_name,
                    sms_phone=self.cleaned_data['phone'],
                    email=self.cleaned_data['email'],
                    birthday=self.cleaned_data['birthday'],
                    sex=self.cleaned_data['sex'])
            username = teacher.make_username()
            raw_password = teacher.make_password()
            user = User.objects.create(
                    username=username,
                    password=make_password(raw_password),
                    first_name=first_name,
                    last_name=last_name)
            teacher.user = user
            teacher.save()
            return teacher
Ejemplo n.º 10
0
    def setUp(self):
        self.student_a = Student(
            first_name="Tiffany",
            last_name="Jeruto",
            date_of_birth=datetime.date(2000, 6, 24),
            registration_number="254016",
            Email="*****@*****.**",
            phone_number="0789647745",
            place_of_residence="Rongai",
            guardian_phone="0789567484",
            id_number=345378625,
            date_joined=datetime.date.today(),
        )

        self.student_b = Student(
            first_name="Clay",
            last_name="Jensen",
            date_of_birth=datetime.date(1999, 7, 25),
            registration_number="254017",
            Email="*****@*****.**",
            phone_number="0789765945",
            place_of_residence="Roysambu",
            guardian_phone="0780007684",
            id_number=3453734789,
            date_joined=datetime.date.today(),
        )

        self.python = Course(name="Python",
                             duration_in_months=10,
                             Course_number="1001",
                             description="Django and Flask frameworks")

        self.javascript = Course(
            name="Javascript",
            duration_in_months=10,
            Course_number="1002",
            description="Vanilla javascript and frameworks")

        self.hardware = Course(name="Hardware",
                               duration_in_months=10,
                               Course_number="1003",
                               description=" Product design using Fusion 360")

        self.teacher = Teacher(first_name="James",
                               last_name="Mwai",
                               place_of_residence="Kilimani",
                               phone_number="0723456786",
                               Email="*****@*****.**",
                               id_number=3128956743,
                               profession="Google Expert",
                               registration_number="2344",
                               date_joined=datetime.date.today())
Ejemplo n.º 11
0
    def get(self, request):
        d = 'helloworld'

        teachers = Teacher.objects(
            id=1
        )[0:
          5]  #Teacher.objects.filter(deleted=0)[page * pagesize: pagesize * (page + 1)]

        json_data = serializers.serialize('json', teachers)  #第二个参数就是 teachers
        json_data = json.loads(json_data)

        response = JsonResponse(json_data, safe=False)  #第一个参数就是 返回个前端的字符串
        return response
Ejemplo n.º 12
0
    def setUp(self):
        self.student_a = Student.objects.create(
            first_name="Joan",
            last_name="Aluka",
            date_of_birth=datetime.date(2000, 7, 10),
            registration_number="123",
            email="*****@*****.**",
            phone_number="0718149079",
            place_of_residence="Nairobi",
            guardian_phone="12334",
            id_number=1234,
            date_joined=datetime.date.today(),
        )

        self.student_b = Student.objects.create(
            first_name="Joan",
            last_name="Aluka",
            date_of_birth=datetime.date(2000, 7, 10),
            registration_number="123",
            email="*****@*****.**",
            phone_number="0718149079",
            place_of_residence="Nairobi",
            guardian_phone="12334",
            id_number=1234,
            date_joined=datetime.date.today(),
        )

        self.python = Course.objects.create(name="python",
                                            duration_in_months=6,
                                            course_number="5",
                                            description="python")
        self.javaScript = Course.objects.create(name="javaScript",
                                                duration_in_months=6,
                                                course_number="5",
                                                description="react js")
        self.hardware = Course.objects.create(name="hardware",
                                              duration_in_months=6,
                                              course_number="5",
                                              description="product design")

        self.teacher = Teacher(
            first_name="Joan",
            last_name="Aluka",
            date_of_birth=datetime.date(2000, 7, 10),
            registration_no="123",
            email="*****@*****.**",
            phone_number="0718149079",
            place_of_residence="Nairobi",
            id_number=1234,
            profession="Frontend developer",
        )
    def handle(self, *args, **options):

        Teacher.objects.all().delete()
        group = list(Groups.objects.all())
        quantity = args[0]
        if quantity > 200:
            quantity = 5
        print(f'Generating {quantity} teachers:')
        lst = []
        for _ in range(quantity):
            a = Teacher.generate_teacher(group)
            lst.append(a)
        for teach in lst:
            print(teach.Teacher_first_name, " ", teach.Teacher_second_name)
 def post(self, request, *args, **kwargs):
     email = request.POST.get('email')
     name = request.POST.get('name')
     password_ = randomPassword()
     try:
         user = Account(email=email,
                        password=make_password(password_),
                        is_teacher=True)
         user.save()
         msg = f'{name}, Your account is created Please use the following credential to login into your account \n Email: {email} \n password: {password_}'
         Mail(subject="Account Creation",
              message=msg,
              recipient_list=[
                  email,
              ])
         teacher = Teacher(name=name, user_id=user.id)
         teacher.save()
         messages.add_message(request, messages.SUCCESS,
                              'Teacher Account is created successfully')
         return redirect(reverse_lazy('manage_teacher'))
     except Exception as e:
         messages.add_message(request, messages.ERROR, str(e))
         return redirect('manage_teacher')
Ejemplo n.º 15
0
    def post(self, request, format='json'):
        serializer = UserSerializer(data=request.data)
        if serializer.is_valid():
            #print("Valid")
            user = serializer.save()
            if user:
                if request.data["isStudent"] == 1:
                    new_student = Student(
                        user=user, contact_no=request.data["contact_no"])
                    new_student.save()
                elif request.data["isStudent"] == 0:
                    new_teacher = Teacher(
                        user=user, contact_no=request.data["contact_no"])
                    new_teacher.save()
                else:
                    return Response(serializer.errors,
                                    status=status.HTTP_400_BAD_REQUEST)

                token = Token.objects.create(user=user)
                json = serializer.data
                json['token'] = token.key
                return Response(json, status=status.HTTP_201_CREATED)

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Ejemplo n.º 16
0
	def setUp(self):
		self.student_a=Student(first_name=Joy,
			last_name=Wahome,
			date_of_birth=datetime.date(1998,8,25),
			registration_number=123,
			place_of_residence=Nairobi,
			phone_number=123456789,
			[email protected],
			guardian_phone=12345,
			id_number=1111111,
			date_joined=datetime.date.today(),)

		self.student_b=Student(first_name=Ivy,
			last_name=Wahome,
			date_of_birth=datetime.date(1996,5,24),
			registration_number=1234,
			place_of_residence=Nairobi,
			phone_number=123456789,
			[email protected],
			guardian_phone=123456,
			id_number=2222222,
			date_joined=datetime.date.today(),)

		self.python=Course(name=python,
			duration_in_months=10,
			course_number=1,
			description=Learn to code in Python,)

		self.javascript=Course(name=javascript,
			duration_in_months=10,
			course_number=2,
			description=Learn to code in JS,)

		self.hardware=Course(name=hardware,
			duration_in_months=10,
			course_number=3,
			description=Learn to build hardware,)

		self.teacher=Teacher(first_name=James,
			last_name=Mwai,
			date_of_birth=datetime.date(1998,8,25),
			registration_no=123,
			place_of_residence=Nairobi,
			phone_number=123456789,
			[email protected],
			id_number=1111111,
			profession=Consultant,)
Ejemplo n.º 17
0
def addTeacher(request):
    teacher_name = request.POST.get('tname', '')
    t = Teacher(teacher_name=teacher_name)
    t.save()
    # request.session['name_teacher'] = teacher_name
    return render_to_response('teacher/teacherAdded.html')
Ejemplo n.º 18
0
    try:
        classes = Classes.objects.get(name=classes)
    except:
        print("+++++++++++------we dont find this %r" % classes, end="||")
        newclass = Classes()
        newclass.name = classes
        newclass.save()
        #continue
        classes = newclass
    #teacher
    try:
        teacher = User.objects.get(username=teacher)
        try:
            teacher = Teacher.objects.get(teacher=teacher)
        except:
            newteacher = Teacher()
            newteacher.teacher = teacher
            newteacher.save()
            teacher = newteacher
    except:
        a = User.objects.create_user(teacher, "*****@*****.**", "jtdxjwk")
        newteacher = Teacher()
        newteacher.teacher = a
        newteacher.is_teacher = True
        newteacher.save()
        teacher = newteacher
        print("we have save a new user %r" % teacher, end="||")

    from course.models import Course
    try:
        course = Course.objects.get(name=course)
Ejemplo n.º 19
0
def generate_teachers(request):
    for _ in range(1):
        Teacher.generate_teacher()
    abc = Teacher.objects.all()
    return HttpResponse(abc)
Ejemplo n.º 20
0
def setup_teachers(request):
    # first see whether the cancel button was pressed
    if "cancel" in request.POST:
        return HttpResponseRedirect(reverse('setup_index'))

    # now start processing the file upload
    context_dict = {
    }
    context_dict['header'] = 'Upload Teachers Data'
    if request.method == 'POST':
        # get the file uploaded by the user
        form = ExcelFileUploadForm(request.POST, request.FILES)
        context_dict['form'] = form

        if form.is_valid():
            try:
                print 'now starting to process the uploaded file for setting up Teachers...'
                fileToProcess_handle = request.FILES['excelFile']

                # check that the file uploaded should be a valid excel
                # file with .xls or .xlsx
                if not validate_excel_extension(fileToProcess_handle, form, context_dict):
                    return render(request, 'classup/setup_data.html', context_dict)

                # if this is a valid excel file - start processing it
                fileToProcess = xlrd.open_workbook(filename=None, file_contents=fileToProcess_handle.read())
                sheet = fileToProcess.sheet_by_index(0)
                if (sheet):
                    print 'Successfully got hold of sheet!'
                for row in range(sheet.nrows):
                    # skip the header row
                    if (row == 0):
                        continue
                    print 'Processing a new row'
                    # we need to explicitly cast employee id to string. Else update will not function properly
                    employee_id = str(sheet.cell(row, 0).value)
                    f_name = sheet.cell(row, 1).value
                    l_name = sheet.cell(row, 2).value
                    email = sheet.cell(row, 3).value
                    # we need to explicitly case mobile number to string. Else update will not function properly
                    mobile = str(sheet.cell(row, 4).value)

                    # if this is an existing employee/teacher, this is an update operations.
                    try:
                        t = Teacher.objects.get(teacher_erp_id=employee_id)

                        if (t):
                            print 'Teacher with Employee ID: ' + employee_id + \
                                  ' & name: ' + f_name + ' already exist. This will be updated!'
                            t.first_name = f_name
                            t.last_name = l_name
                            t.email = email
                            t.mobile = mobile
                    except Exception as e:
                        print 'Exception = %s (%s)' % (e.message, type(e))
                        print 'Teacher ' + f_name + ' ' + l_name + ' is a new entry. Hence inserting...'
                        t = Teacher(teacher_erp_id=employee_id, first_name=f_name, last_name=l_name,
                                    email=email, mobile=mobile)
                    try:
                        t.save()
                        print 'Successfully created Teacher ' + f_name + ' ' + l_name

                        # now, create a user for this teacher
                        # the user name would be the email, and password would be a random string
                        password = User.objects.make_random_password(length=5)

                        print 'Initial password = '******'Successfully created user for ' + f_name + ' ' + l_name
                        except Exception as e:
                            print 'Exception = %s (%s)' % (e.message, type(e))
                            print 'Unable to create user for ' + f_name + ' ' + l_name
                        # todo implement the code to send password to the user through an sms and email

                        # make this user part of the Teachers group
                        try:
                            group = Group.objects.get(name='teachers')
                            user.groups.add(group)
                            print 'Successfully added ' + f_name + ' ' + l_name + ' to the Teachers group'
                        except Exception as e:
                            print 'Exception = %s (%s)' % (e.message, type(e))
                            print 'Unable to add ' + f_name + ' ' + l_name + ' to the Teachers group'

                    except Exception as e:
                        print 'Exception = %s (%s)' % (e.message, type(e))
                        error = 'Unable to save the data for ' + f_name + ' ' + l_name + ' in Table Teacher'
                        form.errors['__all__'] = form.error_class([error])
                        print error
                        # todo - we should skip this teacher but report this and move on to the next treacher <provide code>
                        continue

                # file upload and saving to db was successful. Hence go back to the main menu
                return HttpResponseRedirect(reverse('setup_index'))
            except Exception as e:
                print 'Exception = %s (%s)' % (e.message, type(e))
                error = 'Invalid file uploaded. Please try again.'
                form.errors['__all__'] = form.error_class([error])
                print error
                return render(request, 'classup/setup_data.html', context_dict)
    else:
        form = ExcelFileUploadForm()
        context_dict['form'] = form
    return render(request, 'classup/setup_data.html', context_dict)
Ejemplo n.º 21
0
    def handle(self, *args, **kwargs):
        count = kwargs['count']
        for _ in range(count):
            Teacher.generate_teacher()

        self.stdout.write(self.style.SUCCESS(f'Created: {count} teachers'))
Ejemplo n.º 22
0
    def create(self, request, *args, **kwargs):
        check_token = pd_adm_token(request)
        if check_token:
            return check_token

        # 用户名
        user_name = request.data.get('user_name')
        # 手机号
        phone_number = request.data.get("phone_number")
        # 密码
        password = request.data.get("password")
        # 角色
        role = request.data.get('role')
        # 真实姓名
        name = request.data.get('name')

        if not (role == 0 or role == 1 or role == 2):
            return response_success_200(code=STATUS_PARAMETER_ERROR,
                                        message="role的取值为(0, 1, 2)")

        if not pd_phone_number(phone_number):
            message = "手机号格式错误"
            return response_success_200(code=STATUS_PHONE_NUMBER_DUPLICATE,
                                        message=message)

        if check_user_name(user_name):
            message = "用户名已存在"
            return response_success_200(code=STATUS_USER_NAME_DUPLICATE,
                                        message=message)
        if check_phone_number(phone_number):
            message = "该手机号已被注册"
            return response_success_200(code=STATUS_PHONE_NUMBER_DUPLICATE,
                                        message=message)

        # 创建用户详情 并获得他的id
        user_details_id = UserDetails.objects.create(name=name).id

        # 加密
        request.data["password"] = my_encode(password)
        request.data['user_details'] = user_details_id
        request.data['token'] = "-1"

        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)

        # 创建角色信息
        user_id = serializer.data['id']
        if role == 0:
            save_teacher = Teacher(user_id=user_id)
            save_teacher.save()
        elif role == 1:
            save_student = Student(user_id=user_id)
            save_student.save()
        elif role == 2:
            save_parent = Parent(user_id=user_id)
            save_parent.save()
        else:
            message = "角色不存在"
            return response_success_200(status=STATUS_CODE_ERROR,
                                        message=message)
        # data = serializer.data
        print(f'数据是:{serializer.data}')
        return response_success_200(code=STATUS_200_SUCCESS,
                                    data=serializer.data,
                                    headers=headers)