def create_user(self,
                  username,
                  is_superuser=False,
                  is_active=True,
                  extenduser=True,
                  groups=False,
                  password='******'):
    #Create a testuser
    testuser = User.objects.create_user(first_name='TestFirst',
                   last_name='TestLast',
                   username=username,
                   password=password,
                   email='*****@*****.**')
    testuser.is_active = is_active
    testuser.is_superuser = is_superuser
    testuser.save()

    if extenduser:
        #Create an extended user.
        exttestuser = ExtendedUser(user=testuser,phonenumber='0000000000')
        #Save the extended user.
        exttestuser.save()
        user = exttestuser
    else:
        user = testuser

    #Add in the groups, defined
    #   in a list.
    if groups:
        #Group throught the list of groups.
        for g in groups:
            try:
              group = Group.objects.get(name=g)
            except:
              #Load the group.
              group = Group(name=g)
              #Save the group.
              group.save()
            #Add the usergroup.
            testuser.groups.add(group)

    #Return the user.
    return user
def register(request):
	
	#Load the context variables
	context = {
		'title': 'User Registration',
	}

	#Check the post request.
	if request.method == 'POST':

		#Get the formdata 
		formdata = {
			'first_name' : request.POST['first_name'],
			'last_name' : request.POST['last_name'],
			'username' : request.POST['username'],
			'phonenumber' : request.POST['phonenumber'],
			#Password and confirm password are validated against each other.
			'password' : request.POST['password'],
			'confirm_password' : request.POST['confirm_password'],
			'email' : request.POST['email']
		}

		###
		# We bind the post data to the form here for validation.
		###
		registerform = RegisterForm(formdata)

		#Make sure the register form passed the validation
		if registerform.is_valid():

			#Create the user object.
			newuser = User.objects.create_user(first_name=formdata['first_name'],
									 last_name=formdata['last_name'],
									 username=formdata['username'],
									 password=formdata['password'],
									 email=formdata['email'])

			#Initially the user is inactive, activated by super user.
			newuser.is_active = False
			
			#Save the user object.
			newuser.save()

			#Add the general user group to the new user.
			#GeneralUserGroup = Group.objects.get(name='General User')
			#newuser.groups.add(GeneralUserGroup)

			#Add the Extended user row
			extuser = ExtendedUser(user=newuser,phonenumber=formdata['phonenumber'])
			extuser.save()

			#Send the activation email, contains a publicid.
			send_activation_email(request,newuser)

			#Return the success view
			return render(request,
						  'user_management/registersuccess.html',
						  context)
	else:
		###
		# Create an unbound form because
		#	there isn't any post data.
		###
		registerform = RegisterForm()
		
	"""
	" The below code happens if:
	"	-There is no post data.
	"	-The submitted form is invalid.
	"""
	context['RegisterForm'] = registerform

	#Return the view
	return render(request,
				  'user_management/register.html',
				  context)
def login(request):

	#Load the view variables.
	context = {
		'title': 'User Login',
		'loginerror': False,
	}
	"""
	" This is the login logic.
	"""
	if 'username' in request.POST and 'password' in request.POST:

		#Get the formdata
		formdata = {
			#Get the user input
			'username' : request.POST['username'],
			'password' : request.POST['password'],
		}

		#Authenticate the user based on their input.
		user = authenticate(username=formdata['username'], password=formdata['password'])
		
		#Check if the user authenticated properly.
		if user:
			#Check if the user is active.
			if user.is_active:

				#Login the user
				userlogin(request,user)

				#This is the is_superuser
				if user.is_superuser:
					#If the user is a super user we check to
					#		see if the user groups are created.
					create_groups(user)
					#If there is not an ExtendedUser object associated with
					#		the admin we have to create one for the admin.
					if ExtendedUser.objects.filter(user=user).count() == 0:
						#Create a temporary phone number.
						extendeduser = ExtendedUser(user=user,phonenumber="000000000")
						#Save the ExtendedUser.
						extendeduser.save()
				#Check the next variable in the url
				#	for redirect to the original request.
				if 'next' in request.GET and request.GET['next'] != '/logout/':
					#Redirect to the original request.
					return redirect(request.GET['next'])
				else:
					#Redirect to the default view.
					return redirect('/')
			else:
				context['loginerror'] = "You have not been activated, please check your email"
		else:
			context['loginerror'] = "Incorrect username or password"

	"""
	" End the login logic.
	"""

	"""
	" Load the login form.
	"	This is run if:
	"	-User is not authenticated.
	"	-No POST information.
	"""
	context['AuthenticationForm'] = AuthenticationForm

	return render(request,
		  		  'user_management/login.html',
				  context)
	"""
def viewusers(request):
	
	context= {
			'title':'View Users',
	}

	existingusernotification = False

	#Check to see if a user has been edited
	if request.method == 'POST' and ('edit_user' in request.POST or 'add_user' in request.POST):
		"""
		" Get the form data.
		"""
		#Get the username.
		newusername = request.POST['username']
		#Get the first name.
		newfirst_name = request.POST['first_name']
		#Get the last name.
		newlast_name = request.POST['last_name']
		#Get the email.
		newemail = request.POST['email']
		#Get the phone number.
		newphonenumber = request.POST['phonenumber']
		#Get the password.
		newpassword = request.POST['password']
		#Get wether or not they are active.
		is_active = False
		if 'is_active' in request.POST:
			is_active = True

		is_program_manager = False
		if 'is_program_manager' in request.POST:
			is_program_manager = True

		if 'edit_user' in request.POST:
			#Get the public id
			publicid = request.POST['edit_user']
			#Get the extended user
			extendeduser = ExtendedUser.objects.get(publicid=publicid)
		else:
			extendeduser = False

		"""
		" End the form data.
		"""

		"""
		" Check if is existing user.
		"""
		if not check_existing_user(newusername) or extendeduser and extendeduser.user.username == newusername:

			"""
			" Save the user information.

			"""
			#We are making a new user
			if extendeduser:
				#Get the username.
				extendeduser.user.username = newusername
				#Get the first name.
				extendeduser.user.first_name= newfirst_name
				#Get the last name.
				extendeduser.user.last_name = newlast_name
				#Get the email.
				extendeduser.user.email = newemail
				#Add the phonenumber
				extendeduser.phonenumber = newphonenumber
			else:
				#Create a new user
				user = User.objects.create_user(
					username=newusername,
					password=newpassword,
					first_name=newfirst_name,
					last_name=newlast_name,
					email=newemail,
				)

				extendeduser = ExtendedUser(user=user,phonenumber=newphonenumber)
			
			#Get the active boolean.
			extendeduser.user.is_active= is_active

			#Save the user.
			extendeduser.user.save()
			extendeduser.save()

			if is_program_manager:
				program_manager = Group.objects.get(name='Program Manager')
				extendeduser.user.groups.add(program_manager)
			elif check_user_groups(extendeduser.user,'Program Manager'):
				program_manager = extendeduser.user.groups.get(name='Program Manager')
				extendeduser.user.groups.remove(program_manager)

			if len(newpassword) > 0:
				extendeduser.user.set_password(newpassword)

			"""
			" End of saving the user information.
			"""
		else:
			try:
				existingusernotification = publicid
			except:
				existingusernotification = True

		"""
		" End check of existing users.
		"""
	"""
	" Filter the topics.
	"""
	#Check to see if the user has filtered 
	#	the topics.
	if request.method == 'GET' and 'search' in request.GET:
		#Get the user defined search filter
		search = request.GET['search']
		#Filter the topic list based on the users filtered information.
		users_list = ExtendedUser.objects.filter(
			~Q(user__is_superuser=True) & 
				(Q(user__username__icontains=search) | 
				 Q(user__first_name__icontains=search) |
				 Q(user__last_name__icontains=search) 
			 	)
			)
	else:
		#Load the topic objects into a list
		users_list = ExtendedUser.objects.exclude(user__is_superuser=True)


	users_object = paginate(request,users_list)

	"""
	" End filter of the topics.
	"""

	#Get a user 
	def returnfunc(request,u):

		if request.POST and 'edit_user' in request.POST and request.POST['edit_user'] == u.publicid:
			return request.POST
		else:
			return {
				'first_name':u.user.first_name,
				'last_name':u.user.last_name,
				'email':u.user.email,
				'phonenumber':u.phonenumber,
				'username':u.user.username,
				'is_active':u.user.is_active,
				'is_program_manager' : check_user_groups(u.user,'Program Manager'),
			}

	users = [{
		'publicid':u.publicid,
		'extendeduser':u,
		'user':u.user,
		'user_form':form_modal(request,
													'edit_user',
													UserManagementForm(returnfunc(request, u)).as_table(),
													modal_title = 'Edit %s'% u.user.get_full_name(),
													modal_id = 'edit_user_%s'% u.publicid,
													table_class = 'edit_user_form ',
													formname_value=u.publicid),
		'is_program_manager' : check_user_groups(u.user,'Program Manager'),
	}
	for u in users_object
	]

	#Create a user modal
	add_user_form = form_modal(request,
														'add_user',
														UserManagementForm(request.POST if 'edit_user' in request.POST else None).as_table(),
														modal_title='Add a User',
														modal_id='add_user')

	#Pass in the users.
	context['users'] = users
	context['paginated_users'] = users_object
	context['add_user_form'] = add_user_form
	context['existingusernotification'] = existingusernotification
	context['queries'] = users_object.qstring

	return render(request,
		'user_management/viewusers.html',
		context)