def user_add(request): if request.method == 'POST': form = UserCreateForm(request.POST) if form.is_valid(): u = User(first_name=form.cleaned_data['first_name'], last_name=form.cleaned_data['last_name'], email=form.cleaned_data['email'], is_active=True) # Generate the username username = None while True: username = shortuuid.ShortUUID().random(length=25).upper() if not get_user_model().objects.filter( username=username).exists(): break u.username = username u.set_password(form.cleaned_data['password']) u.save() up = UserProfile( permission_mode=form.cleaned_data['permission_mode']) up.user = u up.save() return HttpResponseRedirect(reverse("admin_user_list")) else: form = UserCreateForm() return render(request, "admin/admin_user_detail.html", { "form": form, "create": True })
def CreatePlayer(self): username = self.POST.get('username') phone = self.POST.get('phone') time = self.POST.get('time') area = self.POST.get('area') school = self.POST.get('school') where = self.POST.get('where') nowtime = datetime.datetime.now() age = int(nowtime.strftime('%Y')) - int(time[:4]) user = User.objects.filter(username=phone) try: if len(user) == 0: user = User.objects.create_user(username=phone, password='******') profile = UserProfile() profile.user_id = user.id profile.name = username profile.palace = area profile.role = '球员' profile.rights = 4 profile.date = time profile.age = age profile.school = school profile.save() player_basic = Player_Basic() player_basic.user_id = profile.id player_basic.position = where player_basic.where_from = self.user.id player_basic.save() return JsonResponse(Msg().Success(msg='添加成功'), safe=False) else: return JsonResponse(Msg().Success(msg='该手机号已被注册了'), safe=False) except Exception as e: print(e) return JsonResponse(Msg().Error(), safe=False)
def login_view(request): elem = { 'title':'Login', } #inloggade användare behöver inte se login view if request.user.is_authenticated(): return HttpResponseRedirect('/home/') if request.method == 'POST': loginform = LoginForm(request.POST) loginAuth(request) if loginform.is_valid(): if request.user.is_authenticated(): #endast för admin, som saknar user profile från början, underlättar testning up = UserProfile.objects.filter(user=request.user) if not up.exists(): new_profile = UserProfile(user=request.user, description=16*"admin") new_profile.save() return HttpResponseRedirect('/home/') else: return HttpResponseRedirect('') loginform = LoginForm() elem.update({'error':'inloggning misslyckades','login_form':loginform}) print "aha" return render_to_response("login.html",elem,context_instance=RequestContext(request)) else: loginform = LoginForm() elem.update({'login_form':loginform}) return render_to_response("login.html",elem,context_instance=RequestContext(request))
def CreateRole(self): username = self.POST.get('username') phone = self.POST.get('phone') time = self.POST.get('time') area = self.POST.get('area') school = self.POST.get('school') role = self.POST.get('role') nowtime = datetime.datetime.now() age = int(nowtime.strftime("%Y")) - int(time[:4]) user = User.objects.filter(username=phone) team_id = UserProfile.objects.get(user_id=self.user.id).team_id try: if len(user) == 0: user = User.objects.create_user(username=phone, password='******') profile = UserProfile() profile.user_id = user.id profile.name = username profile.palace = area if role == '教练': profile.rights = 2 else: profile.rights = 3 profile.role = role profile.date = time profile.age = age profile.school = school profile.team_id = team_id profile.save() return JsonResponse(Msg().Success(msg='添加成功)'), safe=False) else: return JsonResponse(Msg().Success(msg='该手机号码已被注册'), safa=False) except Exception as e: print(e) return JsonResponse(Msg().Error(), safe=False)
def register(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): email = form.cleaned_data['email'] password = form.cleaned_data['password'] first_name = form.cleaned_data['first_name'] last_name = form.cleaned_data['last_name'] user = User.objects.create_user(email, #email is username email, #email password) user.first_name = first_name user.last_name = last_name user.save() up = UserProfile(user=user) up.save() #request.session['next'] = '/' return authenticate(request, email, password) else: form = RegistrationForm() return render_to_response("login.html", { 'form': form, }, context_instance = RequestContext(request) )
def add_user(username, password, email, qq, icp, nickname, sex): password = hashlib.md5(password).hexdigest() u = User(username=username, password=password, email=email) u.save() up = UserProfile(user=u, sex=sex, nickname=nickname, qq=int(qq), icp=icp) up.save() return up
def create_profile(current_user): if request.content_type == 'application/json': data = request.get_json() emp_id = current_user.id first_name = data.get('first_name') last_name = data.get('last_name') designation = data.get('designation') experience = data.get('experience') gender = data.get('gender') skills = data.get('skills') client = data.get('client') location = data.get('location') address = data.get('address') mobile = data.get('mobile') image_url = data.get('image_url') linked_in = data.get('linked_in') github = data.get('github') slack = data.get('slack') joining_date = data.get('joining_date') dob = data.get('dob') if emp_id: user_profile = UserProfile(emp_id, first_name, last_name, designation, experience, gender, skills, client, location, address, mobile, image_url, linked_in, github, slack, joining_date, dob) else: return {"message": "unprocessible entity"}, 422 try: user_profile.save() return { "message": "Profile added successfully" }, 200 except: return {"message": "unable to add profile"}, 500
def register(request): if request.user.is_authenticated(): response = HttpResponse() response.status_code = 303 response['location'] = 'account' return response userExists = False if request.method == 'POST': data = request.POST username = data['username'] u = User.objects.filter(username=username) if not u.exists(): first_name = data['firstname'] last_name = data['lastname'] password = data['password'] email = data['email'] address1 = data['address1'] address2 = data['address2'] ccn = data['ccn'].replace(" ","") ccnexp = datetime.strptime(data['ccnexp'],'%Y-%m') user = User(username=username,password=password,email=email,first_name=first_name,last_name=last_name) user.save() user.set_password(user.password) user.save() extra = UserProfile(address1=address1,address2=address2,ccn=ccn, ccnexp=ccnexp) extra.user = user extra.save() user = authenticate(username=username,password=password) if user is not None: if user.is_active: auth_login(request,user) response = HttpResponse() response.status_code = 303 response['location'] = 'account' return response else: print("non-active user") else: print('incorrect login') else: userExists = True return render(request, 'app/register.html', {"userExists":userExists})
def save_model(self, request, obj, form, change): result = super(MyUserAdmin, self).save_model(request, obj, form, change) if not UserProfile.objects.filter(user=obj): profile = UserProfile(user=obj) profile.save() return result
def form_valid(self, form): res = super(FrietjesRegistrationView, self).form_valid(form) # TODO: Fix this mess user = User.objects.get(username=form.cleaned_data['username']) user_profile = UserProfile(user_id=user.pk, company=self.invite.company) user_profile.save() self.invite.used_on = datetime.datetime.now() self.invite.save() return res
def settings(request): # Check if UserProfile already exists, if it does we just update it with relevant changes. hc = "" pub = False try: profile = request.user.userprofile hc = profile.homeCountry.name pub = profile.public except UserProfile.DoesNotExist: profile = UserProfile(user=request.user) # Create an array of all our destinations, # and then dump into json so we can pass it on to settings.html for autocomplete # Ordered by alphabetical order # Ordered by alphabetical order dest = [ destination.name for destination in Destination.objects.all().order_by('name') ] compile = {'names': dest, 'hc': hc, 'public': pub} data = json.dumps(compile) if request.method == 'POST': form = Settings(request.POST, request.FILES, instance=profile) # Set up values from form if form.is_valid(): profile = form.save(commit=False) profile.user = request.user # AutoComplete works with TextInput, therefore we match a valid text input to Destination entity # Form Validation happens in JavaScript, only valid result accepted onSubmit homeCountryText = form.cleaned_data['homeCountryText'] destinationObject = Destination.objects.get( name__exact=homeCountryText) profile.homeCountry = destinationObject profile.public = form.cleaned_data['public'] profile.save() # Use Redirect so that URL in browser also changes return HttpResponseRedirect(reverse('home')) else: print(form.errors) else: form = Settings(instance=profile) request = render( request, 'app/settings.html', { 'form': form, 'json_data': data, 'previous': request.META.get('HTTP_REFERER') }) return request
def createUser(request): if request.POST: # 获取参数 username = request.POST.get('phoneNumber', None) pwd1 = request.POST.get('pwd1', None) pwd2 = request.POST.get('pwd2', None) nickname = request.POST.get('nickname', None) city = request.POST.get('city', None) gender = request.POST.get('gender', None) if (gender is None) or (nickname is None) or (city is None) or (pwd1 is None) or (pwd2 is None) or ( username is None): return render(request, 'register.html', {'msg': '信息不能为空'}) else: if pwd1 == pwd2: # 判断用户是否存在 user = User.objects.filter(username=username) if len(user) > 0: return render(request, 'register.html', {'msg': '用户名已经被使用'}) # 这是用户名可以使用的时候 # 向django_user数据表种添加数据 user = User.objects.create_user(username=username, password=pwd1) # 向userProfile表中添加数据 profile = UserProfile() # 这是建立外键的一对一关系 profile.user_id = user.id profile.gender = gender # 这是为phone属性赋值 profile.nickname = nickname profile.city = city profile.save() # 给用户添加权限 contentType = ContentType.objects.get_for_model(Result) permissions = Permission.objects.filter(content_type=contentType) # 添加 点赞 和 查看排行榜 的电脑 user.user_permissions.add(permissions[0], permissions[3]) user.save() print(user.get_all_permissions()) return redirect('/app/login/') else: return render(request, 'register.html', {'msg': '注册失败,请检查密码格式'}) else: return render(request, 'register.html')
def register(request): assert isinstance(request, HttpRequest) if request.method == 'POST': username = request.POST['user[name]'] password = request.POST['user[password]'] new_user = User.objects.create_user(username, request.POST['user[email]'], password) new_user.save() profile = UserProfile(user=new_user); profile.save(); user = authenticate(username=username, password=password) login(request, user) return render( request, 'app/index.html', context_instance = RequestContext(request, { 'title':'易游', 'year':datetime.now().year, }) )
def sign(request): users = Users.objects.all() email = request.POST.get('email') name = request.POST.get('name') password = request.POST.get('password') token_push = request.POST.get('token_push') age = request.POST.get('age') gender = request.POST.get('gender') defaultCity = request.POST.get('defaultCity') currentCity = request.POST.get('currentCity') photo1 = request.POST.get('photo1') photo2 = request.POST.get('photo2') photo3 = request.POST.get('photo3') i = 0 userProfileObj = UserProfile(nameUserProfile=name, genderUserProfile=gender, ageUserProfile=age) userProfileObj.save() userProfileObj = UserProfile.objects.get(nameUserProfile=name, genderUserProfile=gender, ageUserProfile=age) cityObj = City(default=defaultCity, current=currentCity) picturesObj = Pictures(picture01=photo1, picture02=photo2, picture03=photo3) userObj = Users(mailUser=email, passwordUser=password, token_push=token_push, UserProfile_idUser=userProfileObj, Pictures_idUserProfile=picturesObj.idUserProfile, City_idUser=cityObj.idUser) userObj.save() user = User(userObj.idUser, userObj.nameUser, userObj.mailUser, userProfileObj.ageUserProfile, userProfileObj.genderUserProfile, CityResponse(cityObj.default, cityObj.current), Photos(photo1, photo2, photo3)) loginResponse = LoginResponse(token_push, user) return JsonResponse(loginResponse.getDict())
def reg_new(request): exist = User.objects.filter(username=request.POST['username']) if (request.POST['password']==request.POST['confirm_password']) and not exist.exists(): print request.POST username=request.POST['username'] password=request.POST['password'] mail =request.POST['mail'] description=request.POST['description'] u=User.objects.create_user(username,mail,password) fill=80-len(description) if fill==80: usr_desc=UserProfile(user=u) else: for x in range(0,fill): description+="=" usr_desc=UserProfile(user=u,description=description) usr_desc.save() loginAuth(request) else: print "user already exists"
def reg_new(request): exist = User.objects.filter(username=request.POST['username']) if (request.POST['password'] == request.POST['confirm_password']) and not exist.exists(): print request.POST username = request.POST['username'] password = request.POST['password'] mail = request.POST['mail'] description = request.POST['description'] u = User.objects.create_user(username, mail, password) fill = 80 - len(description) if fill == 80: usr_desc = UserProfile(user=u) else: for x in range(0, fill): description += "=" usr_desc = UserProfile(user=u, description=description) usr_desc.save() loginAuth(request) else: print "user already exists"
def userRegister(request): try: if request.method=='POST': username=request.POST['name'] password1=request.POST['password1'] password2=request.POST['password2'] email=request.POST['email'] phone=request.POST['phone'] errors=[] filterResult=User.objects.filter(username=username) if len(filterResult)>0: errors.append("用户名已存在") return render(request,'zhuce.html',{'errors':errors}) if len(password1) < 6: errors.append("请输入大于6位数密码") return render(request,'zhuce.html',{'errors':errors}) if password1!=password2: errors.append("两次输入的密码不一致!") return render(request,'zhuce.html',{'errors':errors}) if len(email) < 9: errors.append("请输入有效邮箱") return render(request,'zhuce.html',{'errors':errors}) user=User() user.username=username user.set_password(password1) user.email=email user.save() profile=UserProfile() profile.user_id=user.id profile.phone=phone profile.save() newUser=authenticate(username=username,password=password1) if newUser is not None: login(request, newUser) return redirect("http://127.0.0.1:8000/list/") except Exception as e: errors.append(str(e)) return render(request,'zhuce.html',{'errors':errors}) return render(request,'zhuce.html')
def login_view(request): elem = { 'title': 'Login', } #inloggade användare behöver inte se login view if request.user.is_authenticated(): return HttpResponseRedirect('/home/') if request.method == 'POST': loginform = LoginForm(request.POST) loginAuth(request) if loginform.is_valid(): if request.user.is_authenticated(): #endast för admin, som saknar user profile från början, underlättar testning up = UserProfile.objects.filter(user=request.user) if not up.exists(): new_profile = UserProfile(user=request.user, description=16 * "admin") new_profile.save() return HttpResponseRedirect('/home/') else: return HttpResponseRedirect('') loginform = LoginForm() elem.update({ 'error': 'inloggning misslyckades', 'login_form': loginform }) print "aha" return render_to_response("login.html", elem, context_instance=RequestContext(request)) else: loginform = LoginForm() elem.update({'login_form': loginform}) return render_to_response("login.html", elem, context_instance=RequestContext(request))
def myRegister(request): print(request.POST) if request.POST: username = request.POST.get('RegisterUserName', None) password = request.POST.get('RegisterPassWord', None) phone = request.POST.get('RegisterPhone', None) user = User.objects.filter(username=username) print(user) if len(user) > 0: info = { "status": False, 'msg':'登录用户名不能重复!' } print('创建失败') return HttpResponse(json.dumps(info,ensure_ascii=False), content_type='application/json') user = User.objects.create_user(username=username, password=password) profile = UserProfile() profile.user_id = user.id profile.phone = phone profile.save() print('创建成功') login(request, user) info = { "status": True, 'username':username, } return HttpResponse(json.dumps(info,ensure_ascii=False), content_type='application/json')
def manage_register(request, sort_by_date=0, sort_by_status=0): if not request.user.is_superuser: return HttpResponseRedirect(reverse('school_index')) if request.method == 'POST': if request.is_ajax(): request_type = request.POST['request_type'] if request_type == 'del': ids = request.POST['data'].split('-') try: for id in ids: if id: reg = Register.objects.get(id=int(id)) if reg.status == 'CHUA_CAP': if reg.register_phone: sms_msg = 'Dang ki truong %s tai truongnha.com khong duoc chap nhan!' % (to_en1(unicode(reg.school_name))) try: sendSMS(reg.register_phone, sms_msg, request.user) except Exception: pass send_email(u'Từ chối đăng kí tại Trường Nhà', u'Cảm ơn bạn đã đăng ký để sử dụng dịch ' + u'vụ Trường Nhà.\nSau khi xác minh lại thông tin mà bạn cung cấp, ' + u'chúng tôi từ chối cung cấp dịch vụ cho Trường ' + unicode(reg.school_name) + u'.\n Vui lòng liên hệ với Ban Quản Trị để biết thêm chi tiết.', to_addr=[reg.register_email]) reg.delete() message = u'Xóa thành công' success = True data = simplejson.dumps({ 'message': message, 'success': success }) return HttpResponse(data, mimetype='json') except Exception as e: print e message = u'Không thể xóa đăng ký' success = False data = simplejson.dumps({ 'message': message, 'success': success }) return HttpResponse(data, mimetype='json') elif request_type == 'create_acc': ids = request.POST['data'].split('-') try: account_info = '' for id in ids: if id: reg = Register.objects.get(id=int(id)) if reg.status == 'CHUA_CAP': org_name = reg.school_name org_level = 'T' org_school_level = reg.school_level org_status = 0 org_manager_name = reg.register_name org_address = reg.school_address phone = reg.register_phone email = reg.register_email school = Organization.objects.create( name= org_name, level= org_level, school_level= org_school_level, status= org_status, manager_name= org_manager_name, address= org_address, phone= phone, email= email) user = User() user.username = make_username( full_name=org_manager_name) user.password, raw_password = make_default_password() if reg.register_name: temp = reg.register_name.split(' ') user.first_name = temp[-1] user.last_name = ' '.join(temp[:-1]) user.save() userprofile = UserProfile() userprofile.user = user userprofile.organization = school userprofile.position = 'HIEU_TRUONG' userprofile.save() reg.status = 'DA_CAP' reg.default_user_name = user.username reg.default_password = raw_password reg.save() #notify users about their account via email if school.phone: sms_msg = 'Tai khoan truongnha.com:\n\ Ten dang nhap:%s\nMat khau:%s\n\ Cam on ban da su dung dich vu!'\ % (unicode(user.username), unicode(raw_password)) try: sendSMS(school.phone, sms_msg, request.user) except Exception: pass send_email(u'Tài khoản Trường Nhà', u'Cảm ơn bạn đã đăng ký để sử dụng dịch vụ Trường Nhà.\nTài khoản của bạn như sau:\n'+ u'Tên đăng nhập:' + unicode(user.username) + u'\n' + u'Mật khẩu:' + unicode(raw_password), to_addr=[reg.register_email]) account_info += str(id) + '-' + user.username + '-' + raw_password + ',' else: if reg.register_phone: sms_msg = 'Tai khoan truongnha.com:\nTen dang nhap:%s\nMat khau:%s\nCam on ban da su dung dich vu!' % (unicode(reg.default_user_name), unicode(reg.default_password)) try: sendSMS(reg.register_phone, sms_msg, request.user) except Exception: pass send_email(u'Tài khoản Trường Nhà', u'Cảm ơn bạn đã đăng ký để sử dụng dịch' + u'vụ Trường Nhà.\nTài khoản của bạn như' + u'sau:\n'+ u'Tên đăng nhập:' + unicode(reg.default_user_name) + u'\n' + u'Mật khẩu:' + unicode(reg.default_password), to_addr=[reg.register_email]) account_info += str(id) + '-' + reg.default_user_name + '-' + reg.default_password + ',' message = u'Tạo tài khoản thành công' success = True data = simplejson.dumps({ 'message': message, 'account_info': account_info, 'success': success }) return HttpResponse(data, mimetype='json') except Exception as e: print e message = u'Tạo tài khoản không thành công' success = False data = simplejson.dumps({ 'message': message, 'success': success }) return HttpResponse(data, mimetype='json') elif request.POST[u'request_type'] == u'send_email': try: content = request.POST[u'content'].strip() register_list = request.POST[u'register_list'] register_list = register_list.split("-") sts = [] for register in register_list: if register: sts.append(int(register)) registers = Register.objects.filter(id__in=sts) for reg in registers: if reg.register_phone: sms_msg = to_en1(unicode(content)) try: sendSMS(reg.register_phone, sms_msg, request.user) except Exception: pass send_email(u'Thông báo từ Trường Nhà', unicode(content), to_addr=[reg.register_email]) data = simplejson.dumps({ 'success': True, 'message': u'Gửi thông báo thành công.', }) return HttpResponse(data, mimetype='json') except Exception as e: print e data = simplejson.dumps({ 'success': False, 'message': u'Có lỗi khi gửi thông báo.', }) return HttpResponse(data, mimetype='json') else: raise Exception("BadRequest") if sort_by_date: sort_by_date = '-' else: sort_by_date = '' if sort_by_status: sort_by_status = '-' else: sort_by_status = '' registers = Register.objects.order_by(sort_by_date+'register_date', sort_by_status+'status') if sort_by_date == '-': sort_by_date = 0 else: sort_by_date = 1 if sort_by_status == '-': sort_by_status = 0 else: sort_by_status = 1 context = RequestContext(request) return render_to_response(MANAGE_REGISTER, { 'registers': registers, 'short_by_date': sort_by_date, 'short_by_status': sort_by_status }, context_instance=context)
def userprofiles(): # Get the access token from the header auth_header = request.headers.get('Authorization') print("Auth header is ",auth_header) access_token = auth_header.split(" ")[1] if access_token: # Attempt to decode the token and get the User ID user_id = User.decode_token(access_token) print("user id is ",user_id) if not isinstance(user_id, str): # Go ahead and handle the request, the user is authenticated if request.method == "POST": content=request.json print("Content received = ",content) first_name = str(content['first_name']) last_name = str(content['last_name']) gender = str(content['gender']) category = str(content['category']) area = str(content['area']) contact = str(content['contact']) lat = str(content['coord']['lat']) lon = str(content['coord']['lon']) if first_name: print("First name = ",first_name) userprofile = UserProfile(first_name=first_name, last_name=last_name, gender=gender, category=category, area=area, contact=contact, lat=lat, lon=lon, created_by=user_id) print("saving in db") userprofile.save() print("Saved") response = jsonify({ 'id': userprofile.id, 'first_name': userprofile.first_name, 'date_created': userprofile.date_created, 'date_modified': userprofile.date_modified, 'created_by': user_id }) return make_response(response), 201 else: # GET all the bucketlists created by this user userprofiles = UserProfile.query.filter_by(created_by=user_id) results = [] for userprofile in userprofiles: obj = { 'id': userprofile.id, 'first_name': userprofile.first_name, 'last_name': userprofile.last_name, 'gender': userprofile.gender, 'category': userprofile.category, 'area': userprofile.area, 'contact': userprofile.contact, 'lat': userprofile.lat, 'lon': userprofile.lon, 'date_created': userprofile.date_created, 'date_modified': userprofile.date_modified, 'created_by': userprofile.created_by } results.append(obj) return make_response(jsonify(results)), 200 else: # user is not legit, so the payload is an error message message = user_id response = { 'message': message } return make_response(jsonify(response)), 401
def add_student(student=None, index=0, start_year=None, year=None, _class=None, term=None, school=None, school_join_date=None): if not ( student and start_year and term and school ): raise Exception("Phải có giá trị cho các trường: Student,Start_Year,Term,School.") if 'fullname' in student: first_name, last_name = extract_fullname(student['fullname']) else: last_name = normalize(student['last_name']) first_name = normalize(student['first_name']) if not school_join_date: school_join_date = root_dt.date.today() birthday = student['birthday'] if 'uu_tien' in student: uu_tien = student['uu_tien'] else: uu_tien = '' if 'ban_dk' in student: ban = student['ban_dk'] else: ban = None find = start_year.pupil_set.filter(first_name__exact=first_name)\ .filter(last_name__exact=last_name)\ .filter(birthday__exact=birthday) # count primary subjects print find, 'find' number_subject = 0 if _class: number_subject = _class.subject_set.filter(primary=True).count() if find: # the student exists: transaction.commit() return False, find[0] else: # the student does not exist try: st = Pupil() st.first_name = first_name st.last_name = last_name st.birthday = birthday st.ban_dk = ban st.school_join_date = school_join_date st.start_year_id = start_year st.class_id = _class st.index = index st.school_id = school st.uu_tien = uu_tien if 'dan_toc' in student: st.dan_toc = student['dan_toc'] if 'birth_place' in student: st.birth_place = student['birth_place'] if 'current_address' in student: st.current_address = student['current_address'] if 'father_name' in student: st.father_name = student['father_name'] if 'father_phone' in student: st.father_phone = student['father_phone'] if 'mother_name' in student: st.mother_name = student['mother_name'] if 'mother_phone' in student: st.mother_phone = student['mother_phone'] if 'phone' in student: st.phone = student['phone'] if 'sms_phone' in student: st.sms_phone = student['sms_phone'] if 'sex' in student: st.sex = student['sex'] else: st.sex = 'Nam' user = User() user.username = make_username(first_name=first_name, last_name=last_name, start_year=start_year) user.password, raw_password = make_default_password() user.first_name = st.first_name user.last_name = st.last_name user.is_active = False user.save() userprofile = UserProfile() userprofile.user = user userprofile.organization = school userprofile.position = 'HOC_SINH' userprofile.save() st.user_id = user st.save() st.join_class(_class) _class.max += 1 _class.save() for i in range(1, 3): term1 = year.term_set.get(number__exact=i) tb_hoc_ky = TBHocKy() tb_hoc_ky.student_id = st tb_hoc_ky.number_subject = number_subject tb_hoc_ky.term_id = term1 tb_hoc_ky.save() tk_diem_danh = TKDiemDanh() tk_diem_danh.student_id = st tk_diem_danh.term_id = term1 tk_diem_danh.save() tb_nam = TBNam() tb_nam.student_id = st tb_nam.number_subject = number_subject tb_nam.year_id = year tb_nam.save() if _class: subjects = _class.subject_set.all() for i in range(1, 3): term1 = year.term_set.get(number__exact=i) for subject in subjects: the_mark = Mark() the_mark.student_id = st the_mark.subject_id = subject the_mark.term_id = term1 the_mark.save() for subject in subjects: tkmon = TKMon(student_id=st, subject_id=subject) tkmon.save() transaction.commit() return True, st except Exception as e: print e
def add_many_students( student_list=None, start_year=None, year=None, _class=None, term=None, school=None, school_join_date=None, force_update=False): if not (start_year and term and school and _class ): raise Exception("Start_Year,Term,School CanNotBeNull") index = _class.max existing_student = [] number_of_change = 0 unc_st_found = False for student in student_list: print student index += 1 if 'fullname' in student: first_name, last_name = extract_fullname(student['fullname']) else: last_name = normalize(student['last_name']) first_name = normalize(student['first_name']) if not school_join_date: school_join_date = root_dt.date.today() birthday = student['birthday'] ban = student['ban_dk'] print start_year find = start_year.pupil_set.filter(first_name__exact=first_name, last_name__exact=last_name, birthday__exact=birthday) cr_bl_found = False bl = _class.block_id unc_set = bl.uncategorizedclass_set.filter(year_id=year) for unc in unc_set: unc_st = unc.pupil_set.filter(first_name__exact=first_name)\ .filter(last_name__exact=last_name)\ .filter(birthday__exact=birthday) if unc_st: st = unc_st[0] unc_st_found = True cr_bl_found = True break if not cr_bl_found: try: bl = school.block_set.get(number=bl.number - 1) unc_set = bl.uncategorizedclass_set.filter(year_id=year) for unc in unc_set: unc_st = unc.pupil_set.filter(first_name__exact=first_name)\ .filter(last_name__exact=last_name)\ .filter(birthday__exact=birthday) if unc_st: st = unc_st[0] unc_st_found = True break except ObjectDoesNotExist: pass # count primary subjects if find or unc_st_found: # the student exists: if force_update: st = find[0] elif not unc_st_found: st = find[0] student['class_id'] = st.current_class().id existing_student.append(student) continue else: # the student does not exist st = Pupil(first_name=first_name, last_name=last_name, birthday=birthday, ban_dk=ban, school_join_date=school_join_date, start_year_id=start_year, class_id=_class, index=index, school_id=school) changed = False if 'sex' in student: if st.sex != student['sex']: st.sex = student['sex'] changed = True else: if st.sex != 'Nam': st.sex = 'Nam' changed = True if 'ban_dk' in student and st.ban_dk != student['ban_dk']: st.ban_dk = student['ban_dk'] changed = True if 'dan_toc' in student and st.dan_toc != student['dan_toc']: st.dan_toc = student['dan_toc'] changed = True if 'birth_place' in student and st.birth_place != student['birth_place']: st.birth_place = student['birth_place'] changed = True if 'current_address' in student and st.current_address != student['current_address']: st.current_address = student['current_address'] changed = True if 'father_name' in student and st.father_name != student['father_name']: st.father_name = student['father_name'] changed = True if 'father_phone' in student and st.father_phone != student['father_phone']: st.father_phone = student['father_phone'] changed = True if 'mother_name' in student and st.mother_name != student['mother_name']: st.mother_name = student['mother_name'] changed = True if 'mother_phone' in student and st.mother_phone != student['mother_phone']: st.mother_phone = student['mother_phone'] changed = True if 'sms_phone' in student and st.sms_phone != student['sms_phone']: st.sms_phone = student['sms_phone'] changed = True if force_update and st.current_class() != _class: move_student(school, st, _class) changed = True if not force_update and not unc_st_found: user = User() user.username = make_username(first_name=first_name, last_name=last_name, start_year=start_year) user.password, raw_password = make_default_password() user.first_name = st.first_name user.last_name = st.last_name user.is_active = False user.save() userprofile = UserProfile() userprofile.user = user userprofile.organization = school userprofile.position = 'HOC_SINH' userprofile.save() st.user_id = user if force_update and changed: st.save() number_of_change += 1 elif not force_update: st.save() if st.unc_class_id: st.move_to_new_class(_class) else: st.join_class(_class) if not force_update: for i in range(1, 3): term1 = year.term_set.get(number__exact=i) number_subject = 0 if _class: number_subject += _class.subject_set.filter(primary=0).count() number_subject += _class.subject_set.filter(primary=3).count() if i == 1: number_subject += _class.subject_set.filter(primary=1).count() if i == 2: number_subject += _class.subject_set.filter(primary=2).count() tbhk, created = TBHocKy.objects.get_or_create(student_id=st, term_id=term1) tbhk.number_subject = number_subject tbhk.save() TKDiemDanh.objects.get_or_create(student_id=st, term_id=term1) number_subject = 0 if _class: number_subject += _class.subject_set.filter(primary=0).count() tbnam, created = TBNam.objects.get_or_create(student_id=st, year_id=year) if created: tbnam.number_subject = number_subject tbnam.save() if _class: subjects = _class.subject_set.all() for i in range(1, 3): term1 = year.term_set.get(number__exact=i) for subject in subjects: Mark.objects.get_or_create(student_id=st, subject_id=subject, term_id=term1) for subject in subjects: TKMon.objects.get_or_create(student_id=st, subject_id=subject) _class.max = index _class.save() #transaction.commit() if force_update: return number_of_change return existing_student
def add_teacher(first_name=None, last_name=None, full_name=None, birthday=None, sms_phone='', sex='N', dan_toc='Kinh', major='', current_address='', home_town='', birthplace='', school=None, team_id=None, group_id=None, email='', force_update=False): if full_name: first_name, last_name = extract_fullname(full_name) else: first_name = normalize(first_name) last_name = normalize(last_name) if team_id: if (type(team_id) == str or type(team_id) == unicode) and team_id.strip(): name = team_id.strip() try: team_id = school.team_set.get(name=name) except Exception as e: print e team_id = Team() team_id.name = name team_id.school_id = school team_id.save() elif not isinstance(team_id, Team): team_id = None else: team_id = None if team_id: if group_id: if (type(group_id) == str or type(group_id) == unicode) and group_id.strip(): name = group_id try: group_id = team_id.group_set.get(name=name) except Exception as e: print e group_id = Group() group_id.name = name group_id.team_id = team_id group_id.save() elif isinstance(group_id, Group): if group_id.team_id != team_id: raise Exception("GroupNotBelongToTeam") else: group_id = None else: group_id = None else: group_id = None if major.strip(): if to_en(major) not in SUBJECT_LIST_ASCII: try: major = to_subject_name(major) except Exception: major = '' teacher = Teacher() teacher.first_name = first_name teacher.last_name = last_name teacher.school_id = school teacher.birthday = birthday find = school.teacher_set.filter(first_name__exact=first_name, last_name__exact=last_name, birthday__exact=birthday) if find: if force_update: teacher = find[0] else: return find teacher.sms_phone = sms_phone teacher.email = email teacher.home_town = home_town teacher.sex = sex teacher.dan_toc = dan_toc teacher.current_address = current_address teacher.birth_place = birthplace teacher.team_id = team_id teacher.group_id = group_id teacher.major = major if not force_update: user = User() user.username = make_username(first_name=first_name, last_name=last_name) user.password, raw_password = make_default_password() user.is_active = False user.first_name = teacher.first_name user.last_name = teacher.last_name user.save() userprofile = UserProfile() userprofile.user = user userprofile.organization = school userprofile.position = 'GIAO_VIEN' userprofile.save() teacher.user_id = user teacher.save() return teacher
def manage_register(request, sort_by_date=0, sort_by_status=0): try: if not request.user.is_superuser: return HttpResponseRedirect(reverse('school_index')) if request.method == 'POST': if request.is_ajax(): request_type = request.POST['request_type'] if request_type == 'del': ids = request.POST['data'].split('-') print ids try: for id in ids: if id: register = Register.objects.get(id=int(id)) register.delete() message = u'Xóa thành công' success = True data = simplejson.dumps({ 'message': message, 'success': success }) return HttpResponse(data, mimetype='json') except Exception as e: print e message = u'Không thể xóa đăng ký' success = False data = simplejson.dumps({ 'message': message, 'success': success }) return HttpResponse(data, mimetype='json') elif request_type == 'create_acc': ids = request.POST['data'].split('-') print ids try: account_info = '' for id in ids: if id: register = Register.objects.get(id=int(id)) org_name = register.school_name org_level = 'T' org_school_level = register.school_level org_status = 0 org_manager_name = register.register_name org_address = register.school_address phone = register.register_phone email = register.register_email school = Organization.objects.create( name=org_name, level=org_level, school_level=org_school_level, status=org_status, manager_name=org_manager_name, address=org_address, phone=phone, email=email) user = User() user.username = make_username( full_name=org_manager_name) user.password = make_default_password( user.username) user.save() userprofile = UserProfile() userprofile.user = user userprofile.organization = school userprofile.position = 'HIEU_TRUONG' userprofile.save() register.status = 'DA_CAP' register.default_user_name = user.username register.default_password = user.password register.save() #TODO send an email about account information to customers. account_info += str( id) + '-' + user.username + ',' message = u'Tạo tài khoản thành công' success = True data = simplejson.dumps({ 'message': message, 'account_info': account_info, 'success': success }) print data return HttpResponse(data, mimetype='json') except Exception as e: print e message = u'Tạo tài khoản không thành công' success = False data = simplejson.dumps({ 'message': message, 'success': success }) return HttpResponse(data, mimetype='json') else: raise Exception("BadRequest") if sort_by_date: sort_by_date = '-' else: sort_by_date = '' if sort_by_status: sort_by_status = '-' else: sort_by_status = '' registers = Register.objects.order_by(sort_by_date + 'register_date', sort_by_status + 'status') if sort_by_date == '-': sort_by_date = 0 else: sort_by_date = 1 if sort_by_status == '-': sort_by_status = 0 else: sort_by_status = 1 context = RequestContext(request) return render_to_response(MANAGE_REGISTER, { 'registers': registers, 'short_by_date': sort_by_date, 'short_by_status': sort_by_status }, context_instance=context) except Exception as e: print e raise e
def manage_register(request, sort_by_date=0, sort_by_status=0): try: if not request.user.is_superuser: return HttpResponseRedirect( reverse('school_index')) if request.method == 'POST': if request.is_ajax(): request_type = request.POST['request_type'] if request_type == 'del': ids = request.POST['data'].split('-') print ids try: for id in ids: if id: register = Register.objects.get(id= int(id)) register.delete() message = u'Xóa thành công' success = True data = simplejson.dumps({ 'message': message, 'success': success }) return HttpResponse(data, mimetype='json') except Exception as e: print e message = u'Không thể xóa đăng ký' success = False data = simplejson.dumps({ 'message': message, 'success': success }) return HttpResponse(data, mimetype='json') elif request_type == 'create_acc': ids = request.POST['data'].split('-') print ids try: account_info = '' for id in ids: if id: register = Register.objects.get(id= int(id)) org_name = register.school_name org_level = 'T' org_school_level = register.school_level org_status = 0 org_manager_name = register.register_name org_address = register.school_address phone = register.register_phone email = register.register_email school = Organization.objects.create( name= org_name, level= org_level, school_level= org_school_level, status= org_status, manager_name= org_manager_name, address= org_address, phone= phone, email= email ) user = User() user.username = make_username( full_name=org_manager_name) user.password = make_default_password( user.username ) user.save() userprofile = UserProfile() userprofile.user = user userprofile.organization = school userprofile.position = 'HIEU_TRUONG' userprofile.save() register.status = 'DA_CAP' register.default_user_name = user.username register.default_password = user.password register.save() #TODO send an email about account information to customers. account_info += str(id) + '-' + user.username + ',' message = u'Tạo tài khoản thành công' success = True data = simplejson.dumps({ 'message': message, 'account_info': account_info, 'success': success }) print data return HttpResponse(data, mimetype='json') except Exception as e: print e message = u'Tạo tài khoản không thành công' success = False data = simplejson.dumps({ 'message': message, 'success': success }) return HttpResponse(data, mimetype='json') else: raise Exception("BadRequest") if sort_by_date: sort_by_date = '-' else: sort_by_date = '' if sort_by_status: sort_by_status = '-' else: sort_by_status = '' registers = Register.objects.order_by(sort_by_date+'register_date', sort_by_status+'status') if sort_by_date == '-': sort_by_date = 0 else: sort_by_date = 1 if sort_by_status == '-': sort_by_status = 0 else: sort_by_status = 1 context = RequestContext(request) return render_to_response(MANAGE_REGISTER, { 'registers': registers, 'short_by_date': sort_by_date, 'short_by_status': sort_by_status }, context_instance = context) except Exception as e: print e raise e
def create_user_profile(): user_profile = UserProfile( first_name=get_word(), last_name=get_word()) user_profile.save() return user_profile