Django Form – Selectively hide fields

The model forms has an option to specify an array exclude with fields that you’d like to hide on the form. But for a regular form, it’s much easier. Here’s how it can be implemented in a form.

class ExtendLicenseForm(forms.Form):
    extension_days = forms.IntegerField(required=True, help_text='License can be extended for a maximum of 30 days.')
    # Below is the field that I'd like to show in the form if the kwargs passed in value is True
    upload_tenant_license = forms.BooleanField(required=False, label='Upload license', help_text='Select option if you would like to automatically upload the extended license to the tenant.')
    def __init__(self, *args, **kwargs):
        upload_tenant_lic_opt = kwargs.pop('upload_tenant_license') if 'upload_tenant_license' in kwargs else None
        super(ExtendLicenseForm, self).__init__(*args, **kwargs)
        if not upload_tenant_lic_opt:
            # Hide the form field if the flag is False
            self.fields['upload_tenant_license'].widget = forms.HiddenInput()

.

Postgres – Update table data by replacing words

While working with some email templates, I made a typo. Now, I had a few options to choose from. Open each template from the UI and make the change. The other one was use a SQL editor and create update commands, modify the data in the query and execute. But either of those would be quite laborious. Then I searched for something that could do an update with a string replace across all fields in a table and Voila, found it. Here’s the solution:

UPDATE commander_commonemailtemplate 
SET email_body = replace(email_body, 'file from the links at the bottom', 'file from the link at the bottom');

As you noticed, links was supposed to be replaced with link. But the reason I chose a bigger line was so that if if there are other rightful occurrences of the word links, they won’t get replaced.

Django – Display hyperlinks in templates

I had a couple of challenges here apart from just displaying hyperlinks.

1. Displaying the hyperlinks
2. Filter the list of display data to show hyperlink for first item and not for rest

<table class="sortable">
  <tr>
    {% for column in report_header %}
      <th>{{column}}</th>
    {% endfor %}
  </tr>
  {% for row in report_body %}
    <tr class="{% cycle "row1" "row2" %}">
      {% for column in row %}
        {% if forloop.counter == 1 %}
          {% with row.0|urlencode as encoded_name %}
            <td><a href="#" onclick="window.open('{%url showAccountPage encoded_name%}', '_blank');">{{row.0}}</a></td>
          {% endwith %}
        {% else %}
            <td>{{column}}</td>
        {% endif %}
      {% endfor %}
    </tr>
  {% endfor %}
</table>

PHP Warning – date(): It is not safe to rely on the system’s timezone settings

Ever encountered this warning while executing PHP code?

PHP Warning:  date(): It is not safe to rely on the system's timezone settings. You are *required* to use the date.timezone setting 
or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely 
misspelled the timezone identifier. We selected the timezone 'UTC' for now, but please set date.timezone to select your timezone. 
in/path/file.php on line 10

Solution – explicitly add a timezone to the php.ini file

date.timezone = "America/Los_Angeles"

A list of timezones is available here – http://php.net/manual/en/timezones.php

CentOS 7 – Install PHP and Postgres

First time using CentOS. Thought it will be useful to list down the steps to install PHP and Postgres and get it to work together.

0. Always recommend updating

yum update
# update will update every currently installed package

1. Install PHP

yum install php
# Validate installation and version by executing php --info

2. Install PostgreSQL

yum install postgresql-server postgresql-contrib 

3. Install php-pgsql connector

yum install php-pgsql

4. Now start and enable postgres

service postgresql initdb
systemctl start postgresql
systemctl enable postgresql
service postgresql restart

5. Modify the pg_hba.conf file located under /var/lib/pgsql/data/. Find the lines that looks like this

host    all             all             127.0.0.1/32            ident
host    all             all             ::1/128                 ident

Then replace “ident” with “md5”, so they look like this:

host    all             all             127.0.0.1/32            md5
host    all             all             ::1/128                 md5

6. Create local user and set user password

adduser automation
sudo su
passwd automation

7. Login as postgres and connect to database. Create user role (with same password as shell) and new database

su postgres
pgsql
>CREATE DATABASE masterdb;
>CREATE ROLE automation WITH PASSWORD 'UserPassword';
>GRANT ALL PRIVILEGES ON DATABASE masterdb TO automation;
>ALTER ROLE automation WITH LOGIN; 

The last one was important because I wasn’t able to connect to the database. But not sure if this solved the problem because GRANT ALL PRIVILEGES should have taken care of it. Needs to be researched further.

8. Create a test connection script in PHP to validate database connection

//  Configure DB Parameters
$host = "localhost";
$dbname = "masterdb";
$dbuser = "automation";
$userpass = "UserPassword";

$con = pg_connect("host=$host
                                  dbname=$dbname
                                  user=$dbuser
                                  password=$userpass
                                  ");


if (!$con) {
        die('Could not connect');
}
else {
        echo ("Connected to local DB");
}

Debian – Change date time to PST and sync using NTP

I installed a server that showed time in UTC. I wanted to change the zone to PST and also have the time sync with a trusted source for which I used NTP service. Here’s what you need to do:

1. Remove the localtime file that keeps track of the timezone

rm /etc/localtime

2. Link localtime to other existing timezones. All US timezones are located under under the /usr/share/zoneinfo/US directory. Link the Pacific time to the localtime

cd /etc
ln -s /usr/share/zoneinfo/US/Pacific localtime

3. Now execute the date command and you’ll see the time in PST

date
# Thu Jun  2 12:01:41 PDT 2016

4. Install NTP to sync time

apt-get install ntp

5. Make sure your computer’s clock is set to something sensible (within a few minutes of the ‘true’ time). Just check your computer’s time or your wristwatch and modify the approximate time on the server using

date --set 12:20:00

6. Now restart the NTP services

/etc/init.d/ntp restart

After the minute completes, check the date command and you’ll notice that the time is now synced accurately with a trusted ntp server.

AWS – New server setup

I frequently setup instances on AWS and have to do a bunch of configuration to allow ssh access. Here’s a list of things that need to be done:

1. First time login with private key

ssh -i .ssh/your-private-key.pem admin@IP-Address

2. Change hostname – Changing hostname on Jessie build is fairly straightforward.

hostnamectl set-hostname your-new-hostname

Restart the hostname service within /etc/init.d or logout and log back into session

3. Allow ssh without private key – Modify the sshd_config file and make sure the following setting is enabled

PasswordAuthentication yes

Save the file and exit. Restart the ssh services within /etc/init.d

./ssh restart

4. Add new user – Use the following command as opposed to useradd and follow the prompts

adduser username

5. Add sudo privileges to username – Add sudo privileges without password to the /etc/sudoers file

# User privilege with no password
username     ALL=NOPASSWD:ALL