Example #1
0
    def post(self, request, *args, **kwargs):
        action = request.query_params.get('action')
        if action == 'register':
            staff_name = request.data.get('staff_name')
            password = request.data.get('password')
            email = request.data.get('email')
            department = request.data.get('department')
            dp = Department.objects.get(pk=department)
            is_leader = request.data.get('is_leader')
            staff = Staff()
            staff.staff_name = staff_name
            staff.password = password
            staff.email = email
            staff.department = dp
            if is_leader:
                staff.is_leader = is_leader
            staff.save()

            data = {
                'status': 200,
                'msg': 'create staff success',
                'staff': {
                    'id': staff.id,
                    'staff_name': staff.staff_name,
                    'email': staff.email,
                    'department': staff.department.dp_name,
                    'is_leader': staff.is_leader,
                    'is_delete': staff.is_delete
                }
            }
            return Response(data)
        elif action == 'login':
            return self.login(request, *args, **kwargs)
        else:
            raise ValidationError(detail='请提供正确的请求动作')
Example #2
0
def add_staff(request):
    # 添加完成后跳到最后一页
    staff_num = Staff.objects.all().count()
    per_page = 5
    if staff_num % per_page == 0:
        max_page = math.ceil(staff_num / per_page) + 1
    else:
        max_page = math.ceil(staff_num / per_page)

    if request.method == "GET":
        # 点击返回回到之前所在页面
        page = request.GET.get('page', 1)
        context = {'page': page}
        return render(request, 'add_staff.html', context=context)
    else:
        name = request.POST.get('name')
        age = request.POST.get('age')
        gender = request.POST.get('gender')

        # 信息缺失 无法添加
        if (not name) or (not age) or (not gender):
            context = {'error': 0}
            return render(request, 'add_staff.html', context=context)
        if age.isdigit() and 1 <= int(age) <= 100:
            age = int(age)
        else:
            context = {'error': 1}
            return render(request, 'add_staff.html', context=context)

        staff = Staff(name=name, age=age, gender=gender)
        staff.save()

        return redirect(f'/staff/staffList?page={max_page}')
Example #3
0
def staff_register(request):

    if request.method == 'POST':
        username = request.POST.get('username', None)
        password = request.POST.get('password', None)
        repeatpassword = request.POST.get('repeatpassword', None)
        firstname = request.POST.get('firstname', None)
        lastname = request.POST.get('lastname', None)
        sex = request.POST.get('sex', None)
        phone = request.POST.get('phone', None)
        email = request.POST.get('email', None)
        if password == '' or repeatpassword == '':
            return HttpResponse('empty password')
        elif password != repeatpassword:
            return HttpResponse('repeat error')
        elif User.objects.filter(username=username):
            return HttpResponse('user exist')
        else:
            new_user = User.objects.create_user(username=username,
                                                password=password)
            new_user.save()
            new_staff = Staff(account=new_user,
                              firstname=firstname,
                              lastname=lastname,
                              sex=sex,
                              phone=phone,
                              email=email)
            new_staff.save()
            return HttpResponseRedirect('/staff/login')

    return render_to_response('staff/staffregister.html')
Example #4
0
def institute_staff_create(request):
    if request.method == 'POST':
        user_form = StaffCreateForm(request.POST)

        current_institute = Institutions.objects.get(user__username = request.user)
        license_institute = License.objects.get(li_institute = current_institute)

        is_allowed =   int(license_institute.li_current_staff) < int(license_institute.li_max_staff)

        if is_allowed and user_form.is_valid():
            user = user_form.save()
            user.refresh_from_db()  # This will load the Profile created by the Signal
            assign_perm('staff.is_staff', user)
            profile_form = Staff()  # Reload the profile form with the profile instance

            profile_form.institute = request.user.institutions
            profile_form.staffuser = user
            profile_form.full_clean()  # Manually clean the form this time. It is implicitly called by "is_valid()" method

            license_institute.li_current_staff += 1
            license_institute.save()
            profile_form.save()  # Gracefully save the form
            messages.add_message(request, messages.SUCCESS, 'Staff Profile Added Successfully')
        else:
            messages.add_message(request, messages.INFO, str(user_form.errors.as_ul()))
    else:
        user_form = StaffCreateForm()
        # profile_form = StaffProfileForm()
    return render(request, 'institutions/staff_create.html', {
        'user_form': user_form

    })
Example #5
0
def register_staff(request):
    context = {
        'page': 'register_staff',
    }
    if request.session.get('is_login', None):
        username = request.session.get('username')
        store = request.session.get('storeid')
        context['username'] = username
        if request.session.get('identity') != 'shopkeeper':
            context['errmsg'] = '请以店主账号登录'
            shopkeeper = False
            return render(request,
                          'staff/register_staff.html',
                          context=context)
        else:
            shopkeeper = True
    else:
        return login(request)

    if request.method == "POST" and shopkeeper:
        username = request.POST.get('username')
        name = request.POST.get('name')
        password = request.POST.get('password')
        phonenumber = request.POST.get("phonenumber")
        desc = request.POST.get("desc")
        user_model = Staff.objects.filter(username=username).filter(
            store_id=store)

        # 参数验证
        if not all([username, name, password, phonenumber, desc]):
            # 参数不完整
            context['errmsg'] = '数据不完整'
            return render(request,
                          'staff/register_staff.html',
                          context=context)

        if user_model:  #不为NULL
            context['errmsg'] = '用户名已存在'
            return render(request,
                          'staff/register_staff.html',
                          context=context)
        else:
            user = Staff()
            user.username = username
            user.name = name
            user.password = password
            user.phonenumber = phonenumber
            user.desc = desc
            user.store_id = store
            user.save()
            return redirect(reverse('staff:find_staff'))
    return render(request, 'staff/register_staff.html', context=context)
Example #6
0
    def form_valid(self, form):
        user_obj = form.save()
        assign_perm('institutions.is_institute', user_obj)
        user_obj.save()
        institution_obj = Institutions()

        institution_obj.user = user_obj
        institution_obj.institute_name = self.request.POST['institute_name']
        institution_obj.institute_address = self.request.POST[
            'institute_address']
        institution_obj.institute_city = self.request.POST['institute_city']
        institution_obj.institute_state = self.request.POST['institute_state']
        institution_obj.institute_country = self.request.POST[
            'institute_country']
        institution_obj.institute_contact_mobile = self.request.POST[
            'institute_contact_mobile']
        institution_obj.institute_contact_landline = self.request.POST[
            'institute_contact_landline']

        license_obj = License()
        institution_obj.save()

        license_obj.li_institute = institution_obj
        license_obj.li_key = ''.join(
            random.choices(string.ascii_uppercase + string.digits, k=16))
        license_obj.li_expiration_date = datetime.now() + timedelta(days=10 *
                                                                    365)
        license_obj.li_max_staff = 50
        license_obj.li_max_students = 500
        license_obj.li_max_assesments = 1000
        license_obj.li_current_status = 'acti'

        license_obj.save()

        #Register Institute as first user:

        user_obj.refresh_from_db(
        )  # This will load the Profile created by the Signal
        assign_perm('staff.is_staff', user_obj)
        profile_form = Staff(
        )  # Reload the profile form with the profile instance
        profile_form.institute = user_obj.institutions
        profile_form.staffuser = user_obj
        profile_form.full_clean(
        )  # Manually clean the form this time. It is implicitly called by "is_valid()" method
        license_obj.li_current_staff += 1
        license_obj.save()
        profile_form.save()  # Gracefully save the form

        messages.add_message(self.request, messages.SUCCESS,
                             'Your Account Registered Successfully')
        return HttpResponseRedirect(self.get_success_url())
def register(request, *args, **kwargs):
    if (request.user.is_admin) | (request.user.is_staff):
        form = UserCreationForm(request.POST or None)
        if form.is_valid():
            form.save()
            obj = UserProfile.objects.latest('id')
            if (form.cleaned_data.get('is_doctor') == True):
                doct = doctor(user=obj)
                doct.save()
            if request.POST.get('is_staff'):
                l = Staff(user=obj)
                l.save(obj)

            elif request.POST.get('is_medical'):
                l = medical(user=obj)
                l.save(obj)
            elif request.POST.get('is_lab'):
                l = lab(user=obj)
                l.save(obj)
            elif request.POST.get('is_admin'):
                l = superadmin(user=obj)
                l.save(obj)
            # else:
            #     pass
            # print(who)
            # print(obj)

            print("user Creted0")
            messages.success(request, 'User Register successfully!')
            return redirect("login")
        return render(request, 'register.html', {'form': form})
    else:
        form = UserLoginForm(request.POST or None)
        context = {"form": form}
        return render(request, 'login.html', context)
Example #8
0
def create_staff(staff_info: dict):
    """

    :param staff_info: {
        "shop_id": 1,
        "user_id": 1,
        "roles": 255,
        "permissions": 63,
        "position": "",
        "entry_date": "2019-10-14",
        "remark": ""
    }
    :return:
    """
    staff = Staff(**staff_info)
    staff.save()
    return staff
Example #9
0
File: views.py Project: josben/flo
def loadStaff(staff, employee):
#    cargo = createPosition(staff['cargo'])
#    unit = createWorkUnit(staff['unidad'])
    type_document = TypeDocument.objects.get(key='ci')
    try:
        s = Staff(photo=staff['avatar'], first_name=staff['first_name'], last_name=staff['last_name'],
            birth_date=staff['birth_date'], type_document=type_document, val_document=staff['ci'],
            locale_issue=staff['locale_issue'], date_joined=datetime.datetime.now(), is_active=True)
        s.save()
    except IntegrityError:
        print 'ERROR GARRAFAL EN USUARIO CON CI: ' + str(staff['ci']) + ' E ITEM: ' + str(employee['item'])

    try:
        e = Employee(staff=s, item=employee['item'])
        e.save()
    except IntegrityError:
        print 'ERROR AL CARGAR EL ITEM: ' + employee['item']
Example #10
0
def create_super_admin_staff(shop: Shop, user: User):
    """
    创建一个超级管理员
    :param shop:
    :param super_amdin:
    :return:
    """
    # 计算所有权限,超级管理员拥有所有权限
    permissions = 0
    for k, v in vars(StaffPermission).items():
        if not k.startswith("__"):
            permissions |= v

    staff = Staff(shop=shop,
                  user=user,
                  roles=StaffRole.SHOP_SUPER_ADMIN,
                  permissions=permissions)
    staff.save()
    return staff
Example #11
0
def add_staff(request, excel_file):
    COLUMN_LIMIT = 4
    sheet_name = "staff"
    staff = _get_data_from_sheet(request, excel_file, COLUMN_LIMIT, sheet_name)
    if not staff: return False

    # DATA HEAD FROM SHEET:
    # No	staff_id	name	sms_number

    # Add teacher to the database
    for row in staff:
        if (len(row) > 0):
            if (row[0] != "No"):
                # if there are empty colums
                if (len(row) < COLUMN_LIMIT):
                    i = len(row)
                    while (i < COLUMN_LIMIT):
                        # fill with ""
                        row.append("")
                        i += 1
                try:
                    # Check for the exitence of the staff id
                    t = Staff.objects.filter(staff_id=row[1])
                    if (t.count() == 0):
                        new_row = Staff(
                            staff_id=row[1],
                            name=row[2],
                            sms_number=row[3],
                        )
                        new_row.save()
                except ValueError as err:
                    request.session["error_message"] = str(err)
                    return False
                except IntegrityError as err:
                    request.session["error_message"] = str(err)
                    return False
                except FieldError as err:
                    request.session["error_message"] = str(err)
                    return False
                except Exception as err:
                    request.session["error_message"] = str(err)
                    return False
    return True
Example #12
0
def new_staff(req):
	from staff.models import Staff

	if req.method == 'POST':
		posted = req.POST

		staff = Staff()

		staff.groupschedule = req.user.groupschedule
		staff.name = posted['name']

		staff.save()

		return redirect('/')

	temp = 'staff/new_staff.html'
	contxt = {}

	return render(req,temp,contxt)
Example #13
0
def add(request):
    if request.POST:
        area_id = int(request.POST.get('area_id'))
        realname = request.POST.get('realname')
        accountname = request.POST.get('accountname')
        is_available_list = request.POST.getlist('is_available')
        phone = request.POST.get('phone')
        weight = int(request.POST.get('weight'))
        email = request.POST.get('email')
        
        # 不允许重复添加
        staff_list = Staff.objects.filter(accountname=accountname, is_deleted=0)
        if staff_list:
            return HttpResponse(simplejson.dumps({"statusCode":400, "message":u'此IT员工已存在,不允许重复添加!'}), mimetype='application/json')
            
        staff = Staff()
        # 一类特殊情况,IT工程师删除以后又被重新加入
        staff_list = Staff.objects.filter(accountname=accountname, is_deleted=1)
        if staff_list:
            staff = staff_list[0]
        
        staff.area_id = area_id
        staff.realname = realname
        staff.accountname = accountname
        staff.phone = phone
        staff.weight = weight
        staff.is_deleted = 0
        staff.email = email
        
        if is_available_list:
            staff.is_available = 1
        else:
            staff.is_available = 0
            
        staff.save()
        
        return HttpResponse(simplejson.dumps({"statusCode":200,"url": "/staff/index", "message":u'添加成功'}), mimetype='application/json')
    else:
        # 区域
        area_list = Area.objects.all()
        return render_to_response('staff/add.html',{'area_list':area_list,'weight_dict':weight_dict}) 
    def post(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            staff = Staff(
                user=User.objects.get(pk=request.POST["user_id"]),
                academic_degree=Academic_Degree.objects.get(
                    pk=request.POST["academic_degree_id"]),
                academic_rank=Academic_Rank.objects.get(
                    pk=request.POST["academic_rank_id"]),
                position=Positions.objects.get(pk=request.POST["position_id"]))
            staff.save()

            user = User.objects.get(pk=request.POST["user_id"])
            group = Group.objects.get(name='Staff')
            group.user_set.add(user)

            response_serializer = self.serializer_class(staff)
            return Response(response_serializer.data)
        else:
            return Response({"msg": serializer.errors},
                            status=status.HTTP_400_BAD_REQUEST)
Example #15
0
def staff_registration(request, *args, **kwargs):
    if request.method == "POST":
        form = StaffForm(request.POST or None)
        if form.is_valid():
            details = form.cleaned_data
            new_username = details['username']
            new_fName = details['firstName']
            new_mName = details['middleName']
            new_lName = details['lastName']
            new_passwd = details['passwd']
            new_email = details['email']
            new_dob = details['date']
            new_gender = details['gender']
            new_mobile = details['mobile']
            new_branch = details['branch']
            new_designation = details['designation']
            new_isAdmin = False
            new_isPending = True
            new_account_id = id_generator()

            #sets category of user
            new_category = ''
            if new_designation in ['Professor', 'Assistant Professor']:
                new_category = 'Faculty'
            elif new_designation == 'Head of Department':
                new_category = 'Head of Department'
            elif new_designation in ['Lab Instructor', 'Lab Assistant']:
                new_category = 'Staff'

            # find the number of users in staff
            staff_count = int(Staff.objects.count())

            # if there are no staff members, the first created user will be admin
            if staff_count < 1:
                new_isAdmin = True
                new_category = 'Admin'
                new_isPending = False

            try:
                validate_password(new_passwd, form)
            except ValidationError as e:
                form.add_error('passwd', e)
                return render(request, "common/staffregistration.html",
                              {'form': form})

            # try:
            #     user_credentials = [new_username, new_fName, new_lName, new_mName, new_mobile]
            #     for item in user_credentials:
            #         if item.lower() in new_passwd.lower():
            #             raise ValidationError('Password too similar to credentials.')
            # except ValidationError as e:
            #     form.add_error('passwd', e)
            #     return render(request, "common/staffregistration.html", {'form': form})

            newStaff = Staff(firstName=str(new_fName.capitalize()),
                             middleName=str(new_mName.capitalize()),
                             lastName=str(new_lName.capitalize()),
                             username=str(new_username),
                             passwd=str(new_passwd),
                             account_id=str(new_account_id),
                             date=str(new_dob),
                             mobile=str(new_mobile),
                             branch=str(new_branch),
                             email=str(new_email.lower()),
                             gender=str(new_gender),
                             designation=str(new_designation),
                             isAdmin=new_isAdmin,
                             isPending=new_isPending,
                             category=str(new_category))

            # newUser = AppUser(
            #             firstName=str(new_fName.capitalize()),
            #             lastName=str(new_lName.capitalize()),
            #             username=str(new_username),
            #             passwd=str(new_passwd),
            #             email=str(new_email.lower()),
            #             category=str(new_category),
            #             isAdmin=new_isAdmin,
            #             isPending=new_isPending
            # )

            newUser = User.objects.create_user(
                username=str(new_username),
                password=str(new_passwd),
                first_name=str(new_fName.capitalize()),
                last_name=str(new_lName.capitalize()),
                email=str(new_email.lower()),
            )

            # newDjangoUser.save()
            newStaff.save()
            newUser.save()

            if new_isPending:
                return redirect("../pending-account")
            else:
                return redirect("../account-created")
    else:
        form = StaffForm(request.POST or None)
        for field in form.errors:
            form[field].field.widget.attrs['class'] += 'error'

    return render(request, "common/staffregistration.html", {'form': form})