Esempio n. 1
0
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
    })
Esempio n. 2
0
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})
Esempio n. 3
0
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
Esempio n. 4
0
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
Esempio n. 5
0
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
Esempio n. 6
0
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
Esempio n. 7
0
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
Esempio n. 8
0
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)
Esempio n. 9
0
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