コード例 #1
0
def add_4(request):
    teacher=Teacher(
    id=2,
    tea_name="张老师"
    )
    teacher.save()
    return HttpResponse("添加成功")
コード例 #2
0
ファイル: views.py プロジェクト: tranvictor/truongnha
        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
コード例 #3
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')
コード例 #4
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)
コード例 #5
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')
コード例 #6
0
 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')
コード例 #7
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)
コード例 #8
0
    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)
    except:
        newcourse = Course()
コード例 #9
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)
コード例 #10
0
ファイル: views.py プロジェクト: atulmala/DreamProject
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)
コード例 #11
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')