예제 #1
0
    def save(self):
        """ Save an user like teacher or student"""

        data = self.cleaned_data

        data.pop('password_confirmation')

        is_teacher = data['is_teacher']
        data.pop('is_teacher')

        # Crear el username
        data['username'] = data['first_name'][:1] + data['last_name'].split(
            ' ')[0]
        data['username'] = data['username'].upper()

        while User.objects.filter(username=data['username']).exists():
            data['username'] = data['username'] + str(randrange(1000, 9999))

        user = User.objects.create_user(**data)

        if is_teacher:
            teacher = Teacher(user=user)
            teacher.save()
        else:
            student = Student(user=user)
            student.save()
def addTeacherView(request):
    form = AddTeacherForm()
    if request.method == 'POST':
        form = AddTeacherForm(request.POST)
        if form.is_valid():
            name = form.cleaned_data['name']
            teacher_pin = form.cleaned_data['teacher_pin']
            designation = form.cleaned_data['designation']
            joined = form.cleaned_data['joined']
            phone = form.cleaned_data['phone']
            instance = Teacher(name=name,
                               techer_id=teacher_pin,
                               designation=designation,
                               joined=joined,
                               phone=phone)
            instance.save()
            form = AddTeacherForm()
            return redirect('/teachers/')

    else:
        form = AddTeacherForm()
    context = {
        'form': form,
    }
    return render(request, 'teachers/add_teacher.html', context)
예제 #3
0
def generate_plan(request):
    context = {}
    # here call method to generate possible plan and
    # generate events to the students

    free_times = FreeTime.objects.filter(student=request.user)
    hobbies_user = Hobbie.objects.filter(student=request.user)
    str_hobbies = [x.name for x in hobbies_user]
    activities = Activity.objects.filter(student=request.user)
    possible_classe = []
    for free_time in free_times:
        # available classes at that time with that topic for that user
        ans = Class.objects.filter(start__gte=free_time.start,
                                   end__lte=free_time.end)
        for a in ans:
            if a.topic in str_hobbies:
                possible_classe.append(a)

    if len(possible_classe) == 0:
        Teacher.objects.all().delete()
        for row in generate_random_teachers(30):
            t = Teacher(name=row["name"],
                        email=row["email"],
                        last_name=row["last_name"])
            t.save()
            for p in row["proposals"]:
                nclass = Class(
                    teacher=t,
                    topic=p["topic"],
                    start=p["start"],
                    end=p["end"],
                    slots=p["number_of_slots"],
                )
                nclass.save()

    if len(possible_classe) == 0:
        messages.info(
            request,
            "There are not available classes that match your availability & hobbies.",
        )
        messages.info(
            request,
            "But we propose some interesting ideas, you can change them.",
        )
        possible_classe = random.sample(list(Class.objects.all()), 3)

    Class.objects.filter(student=request.user).delete()
    for p in possible_classe:
        p.student = request.user
        p.save()

    hobbies = ", ".join([h.name for h in hobbies_user])
    context["hobbies"] = hobbies
    context["free_times"] = free_times
    context["activities"] = activities
    context["classes"] = possible_classe

    return redirect("students:index")
예제 #4
0
 def setUp(self):
     College.objects.create(name='software college')
     teacher_user = User.objects.create(
         username='******', password='******')
     teacher = Teacher(user=teacher_user, email='*****@*****.**')
     teacher.save()
     Room.objects.create(
         title='', college_id=1, description='',
         password='******', host_email_id='*****@*****.**', is_white_board=1, is_code_editor=1)
예제 #5
0
def add_teachers_to_db(csv_file: str, department: Model) -> None:
    with open(csv_file, 'r', encoding='utf-8') as file:
        reader = csv.DictReader(file)
        for row in reader:
            second_name = row['second_name']
            first_name = row['first_name']
            middle_name = row['middle_name']
            kstu_link = row['kstu_link']
            teacher = Teacher(second_name=second_name,
                              first_name=first_name,
                              middle_name=middle_name,
                              kstu_link=kstu_link,
                              department=department)
            teacher.save()
예제 #6
0
    def handle(self, *args, **options):
        Group.objects.all().delete()
        Student.objects.all().delete()
        Teacher.objects.all().delete()

        # Create 100 students wo group/teacher
        students = [Student.generate_student() for i in range(100)]
        print(len(students))

        # Create 10 teachers wo group
        teachers = [Teacher.gen_teacher() for i in range(10)]
        print(len(teachers))

        # Create 10 groups wo teacher and senior
        groups = [Group.gen_group() for i in range(10)]

        # Update students with random Group
        for student in students:
            student.groups = random.choice(groups)
            print(student.groups)
            student.save()

        # Add for Group senior FROM THE GROUP and curator - random teacher
        for group in groups:
            while group.senior is None:
                student = random.choice(students)
                if student.groups.id == group.id:
                    group.senior = student
                else:
                    print(f'student {student.groups} not in group {group.id}')
            group.curator = random.choice(teachers)
            group.save()
            print(group.get_info())
예제 #7
0
 def setUp(self):
     College.objects.create(name='software college')
     teacher_user = User.objects.create_user(username='******',
                                             password='******')
     teacher = Teacher(user=teacher_user, email='*****@*****.**')
     teacher.save()
     Room.objects.create(title='',
                         college_id=1,
                         description='',
                         password='******',
                         host_email_id='*****@*****.**',
                         is_white_board=1,
                         is_code_editor=1)
     RoomCalendar.objects.create(room_id_id=1,
                                 week='1',
                                 day='3',
                                 open_time='17:30',
                                 end_time='18:30')
예제 #8
0
def signup_view(request):
    if not request.user.admin:
        return HttpResponse(
            '<h1>You are not authorised to view this page</h1>')

    if request.method == 'POST':
        form = UserSignupForm(request.POST, request.FILES)
        form2 = StudentExtraForm(request.POST)
        if form.is_valid():
            user = form.save(commit=False)
            email = form.cleaned_data.get('email')
            password = form.cleaned_data.get('password1')
            user.save()
            user = authenticate(email=email, password=password)
            role = request.POST.get('role')
            login(request, user)
            if role == 'Teacher':
                user = request.user
                user.is_teacher = True
                user.is_student = False
                user.save()
                teacher = Teacher(user=user)
                teacher.save()
                return redirect('teachers:home')
            else:
                if form2.is_valid():
                    user = request.user
                    user.is_student = True
                    user.save()
                    student = form2.save(user)
                    student.standards.add(student.current_standard)
                    student.save()
                    return redirect('students:home')

    else:
        form = UserSignupForm()
        form2 = StudentExtraForm()

    return render(request, 'admins/home.html', {
        'form': form,
        'studentForm': form2
    })
예제 #9
0
    def handle(self, *args, **options):
        fake = Faker()

        teachers = []
        for _ in range(1000):
            teachers.append(
                Teacher(
                    first_name=fake.first_name(),
                    last_name=fake.last_name(),
                    age=random.randint(10, 100),
                ))
        Teacher.objects.bulk_create(teachers)
예제 #10
0
 def handle(self, *args, **options):
     fake = Faker()
     specifications = ['Python', 'Javascript', 'Java', 'C++']
     count = options.get('number_of_teachers')
     for _ in range(count):
         new_teachers.append(Teacher(
             first_name=fake.first_name(),
             last_name=fake.last_name(),
             age=randint(25, 100),
             specification=choice(specifications),
             active_groups=randint(1, 5)
         ))
         Teacher.objects.bulk_create(new_teachers)
예제 #11
0
 def handle(self, *args, **kwargs):
     fake = Faker()
     count = kwargs['count']
     teachers = []
     for _ in range(count):
         teachers.append(Teacher(
             first_name=fake.first_name(),
             last_name=fake.last_name(),
             age=random.randint(20, 60),
             teaching_subjects=fake.job(),
         ))
     Teacher.objects.bulk_create(teachers)
     self.stdout.write(f'Created {count} teachers.')
 def handle(self, *args, **kwargs):
     value = kwargs['value']
     fake = Faker()
     teachers = []
     for _ in range(value):
         teachers.append(
             Teacher(
                 first_name=fake.first_name(),
                 last_name=fake.last_name(),
                 age=fake.pyint(20, 90, 1),
                 number_of_hours=fake.pyint(0, 200, 1),
                 subject=fake.job(),
             ))
     Teacher.objects.bulk_create(teachers)
예제 #13
0
def atomic_create_teacher(table, rows):
    """the function of admin atomic_create_teacher"""
    try:
        with transaction.atomic():
            for i in range(1, rows):
                row_values = table.row_values(i)
                teacher_user = User.objects.create_user(username=row_values[0],
                                                        password=row_values[1])
                teacher = Teacher(user=teacher_user, email=row_values[0])
                teacher.save()
    except Exception:
        data = {'code': '0003', 'msg': '导入教师账号失败'}
    else:
        teachers = Teacher.objects.all()
        data_json = json.loads(serializers.serialize("json", teachers))
        return_data = []
        for data in data_json:
            primary_key = data["pk"]
            fields = data["fields"]
            fields["pk"] = primary_key
            del fields["user"]
            return_data.append(fields)
        data = {'code': '0000', 'msg': '导入教师账号成功', 'data': return_data}
    return data
예제 #14
0
 def handle(self, *args, **options):
     fake = Faker()
     count = 100
     if options.get('count'):
         if options.get('count').isdigit():
             count = int(options.get('count'))
     choices = ['High', 'Middle', 'Low']
     insert_data = []
     for _ in range(count):
         insert_data.append(Teacher(first_name=fake.first_name(),
                                    last_name=fake.last_name(),
                                    age=random.randint(22, 60),
                                    education=random.choice(choices),
                                    ))
     Teacher.objects.bulk_create(insert_data)
예제 #15
0
    def handle(self, *args, **options):
        fake = Faker()

        course = [
            'PHP', 'Java', 'Python', 'Ruby', 'Rust', 'Swift', 'Linux',
            'Introduction'
        ]
        teacher = []

        for _ in range(100):
            teacher.append(
                Teacher(
                    first_name=fake.first_name(),
                    last_name=fake.last_name(),
                    age=random.randint(25, 45),
                    course=random.choice(course),
                ))

        Teacher.objects.bulk_create(teacher)
예제 #16
0
def make_fake_teacher() -> Teacher:
    return Teacher(first_name=fake.first_name(),
                   last_name=fake.last_name(),
                   stupen=random.choice(stups))
예제 #17
0
    droplet_student_limit=1,
)
class1.save()

class2 = Class(
    prefix="potions",
    name="Potions",
    droplet_image="ubuntu-20-04-x64",
    droplet_size="s-1vcpu-1gb",
    droplet_region="sfo3",
    droplet_student_limit=3,
    allow_registration=True,
)
class2.save()

teacher1 = Teacher(user=user1, droplet_limit=50)
teacher1.save()
teacher1.classes.add(class1)

teacher2 = Teacher(user=user2, droplet_limit=50)
teacher2.save()
teacher2.classes.add(class2)

student1 = Student(user=user3)
student1.save()
student1.classes.add(class1, class2)

student2 = Student(user=user4)
student2.save()
student2.classes.add(class1, class2)
예제 #18
0
def add(request):
    name = request.POST["name"]
    t = Teacher( name = name )
    t.save()
    return HttpResponseRedirect(reverse('teachers.views.index'))
예제 #19
0
def generate_teacher(request):
    teacher = Teacher.gen_teacher()
    return HttpResponse(f'{teacher.get_info()}')
예제 #20
0
 def handle(self, *args, **options):
     num = int(options.get('number') or 1)
     for _ in range(num):
         Teacher.generate_teacher()
예제 #21
0
파일: dummy.py 프로젝트: itao/wnw
def init():
    print 'Existing database will be wiped, continue? (y/n)'
    choice = raw_input().strip()
    if choice == 'y':

        print 'Working...'

        # Wipe db
        clean()

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

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

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

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

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


        k = Klass.objects.all()[0]
        s = Student.objects.all()
        # Create notes
        for i in range(3):
            index = str(i+1)
            detail = 'This is note #' + index
            n = Note(klass=k, detail=detail)
            n.save()
            n.students = s[:i+1]
        print 'All done, goodbye!'
    else:
        print 'Fine, I see how it is.'
예제 #22
0
def register_view(request):
    # make sure users that are logged in can't reach this
    if request.user.is_authenticated and request.user.is_active:
        return redirect('/')

    # grab all schools to pass onto registration form
    schools = School.objects.all()

    if request.method == 'POST':
        if request.POST['type'] == 'teacher':
            try:
                new_user = User.objects.create_user(
                    username=request.POST['username'],
                    first_name=request.POST['first_name'],
                    last_name=request.POST['last_name'],
                    password=request.POST['password'],
                    email=request.POST['email']
                )
            except IntegrityError as e:
                if str(e) == 'column username is not unique':
                    return render(request, 'auth/register.html', {
                        'schools': schools,
                        'error': 'Username is already taken.'
                    })
                else:
                    return render(request, 'auth/register.html', {
                        'schools': schools,
                        'error': 'Registration error. Please try again.'
                    })

            needs_tos = Permission.objects.get(codename='needs_tos')
            new_user.user_permissions.add(needs_tos)
            new_user.save()
            teacher_name = new_user.first_name + ' ' + new_user.last_name

            # grab the selected school model
            home_school = School.objects.get(pk=request.POST['school'])

            new_teacher = Teacher(school=home_school)
            new_teacher.save()

            z_user = ZerebralUser(user=new_user, teacher=new_teacher)
            z_user.save()

            new_user = authenticate(username=request.POST['username'], password=request.POST['password'])
            login(request, new_user)

            # send the welcome email
            send_teacher_welcome_email(teacher_name, new_user.email)

            return redirect('/accounts/tos')
        elif request.POST['type'] == 'student':
            try:
                new_user = User.objects.create_user(
                    username=request.POST['username'],
                    first_name=request.POST['first_name'],
                    last_name=request.POST['last_name'],
                    password=request.POST['password'],
                    email=request.POST['email']
                )
            except IntegrityError as e:
                if str(e) == 'column username is not unique':
                    return render(request, 'auth/register.html', {
                        'schools': schools,
                        'error': 'Username is already taken.'
                    })
                else:
                    return render(request, 'auth/register.html', {
                        'schools': schools,
                        'error': 'Registration error. Please try again.'
                    })

            needs_tos = Permission.objects.get(codename='needs_tos')
            new_user.user_permissions.add(needs_tos)
            new_user.save()
            student_name = new_user.first_name + ' ' + new_user.last_name

            # grab the existing parent or create a new one
            try:
                new_parent = Parent.objects.get(email__iexact=request.POST['parent_email'])
            except:
                new_parent = None

            try:
                if new_parent is None:
                    new_parent = Parent(
                        email=request.POST['parent_email'],
                        first_name=request.POST['parent_first_name'],
                        last_name=request.POST['parent_last_name']
                    )
                    new_parent.save()

                new_student = Student(
                    parent_token=generate_token(50),
                    parent=new_parent
                )
                new_student.save()
            except:
                new_user.delete()
                return render(request, 'auth/register.html', {
                    'schools': schools,
                    'error': "Please enter your parent's contact info."
               })

            # send email to parent for consent
            send_consent_email(
                request.build_absolute_uri('/parent/consent/'+new_student.parent_token),
                student_name,
                new_parent.email
            )

            z_user = ZerebralUser(user=new_user, student=new_student)
            z_user.save()

            new_user = authenticate(username=request.POST['username'], password=request.POST['password'])
            login(request, new_user)

            # send the welcome email
            send_student_welcome_email(student_name, new_user.email)

            return redirect('/accounts/tos')



    return render(request, 'auth/register.html', {'schools': schools})