Facebook

How to hide pages on google sites

Sometimes you might required to hide some pages from public views in Google sites. Or you may want to delete the page but then you might use same page again so you decided to save the page as draft temporarily.

Here is the step by step process to do so.

- Login to your account. Open the google site.
- Open any page. Click on the settings button on top right corner.

- Look for sharing and permission menu item. Click on it.



- on next page, click on 'Turn page level permission on'.


- Now select any page you want to hide or save as draft.
- Change the permission settings to desired value.


How to use custom UserModel in django

In previous article we learned how to use django authentication in your application. But sometimes it may happen that default user model of django does not fit your requirement. You may want to add more fields to it. Now there are multiple ways to do it.

1. Use proxy model. No new model is created.
2. Use one-to-one relationship and create another model.
3. Create your own user model and use default authentication system.
4. Create your own user model and create your own authentication system.

Previous article - http://www.newbie42.com/2016/09/implementing-authentication-in-django.html

We will be learning 3rd method here.

Note : This needs to be done before performing any migration.

- First create the custom user model and custom user manager.

from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
from django.utils import timezone
from django.db.models import Max

class MyUserManager(BaseUserManager):
use_in_migrations = True
def create_user(self,login, parent_type, last_name, first_name, password):
return create_superuser(self,login, parent_type, last_name, first_name, password)

def create_superuser(self,login, parent_type, last_name, first_name, password):
maxx = self.model.objects.all().aggregate(Max('sys_id'))
if maxx["sys_id__max"] is None:
maxx["sys_id__max"] = 0
user = self.model(
                 sys_id = maxx["sys_id__max"] + 1,
                 login = login,
                 parent_type = parent_type,
                 last_name = last_name,
                 first_name = first_name,
                 display_name = last_name + " " + first_name,
                 created_when = timezone.now()
                 )
user.set_password(password)
user.save(using=self._db)
# no difference here...actually can set is_admin = True or something like that.
return user

class UserModel(AbstractBaseUser):
# custom user class

sys_id = models.BigIntegerField(primary_key=True, blank=True)
last_name = models.CharField(null=False, blank=False, max_length=40)
first_name = models.CharField(max_length=40, null=False, blank=False)
display_name = models.CharField(max_length=80, unique=True, null=False, blank=True)
login = models.CharField(max_length=40, unique=True, null=False, blank=False)
authentication_method = models.CharField(max_length=80, null=True, blank=True)
access_valid_start = models.DateTimeField(null=True, blank=True)
access_valid_end = models.DateTimeField(null=True, blank=True)
notes = models.CharField(max_length=2048, null=True, blank=True)
is_active = models.BooleanField(default=True)

objects = MyUserManager()

USERNAME_FIELD = "login"
# REQUIRED_FIELDS must contain all required fields on your User model, 
# but should not contain the USERNAME_FIELD or password as these fields will always be prompted for.
REQUIRED_FIELDS = [ 'last_name', 'first_name']

class Meta:
app_label = "appname"
db_table = "Users"

def __str__(self):
return self.display_name

def get_full_name(self):
return self.display_name

def get_short_name(self):
return self.last_name


- Now in your settings.py file add this line. It will tell your application that you have to use your custom model for authentication instead of default one.

AUTH_USER_MODEL = 'accounts.UserModel'

- Write your login/logout functions just like in previous article.
-

Implementing authentication in Django

Django - 1.9
Python - 3.4

To implement the authentication in django follow these steps.

- First complete the initial migration so that initial tables are created in DB.
- Create superuser.
- Login to admin module using the credentials created in step above.
- Create another user which might be admin 'staff' member or not.
- Edit your url.conf file and add the urls corresponding to login and logout.
 [replace appname with your app's name in code below]

    url(r'^$', views.index, name='index'),
    url(r'^login/$', views.appname_login, name='appname_login'),
    url(r'^logout/$', views.appname_logout, name='appname_logout'), 



- Create login, logout and index functions in your view.py file

from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate, login, logout
from django.core.urlresolvers import reverse


@login_required(login_url='/appname/login/')
def index(request):
    print(request.user)
    context = {}
    context["user"] = request.user
    return render(request, "appname/index.html", context)



def tenant_login(request):
    context = {}
    if request.method == "GET":
        if "next" not in request.GET:
            context["next"] = "/appname/"
        else:
            context["next"] = request.GET["next"]
        return render(request, "appname/login.html", context)
    else:
        username = request.POST["username"]
        password = request.POST["password"]
        next_url = request.POST["next"]
        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)
                return redirect(next_url, args=(),kwargs={})
            else:
                context["message"] = "User is not active"
        else:
            context["message"] = "Invalid username or password"
        return render(request, "appname/login.html", context)


@login_required(login_url='/appname/login/')
def tenant_logout(request):
    logout(request)
    url = reverse("appname:appname_login")
    return redirect(url, args=(),kwargs={})


- Create login.html file in template directory.

   <form method="post" action="{% url "appname:appname_login" %}">
        {% csrf_token %}
       
<input type="text" name="next" hidden="" value="{{next}}">         
        <input type="text" name="username"> 
        <input type="password" name="password">
       
<input type="submit" name="submit" value="Log In">
   
</form>
    {{message}}


- Inside your index.html file

   {% if user.is_authenticated  %}
    {{user.first_name}}
    <a href="{% url "tenant:tenant_logout" %}">Logout</a>

    {% endif %}

- Run the python server. Goto localhost:8000/appname/.
- In view file you can see that 'index' method uses login_required decorator, if you are not logged in than you will be redirected to login page.
- When you are redirected to login page from any xyz page then a url parameter is added to url which tells where to redirect on successful login. Observe the url in address bar when you are redirected to login page.
- Enter the username and password of the user created in a step above. Log in.
- You will redirected to index page. If user is authenticated (if user is not AnonymousUser) then user's first name and logout link is displayed otherwise not.
- Clicking logout will logout you from the application and try to redirect to index page. but since index page requires login you will be redirected to login page.
- You can print user's full name in index template because you have full access to user object. Use {{user.get_full_name}} or {{user.first_name}} in template.


Let me know if you face any issues in this.

Pretty print json using comman line


1.  cat FileName.json | python -m json.tool


2.  cat FileName.json~ | jq ''
Bonus - colors and multiple options.

Output -

{
  "Apply_Data": "",
  "Message": "Invalid Token or Username-Password combination.",
  "Code": 403
}


3.
echo '{"foo": "bar"}' | python -m json.tool | pygmentize -g
Bonus - Pretty print with syntax highlighting.
















Ubuntu 16.04 new features

Ubuntu 16.04 is about to release on 23rd of April 2016. Ubuntu fans might be exited about the latest features coming to this release. Here is the list of all such features.

Official mascot of Ubuntu 16.04


1. Online searches have been disabled from unity search results. Now you will not see any more Amazon suggestions.

2. Ubuntu software center has been removed as it was very heavy.

3. 'apt-get' has been replaced with 'apt' only. This command is used in Debian systems. 

4. Unity Launcher can be moved to bottom of the screen.




5. Default support for ZFS file system.

6. Linux Kernel 4.4 , Mozilla Thunderbird updated to 45.0,  Docker 1.10 and much more...

Me right now... 




How to send email using python

To send the mail to multiple people using code is easy. Copy paste the below line in a text file and save as mail.py.  Replase the me@gmail.com with your actual email address and you@gmail.com with the address to whom you want to send the email.

Make sure your access level settings in gmail account are set to low.
go to this link https://www.google.com/settings/u/1/security/lesssecureapps
and check radio button 'Turn on'.

# code starts here ...

import smtplib

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

# me == my email address
# you == recipient's email address
me = "me@gmail.com"
you = "you@gmail.com"

# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = "Link"
msg['From'] = me
msg['To'] = you

# Create the body of the message (a plain-text and an HTML version).
text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.python.org"
html = """\
Your html content goes here...
"""

# Record the MIME types of both parts - text/plain and text/html.
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')

# image attachment code here

# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
msg.attach(part1)
msg.attach(part2)
# Send the message via local SMTP server.
mail = smtplib.SMTP('smtp.gmail.com', 587)

mail.ehlo()

mail.starttls()

mail.login('username', 'password')
mail.sendmail(me, you, msg.as_string())
mail.quit()

# code ends here ...


You can also attach file/images to your email.  Use the below code snippet for same.

#attaching an image as attachment. START

ImgFileName = '/home/rana/Pictures/1.jpg'
img_data = open(ImgFileName, 'rb')
image = MIMEApplication(img_data.read(), Content_Disposition='attachment; filename="%s"' % basename(ImgFileName), Name=basename(ImgFileName))
msg.attach(image)

#attaching an image as attachment. END

You can use for loop to send the same mail to multiple people. That part I leave up to you.


If you face any issue while sending mail using this code, let me know.






Finding file and directory in ubuntu


To find a file in your system by name use below command -

find -name "query"

For case insensitive search -
find -iname "query"

Create a bootable Pen Drive in Ubuntu


Ubuntu have a default program to create a bootable pen drive.
Follow these steps to create the same.

1. Download the iso image file of latest Ubuntu from their official site.
2. Now attach an empty USB drive to the system.
3. Start the 'startup disk creator' program.


4. Select the downloaded iso image file as the source file.


5. Select the USB device as the 'disk to use'.
6. Select less than 1 GB Reserved disk space. Click 'Make Startup Disk'.


7. Files will be copied to disk. After some time when OS installation on the disk is complete click the 'quit' button.



8. Detach the USB disk and follow this article to install the Ubuntu on any system. 

Leave a comment in case of any query.

Classic snake game in Linux terminal

Hello Friends,

You must have played the classic snake game on feature phones like Nokia 1100.
Now you can again play the same game in Linux terminal.
For this you need to install nsnake package by running below command in terminal.


sudo apt-get install nsnake


After the package is installed , run the game by running nsnake command.




Use the up and down arrow keys to change to game mode to Borders On and Borders Off.
Use left and right arrow keys to change the speed.
Press enter or space to start the game one you are done with settings.
You can exit the game by pressing q key.




Rules are the same as they were in classic game.
If you collide with yourself (snake), you die. Game over.




Download the latest version of this game from Github.
Buy cheapest nokia mobile phones here.