def studentRegistration(request): registered = False uid = request.GET['value1'] print(request.user) if request.method == "POST": Student_form = StudentInfoForm(request.POST, request.FILES) if Student_form.is_valid(): Student = Student_form.save(commit=False) Student.user = request.user Student.email = request.user.email # print(request.FILES) # if 'avatar' in request.FILES: # Student.avatar = request.FILES['avatar'] Student.save() registered = True else: print(Student_form.errors) else: # user_form=UserForm() Student_form = StudentInfoForm() return render(request, 'main/studentreg.html', {'Student_form': Student_form, 'registered': registered, 'user': request.user})
def create_student(i): try: fake_id = fake_bitsID if random.random() < 0.6 else fake_phd prefix = 'f' if fake_id == fake_bitsID else 'p' (mUser, created1) = User.objects.get_or_create( username=prefix + str(i), first_name='Student' + str(i), email=prefix + str(i) + "@goa.bits-pilani.ac.in") mUser.set_password('password') mUser.save() if created1: mStudent = Student( user=mUser, name='Student ' + str(i), bitsId=fake_id(mUser.username), phone=fake_number_generator(), gender=fake_gender(), bDay=fake_date(), email=mUser.email, address='BITS Goa', bloodGroup='O+ve', cgpa=fake_cgpa(), admit=datetime.datetime.now(), parentName='Parent' + str(i), parentPhone=fake_number_generator(), bank_account_no=fake_number_generator(), ) mStudent.save() return True except Exception as e: print("Exception raised in creating student " + str(i) + ": " + str(e)) return False
def register(request): try: tutor = Tutor.objects.get(email=request.user.email) return render(request, 'main/alreadyRegistered.html', {}) except Tutor.DoesNotExist: pass try: student = Student.objects.get(email=request.user.email) return render(request, 'main/alreadyRegistered.html', {}) except Student.DoesNotExist: pass message = "" messageType = "danger" try: registration = Registration.objects.get(email=request.user.email) registerSubmitText = "Update Registration" message = "Registration Status: " + registration.status + ". Do some stuff." # TODO: Handle what happens if status isn't just pending, like they have to do something messageType = "info" except Registration.DoesNotExist: registration = None registerSubmitText = "Request Registration" if request.method == 'POST': form = SignupForm(request.POST) if form.is_valid(): print("Register good form") # Get hidden information from form fullName = str(form.cleaned_data['fullName']) email = request.user.email phone = str(form.cleaned_data['phone']) registrationType = str(form.cleaned_data['registrationType']) if registrationType == "Tutor": # TODO: tutor registration status = "Pending" message = "Your Tutor registration is being reviewed for approval. Please look over your registration information and make any needed corrections." messageType = "info" updated_at = datetime.datetime.now() registration = Registration(fullName=fullName, email=email, phone=phone, registrationType=registrationType, status=status, message=message, updated_at=updated_at) # TODO: make sure registration actually saves registration.save() pass elif registrationType == "Student": # TODO: student registration # TODO: make sure email is unique student = Student(fullName=fullName, email=email, phone=phone, status="active") student.save() # TODO: Successfully registered for students page return HttpResponseRedirect('/home/') else: pass # TODO: bad registration return render(request, 'main/register.html', {'message': message, 'messageType': messageType, 'registration': registration, 'registerSubmitText': registerSubmitText})
def create_student(request): """ Creates student by student's name """ student_name_from_request = request.GET.get('name') if not student_name_from_request: return HttpResponse('Student name missing') student = Student() student.name = student_name_from_request student.save() return HttpResponse('Student {} have been created'.format(student.name))
def register(response): if response.method == "POST": form = RegisterForm(response.POST) if form.is_valid(): form.save() if response.POST.get('role') == 'ST': a = get_object_or_404(CustomUser,email=response.POST.get('email')) b = Student(profile=a) b.save() return redirect("/") else: profile = response.user form = RegisterForm() return render(response, "register/register.html", {"form":form, "profile":profile})
def save(self): password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') username = self.cleaned_data.get('username') if password1 == password2: if len(User.objects.filter(username=username)) == 0: user = User(username=username) user.set_password(password1) user.save() student = Student(user=user, code=self.cleaned_data.get('code')) student.save() return student self.error_list.append('Пароли не совпадают') return None
def studentRegistration(request): registered = False uid = request.GET['value1'] print(request.user) if request.method == "POST": Student_form = StudentInfoForm(data=request.POST) if Student_form.is_valid(): Student = Student_form.save(commit=False) print(Student) print("HEreeee") Student.user = request.user print(request.user) if 'profile_pic' in request.FILES: Student.profile_pic = request.FILES['profile_pic'] Student.save() registered = True else: print(Student_form.errors) else: # user_form=UserForm() Student_form = StudentInfoForm() return render( request, 'main/studentreg.html', { 'Student_form': Student_form, 'registered': registered, 'user': request.user })
def addUser(request): if request.method == "POST": first_name = request.POST.get('first_name') last_name = request.POST.get('last_name') email = request.POST.get('email') user_type = request.POST.get('type') phone_number = request.POST.get('phone_number') if User.objects.filter(email=email).exists(): return JsonResponse({"error": "Duplicate user"}) alphabet = string.ascii_letters + string.digits password = ''.join(secrets.choice(alphabet) for i in range(20)) username = f2p("reza") return JsonResponse({"success": username}) user = User.objects.create_user(username, email, password) user.first_name = first_name user.last_name = last_name user.save() if user_type == "دانش آموز": student = Student(user=user) student.save() return JsonResponse({"success": "stu"}) return JsonResponse({"success": user_type}) else: return JsonResponse({"error": "Invalid Request!"})
def register(response): if response.method == "POST": form = RegisterForm(response.POST) if form.is_valid(): profile = form.save(commit=False) if response.POST.get('occupation') == '1': stud = Student(username=response.POST.get('username'), first_name=response.POST.get('first_name'), last_name=response.POST.get('last_name'), email=response.POST.get('email')) stud.save() if response.POST.get('occupation') == '2': teach = Teacher(username=response.POST.get('username'), first_name=response.POST.get('first_name'), last_name=response.POST.get('last_name'), email=response.POST.get('email')) profile.is_staff = True profile.is_superuser = True teach.save() profile.save() return redirect("/") else: form = RegisterForm() return render(response, "register/register.html", {"form": form})
def save(self): password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') username = self.cleaned_data.get('username') if password1 == password2: # TODO - make regex tmp_username = '' for x in username.lower(): if x.isalpha() or x.isdigit() or x == '_': tmp_username += x username = tmp_username if len(User.objects.filter(username=username)) == 0: # Создание ядра пользователя user = User(username=username) user.set_password(password1) user.save() # Создание студента student = None code = self.cleaned_data['code'] code_tmp = Code.objects.filter(code=code, activated=False).first() if code_tmp: code_tmp.activated = True code_tmp.save() user.groups.add(code_tmp.group) user.save() # Создание кошелька w = Wallet(amount=0, is_valid=True) w.save() student = Student(user=user, id_link=username, code=code_tmp, guest=False, wallet=w) else: student = Student(user=user, id_link=username, guest=True) student.save() return student else: self.error_list.append( 'Пользователь с таким ником уже существует') else: self.error_list.append('Пароли не совпадают') return None
def student_reg_view(request): loggedin_user = request.user loggedin_staff = Staff.objects.get(user=loggedin_user) if loggedin_user.is_staff or loggedin_staff.student_admission_access or loggedin_staff.director_access or loggedin_staff.department.lower( ) == "admission": if request.method == "GET": discounts_and_scholarships = DiscountsAndScholarship.objects.all() programmes = Programme.objects.all() event.create_event(request, request.user, "Accessed Student Creation Page") return render(request, "main/student_register.html", { "discounts": discounts_and_scholarships, "programmes": programmes }) if request.method == "POST": event.create_event(request, request.user, "Tried to create a new student") first_name = request.POST["first-name"] lasst_name = request.POST["last-name"] sex = request.POST["sex"] email = request.POST["email"] phone = request.POST["phone"] address = request.POST["address"] country = request.POST["country"] is_international = request.POST.get("is-international") programme = request.POST["programme"] has_offer = request.POST.get("has-offer") discounts = request.POST.getlist("discounts") try: new_student = Student( first_name=first_name, last_name=lasst_name, sex=sex, phone=phone, email=email, country=country, address=address, isInternationalStudent=True if is_international == "on" else False, programme_application=Programme.objects.get( pk=int(programme)), hasOffer=True if has_offer == "on" else False, ) new_student.save() event.create_event(request, request.user, f"Created student {new_student.id}") if len(discounts) > 0: for discount in discounts: discount_object = DiscountsAndScholarship.objects.get( pk=int(discount)) new_student.DiscountOrScholarship.add(discount_object) new_student.save() except IntegrityError: event.create_event(request, request.user, "Tried to create a new student") return HttpResponse("Failed to create a new user") return HttpResponseRedirect( reverse("student", args=(new_student.id, ))) else: event.create_event(request, request.user, "Tried to access student creation page") return HttpResponseRedirect(reverse("noaccess"))
def create_students_list(PER_BATCH_SIZE, YEAR_START, YEAR_END): """Creates a list of Users, then maps a Student to each User""" # First, generate the list of student users # mUser_list = [None]*(PER_BATCH_SIZE * (YEAR_END - YEAR_START + 1)) N = PER_BATCH_SIZE * (YEAR_END - YEAR_START + 1) function_prefix_list = [] stime = time.time() print("Creating Student Users...", end=" ") user_data = [] for year in range(YEAR_START, YEAR_END+1): for id in range(PER_BATCH_SIZE): i = year*10000 + id*10000//PER_BATCH_SIZE [fake_id_function, prefix] = random.choice([[fake_phd, 'p'], [fake_singlite, 'f'], [fake_dulla_firstie, 'f'], [fake_dulla_secondie, 'f'], [fake_higher_degree, 'h']]) function_prefix_list.append([fake_id_function, prefix]) user_data.append({ "username": f"{prefix}{i}", "first-name": f"Student{i}", "email": f"{prefix}{i}@goa.bits-pilani.ac.in" }) user_list = create_generic_users(user_data) print(f"{len(user_list)} created in {time.time() - stime:.3f}s") # Next, generate a list of students students_list = [] stime = time.time() print("Creating Students...", end=" ") counter = 0 for year in range(YEAR_START, YEAR_END+1): for id in range(PER_BATCH_SIZE): i = year*10000 + id*10000//PER_BATCH_SIZE mUser = user_list[counter] [fake_id_function, prefix] = function_prefix_list[counter] mStudent = Student( user=mUser, name=f'Student {i}', bitsId=fake_id_function(mUser.username), phone=fake_number_generator(), gender=fake_gender(), bDay=fake_date(), email=mUser.email, address='BITS Goa', bloodGroup='O+ve', cgpa=fake_cgpa(), admit=datetime.datetime.now(), parentName='Parent' + str(i), parentPhone=fake_number_generator(), bank_account_no=fake_number_generator(), ) students_list.append(mStudent) counter += 1 # Create file with student details relevant_details = ['name', 'bitsId', 'email', 'gender', 'phone'] with open("student-details.txt", 'w') as file: details = [] for student in students_list: details.append("\t".join(str(getattr(student, detail)) for detail in relevant_details)) file.write("\n".join(details)) with transaction.atomic(): Student.objects.bulk_create(students_list) print(f"{len(students_list)} created in {time.time() - stime:.3f}s")
['Computer Networks', 'CS8553', 'CSE', 5, '2020-12-14', '350'], ['Thermal Engineering 2', 'ME8651', 'Mech', 6, '2020-12-10', '350'], ['Dynamics and Machines', 'ME8652', 'Mech', 6, '2020-12-12', '350'], ['Design of Machine Elements', 'ME8653', 'Mech', 6, '2020-12-14', '350'], ['Mechatronics', 'ME8751', 'Mech', 7, '2020-12-10', '350'], ['Power Plant Engineering', 'ME8752', 'Mech', 7, '2020-12-12', '350'], ['Process and Plan Cost Estimation', 'ME8753', 'Mech', 7, '2020-12-14', '350'], ['Fundamentals Of Nano Science', 'GE8851', 'Mech', 8, '2020-12-10', '350'], ['Vibration and Noise Control', 'ME8852', 'Mech', 8, '2020-12-12', '350'], ] for subject in subjects: sub = Subject(Name= subject[0], Sub_code= subject[1], Department= subject[2], Semester= subject[3], DateofExam = subject[4], Fee= subject[5]) sub.save() users = [ ['310618104102', '*****@*****.**', '13dec2000', 'Sudharshanam', ''], ['2000-12-13', 'Male', 'CSE', 5], ['310618104130', '*****@*****.**', '01jan2000', 'ABC', ''], ['2000-12-31', 'Female', 'CSE', 3], ['310618104121', '*****@*****.**', '01jan2000', 'New User', ''], ['2000-12-01', 'Male', 'IT', 4], ] for i in range(0, len(users), 2): user = User(username = users[i][0], password = users[i][2], email = users[i][1], first_name= users[i][3], last_name = users[i][4]) user.save() stud = Student(user = user, DOB= users[i+1][0], Gender= users[i+1][1], Department= users[i+1][2], Semester = users[i+1][3]) stud.save()
def addStudentResualt(request): tempStudent = Student() tempStudent.teacher_id = 1 tempStudent.name_pinyin = 'null' tempStudent.family_name = 'null' tempStudent.given_name = 'null' tempStudent.nickname = 'null' tempStudent.admission_date = 'null' tempStudent.graduation_date = 'null' tempStudent.mentor = 'null' tempStudent.vice_mentor = 'null' tempStudent.birthdate = '2015-09-21' tempStudent.email = 'null' tempStudent.cellphone = 'null' tempStudent.photo = 'null' tempStudent.auth_info_modify = 0 tempStudent.auth_info_add = 0 tempStudent.auth_info_delete = 0 tempStudent.valid = 1 if 'name_cn' in request.GET: tempStudent.name_cn = request.GET['name_cn'] if 'grade' in request.GET: tempStudent.grade = request.GET['grade'] if 'student_no' in request.GET: tempStudent.student_no = request.GET['student_no'] if 'account' in request.GET: tempStudent.account = request.GET['account'] if 'password' in request.GET: tempStudent.password = request.GET['password'] if 'sex' in request.GET: tempStudent.sex = request.GET['sex'] tempStudent.save() posts = tempStudent.__class__.objects.all() t = loader.get_template('xueshengguanli.html') c = Context({'posts': posts}) return HttpResponse(t.render(c))
def addStudentResualt(request): tempStudent=Student() tempStudent.teacher_id= 1 tempStudent.name_pinyin= 'null' tempStudent.family_name= 'null' tempStudent.given_name= 'null' tempStudent.nickname= 'null' tempStudent.admission_date= 'null' tempStudent.graduation_date= 'null' tempStudent.mentor= 'null' tempStudent.vice_mentor= 'null' tempStudent.birthdate= '2015-09-21' tempStudent.email= 'null' tempStudent.cellphone= 'null' tempStudent.photo= 'null' tempStudent.auth_info_modify= 0 tempStudent.auth_info_add= 0 tempStudent.auth_info_delete= 0 tempStudent.valid=1 if 'name_cn' in request.GET: tempStudent.name_cn= request.GET['name_cn'] if 'grade' in request.GET: tempStudent.grade= request.GET['grade'] if 'student_no' in request.GET: tempStudent.student_no= request.GET['student_no'] if 'account' in request.GET: tempStudent.account= request.GET['account'] if 'password' in request.GET: tempStudent.password= request.GET['password'] if 'sex' in request.GET: tempStudent.sex= request.GET['sex'] tempStudent.save() posts = tempStudent.__class__.objects.all() t =loader.get_template('xueshengguanli.html') c =Context({'posts':posts}) return HttpResponse(t.render(c))
while i < len(surnames): user = User.objects.create_user(username=surnames[i] + str(i), password=surnames[i] + surnames[i]) user.save() i += 1 print("users generated") print("started generating students") i = 0 while i < len(names): grs = Group.objects.filter(name=st_groups[i]) if (len(grs) == 0): gr = Group.objects.all()[0] else: gr = Group.objects.get(name=st_groups[i]) stud = Student(name=names[i], surname=surnames[i], group=gr, user=User.objects.all()[i]) stud.save() i += 1 print("students generated") print("started generating resToStud") i = 0 while i < len(names): rts = ResourceToStudent( student=Student.objects.all()[i], resource=AdditionalEduResource.objects.all()[i % len(ress)]) rts.save() i += 1 print("resToStudGenerated") print("started generating PointLists") i = 0
def registration(request): # Like before, get the request's context. context = RequestContext(request) # A boolean value for telling the template whether the registration was successful. # Set to False initially. Code changes value to True when registration succeeds. registered = False # If it's a HTTP POST, we're interested in processing form data. if request.method == 'POST': # Attempt to grab information from the raw form information. # Note that we make use of both UserForm and UserProfileForm. user_form = UserForm(data=request.POST) profile_form = UserProfileForm(data=request.POST) user_type_form = UserTypeForm(data=request.POST) # If the two forms are valid... if user_form.is_valid() and profile_form.is_valid( ) and user_type_form.is_valid(): # Save the user's form data to the database. user = user_form.save() # Now we hash the password with the set_password method. # Once hashed, we can update the user object. user.set_password(user.password) user.save() nickname = profile_form.cleaned_data['nickname'] # Now sort out the Student instance. # Since we need to set the user attribute ourselves, we set commit=False. # This delays saving the model until we're ready to avoid integrity problems. user_type = user_type_form.cleaned_data['user_type'] user_type = int(user_type) #user_type = 1 if user_type: profile = Student(nickname=nickname) else: profile = Instructor(nickname=nickname) profile.user = user # Add the personal calendar for the user calendar = Calendar(name=user.username + "'s personal calendar") calendar.save() profile.cal = calendar profile.school = None # Now we save the Student model instance. profile.save() # Update our variable to tell the template registration was successful. registered = True # Invalid form or forms - mistakes or something else? # Print problems to the terminal. # They'll also be shown to the user. else: print user_form.errors, profile_form.errors, user_type_form.errors # Not a HTTP POST, so we render our form using two ModelForm instances. # These forms will be blank, ready for user input. else: user_form = UserForm() profile_form = UserProfileForm() user_type_form = UserTypeForm() # Render the template depending on the context. return render_to_response( 'main/register.html', { 'user_form': user_form, 'profile_form': profile_form, 'user_type_form': user_type_form, 'registered': registered }, context)
def handle(self, *args, **options): faker = Faker() self.stdout.write('Start inserting Students') for _ in range(options['len']): self.stdout.write('Start inserting Students') student = Student() student.name = faker.first_name() student.surname = faker.last_name() student.sex = (faker.simple_profile()).get('sex') student.address = faker.street_address() student.description = faker.text() student.birthday = faker.date_of_birth() student.email = faker.company_email() student.save() self.stdout.write('End inserting Students')