Category Archives: Programming

How to perform CRUD functionalities in Django Rest Framework

Django Rest framework is a powerful toolkit for building web APIs.

What is an API?

An API (Application Programming Interface) is a set of rules shared by a particular service. These rules determine in which format and with which command set your application can access the service, as well as what data this service can return in the response. It acts as a layer between your application and external service.

REST API (Representational state transfer) is an API that uses HTTPS requests for communication with web services. From the python site, the REST API can be viewed as a data source located on an internet address that can be accessed in a certain way through certain libraries.

Types of Requests:

GET: retrieve information like a search result

POST: adds new data to the server

PUT: changes existing information

DELETE: deletes existing information

Status Codes

200-OK. The request was successful.

204-No content. The server successfully processed the request and did not return any content.

301-Moved permanently. The server responds that the requested page(endpoint) has been moved to another address and redirects to this address.

400-Bad request. The server cannot process the request because of the client-side errors (incorrect request format).

401-Unauthorized. Occurs when authentication failed due to incorrect credentials or even their absence.

403-Forbidden. Access to the specified resource is denied.

404-Not found. The requested resource was not found on the server.

500-Internal Server Error. Occurs when an unknown error has occurred on the server.

Enough with the theory part. Let’s see how we can create CRUD functionalities in the Django Rest framework.

I will create a small to-do list application to guide us through the process.

Steps to follow.

  1. Create a project and set up a virtual environment.
  2. Activate virtual environment
  3. Install Django using pip
  4. Create a project and an app

Create a Django Project and set up a virtual environment.

The first thing to do whenever you are creating Django projects is to set up your virtual environment where you can work in isolation. Let’s start. Install venv package to allow you to create a virtual environment. On your terminal use the following command to create virtual environment.

$ python3 -m venv env 

If you ls you will see your environment created. For my case, I created env as my environment.

To activate your environment, use the following command.

source env/bin/activate

After the environment is activated, let’s install Django using the pip command.

pip install django

Create a requirements.txt file to store all your installations so that the next time someone is using your applications, it will be easy to start off. An easy way to create requirements is to use the freeze command.

pip freeze > requirements.txt

And to do an installation from the requiremets.txt file, use the following command.

pip install -r requiremets.txt

Create a Django Project

To create a Django project, we use the following command.

django-admin startproject myapi .

Take note of the period in the end, it will help create a project from the current directory.

After this is done, create an app.

python manage.py startapp todoapi

The last thing before we can start our server is to go to settings.py and add your created app to the installed apps section. From here the best thing is to open your project using Visual Studio or Pycharm. For me, I will be using Pycharm.

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    
    'todoapi',# our app
]

From here you can test if the server is running

python manage.py runserver

if you see the following as output, then we are good to continue.

System check identified no issues (0 silenced).

You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
July 13, 2022 - 07:03:07
Django version 4.0.6, using settings 'myapi.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

Go to the given IP address to see the outcome.

Let’s render something rather than the default Django output by adding our app to the projects urls.py section.

#myapi.urls
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include('todoapi.urls')), # add this todoapi.urls 
]

Also to keep our URLs neat and tidy, go to todoapi and create a urls.py

#todoapi urls.py
from django.urls import path
from . import views 

urlpatterns = [
    path('', views.home, name='home'),
]

Go to todoapi views.py and create the first view of our rest API.

#todoapi/views.py
from django.shortcuts import render
from django.http import HttpResponse


def home(request):
    return HttpResponse("My first api")

You are supposed to see “my first API from the browser”. This means we are good to create our API now.

Create Django Rest API

To start creating a rest API, you need to install djangorestframework and add it to your installed apps in the settings.py

pip install djangorestframework

Then you need to add it to your installed apps

INSTALLED_APPS = [
    ...
    'rest_framework',
]

Also you can add it to your requirements.txt file

pip freeze > requirements.txt 

To begin with, we are going to use function based views therefore we need decorators. For function based views, we use @api_view.

Go to models.py and add the following

#todoapi models.py
from django.db import models


class Todo(models.Model):
    title = models.CharField(max_length=150)
    completed = models.BooleanField(blank=True, null=True, default=False)

    def __str__(self):
        return self.title

To begin, lets create a serializers.py file in our todoapi app first.

#todoapi serializers.py
from rest_framework import serializers

from todoapi.models import Todo


class TodoSerializer(serializers.ModelSerializer):
    class Meta:
        model = Todo
        fields = '__all__'

You need to make migrations for the serializer tables to be created.

$ python manage.py makemigrations
$ python manage.py migrate 

From here you can create admin account so that you can insert the test data. to create admin panel use the following command.

$ python manage.py createsuperuser
Username (leave blank to use 'nextgen'): admin
Email address: 
Password: 
Password (again): 
Superuser created successfully.

The next thing is to register admin in the admin dashboard. use the following.

from django.contrib import admin

# Register your models here.
from todoapi.models import Todo

admin.site.register(Todo)

Running CRUD operations

List Request

To start performing CRUD operations, lets start with the List Operations, this will show all the todos we have in our database. List is a GET operations, so make sure to add that

Go to views.py and add the following.

@api_view(['GET'])
def list_view(request):
    todos = Todo.objects.all()
    serializer = TodoSerializer(todos, many=True)
    return Response(serializer.data, status=status.HTTP_200_OK)

Create a url corresponding to the above view.

path('todo-list/', views.list_view, name='todo-list')

Detail Request

The next thing is to create a detail view, also we are going to use GET to retrieve data.

@api_view(['GET'])
def detail_view(request, pk):
    todo = Todo.objects.get(id=pk)
    serializer = TodoSerializer(todo, many=False)
    return Response(serializer.data)

Note we are using primary key to retrieve specific item.

Create corresponding url for detail view set.

path('detail-view/<int:pk>/', views.detail_view, name='detail-view')

Create Request

Here we are using POST to post data into the database. Use the following code

@api_view(['POST'])
def create_view(request):
    serializer = TodoSerializer(data=request.data)

    if serializer.is_valid():
        serializer.save()
    return Response(serializer.data, status=status.HTTP_201_CREATED)

Add corresponding url path

 path('create-todo/', views.create_view, name='create-todo'),

For testing purposes you can use Insomnia or postman or you can stick to the one provided once you access the API on your browser.

Update request

To update a given request we use POST method. use the following code.

@api_view(['POST'])
def update_view(request, pk):
    todo = Todo.objects.get(id=pk)
    serializer = TodoSerializer(instance=todo, data=request.data)

    if serializer.is_valid():
        serializer.save()
    return Response(serializer.data, status=status.HTTP_202_ACCEPTED)

Add corresponding url path

path('update-todo/<int:pk>/', views.update_view, name='update-todo'),

Delete request

To use delete request, DELETE options is called. Use the following code.

@api_view(['DELETE'])
def delete_view(request, pk):
    todo = Todo.objects.get(id=pk)
    todo.delete()
    return Response("Todo deleted successfully", status=status.HTTP_204_NO_CONTENT)

Add corresponding url path accordingly.

path('delete-todo/<int:pk>/', views.delete_view, name='delete-todo'),

Conclusion

We have successfully performed CRUD operations on Django Rest API. To take it further you can use swaggerUI to visualize your API or you can connect to any frontend libraries such React, Vue, Svelte or use Vanilla Javascript.

How to install Python Pip on Ubuntu 22.04

In this tutorial, you will learn how to install Python pip on Ubuntu 22.04.

Pip is a package management system written in Python and is used to install and manage software packages. It connects to an online repository of public packages called the Python Package Index. It can also be configured to connect to other package repositories.

Usually, Pip is automatically installed while working in a virtual environment, and also if you are using Python that has not been modified by the redistributor to remove ensure pip.

Pip is recommended tool for installing Python packages. For you to start using pip, you need to have python3 installed on your system.

Installing Python pip on Ubuntu 22.04

You can install pip either through a virtual environment or while installing Python. It depends on which one you prefer. I will be using a virtual environment to install pip on Ubuntu 22.04.

1. Run system updates

First, we need to update our repositories to make them up to date by issuing update and upgrade commands on our terminal.

$ sudo apt update && apt upgrade -y

2. Create a virtual environment

A virtual environment is used to manage Python packages for different projects. It creates an isolated environment for pip packages.

Begin by creating a directory where your virtual environment will be located.

$ sudo mkdir nextgen
$ cd nextgen

Next, create a virtual environment

$ python3 -m venv env

env is the name given to a virtual environment.

In case you encounter the following error, follow the instruction in order to make necessary changes.

The virtual environment was not created successfully because ensurepip is not
available.  On Debian/Ubuntu systems, you need to install the python3-venv
package using the following command.

    apt install python3.10-venv

You may need to use sudo with that command.  After installing the python3-venv
package, recreate your virtual environment.

Failing command: ['/root/nextgen/env/bin/python3', '-Im', 'ensurepip', '--upgrade', '--default-pip']

Correct this error by running

sudo apt install python3.10-venv

From the above, you will see the following output.

The following additional packages will be installed:
  python3-pip-whl python3-setuptools-whl
The following NEW packages will be installed:
  python3-pip-whl python3-setuptools-whl python3.10-venv
0 upgraded, 3 newly installed, 0 to remove and 0 not upgraded.
Need to get 2473 kB of archives.
After this operation, 2882 kB of additional disk space will be used.
Do you want to continue? [Y/n] 

The next thing is to run python3 -m venv env again.

sudo python3 -m venv env

You need to activate the virtual environment to start using it.

$ source env/bin/activate 
(env) root@localhost:~/nextgen# 

Now that we have activated the virtual environment, you can now check if pip has been installed, because pip is installed while creating the virtual environment.

pip --version
pip 22.0.2 from /root/nextgen/env/lib/python3.10/site-packages/pip (python 3.10)

Conclusion

We have learned how to install pip on Ubuntu 22.04 because this is the starting point for any python programming. I am glad you have enjoyed the tutorial. Feel free to comment in case you are faced with a challenge.

How to install PHP 8.1 on Ubuntu 22.04

In this tutorial, we will learn how to install the current stable release version of PHP 8.1 on Ubuntu 22.04.

PHP is a general-purpose scripting language suitable for web development. Most websites out there are programmed using PHP language because it is:

  • Fast – PHP is fast because it runs on its own memory space. Also, PHP has a Zend engine that parses PHP code and turns it into opcodes which are then interpreted.
  • Flexible – PHP is flexible because it allows for almost all databases. MySQL is the de-facto database to connect to because it is open source.
  • Free and open source
  • PHP is forgiving – Why do we say PHP is forgiving? It is forgiving, meaning learning is not so hard and therefore suitable to almost all programmers starting out.
  • PHP supports major communication protocols i.e LDAP, IMAP, POP3.

Features of PHP 8.1

PHP 8.1 is a major update release version. It contains many new features and optimizations such as:

  • It introduced the Enumerations feature. Enumerations or Enum feature allow a developer to define a custom type that is limited to one of the discrete numbers of possible values. This is helpful while defining the domain model.
  • Improvement of RFC read-only property version 2. This prevents modification of the property after initialization.
  • The introduction of RFC fibers calls for action. This seeks to eliminate synchronous and asynchronous function calls by allowing functions to become interruptible without affecting the entire function.
  • Introduction of a non-return type. This indicates that a function either exits throws an exception or doesn’t terminate.
  • Introduction of first-class callable actions.
  • Introduction of fsync and fdatasync functions
  • Introduction of array_is_list functions
  • Introduction of explicit octal numeral notation

Installing PHP 8.1 on Ubuntu 22.04

1. Run system updates

The first thing to do in a new system is to update our repositories in order to make them up to date. Run upgrade command also.

$ sudo apt update && apt upgrade -y

2. Add Ondrej Sury PPA repository

To run PHP 8.1 on Ubuntu 22.04, we need to add Ondrej Sury PPA into our system. This is the maintainer of the PHP repository at the moment. This PPA is not currently checked so installing from it will not guarantee 100% results.

To add this PPA use the following command on our terminal.

$ sudo add-apt-repository ppa:ondrej/php

You will see the following as the output.

PPA publishes dbgsym, you may need to include 'main/debug' component
Repository: 'deb https://ppa.launchpadcontent.net/ondrej/php/ubuntu/ jammy main'
Description:
Co-installable PHP versions: PHP 5.6, PHP 7.x and most requested extensions are included. Only Supported Versions of PHP (http://php.net/supported-versions.php) for Supported Ubuntu Releases (https://wiki.ubuntu.com/Releases) are provided. Don't ask for end-of-life PHP versions or Ubuntu release, they won't be provided.

Debian oldstable and stable packages are provided as well: https://deb.sury.org/#debian-dpa

You can get more information about the packages at https://deb.sury.org

IMPORTANT: The <foo>-backports is now required on older Ubuntu releases.

BUGS&FEATURES: This PPA now has a issue tracker:
https://deb.sury.org/#bug-reporting

CAVEATS:
1. If you are using php-gearman, you need to add ppa:ondrej/pkg-gearman
2. If you are using apache2, you are advised to add ppa:ondrej/apache2
3. If you are using nginx, you are advised to add ppa:ondrej/nginx-mainline
   or ppa:ondrej/nginx

PLEASE READ: If you like my work and want to give me a little motivation, please consider donating regularly: https://donate.sury.org/

WARNING: add-apt-repository is broken with non-UTF-8 locales, see
https://github.com/oerdnj/deb.sury.org/issues/56 for workaround:

# LC_ALL=C.UTF-8 add-apt-repository ppa:ondrej/php
More info: https://launchpad.net/~ondrej/+archive/ubuntu/php
Adding repository.
Press [ENTER] to continue or Ctrl-c to cancel.
Adding deb entry to /etc/apt/sources.list.d/ondrej-ubuntu-php-jammy.list
Adding disabled deb-src entry to /etc/apt/sources.list.d/ondrej-ubuntu-php-jammy.list
Adding key to /etc/apt/trusted.gpg.d/ondrej-ubuntu-php.gpg with fingerprint 14AA40EC0831756756D7F66C4F4EA0AAE5267A6C
Hit:1 http://mirrors.linode.com/ubuntu jammy InRelease
Hit:2 http://mirrors.linode.com/ubuntu jammy-updates InRelease                 
Hit:3 http://mirrors.linode.com/ubuntu jammy-backports InRelease               
Hit:4 http://security.ubuntu.com/ubuntu jammy-security InRelease               
Get:5 https://ppa.launchpadcontent.net/ondrej/php/ubuntu jammy InRelease [23.9 kB]
Get:6 https://ppa.launchpadcontent.net/ondrej/php/ubuntu jammy/main amd64 Packages [92.9 kB]
Get:7 https://ppa.launchpadcontent.net/ondrej/php/ubuntu jammy/main Translation-en [29.1 kB]
Fetched 146 kB in 2s (68.5 kB/s)                                 
Reading package lists... Done

You need to update your system repositories again for the changes to take effect.

sudo apt update 

Install PHP 8.1 on Ubuntu 22.04

After you have updated your system, it’s now time to run the installation, with the following command.

sudo apt install php8.1 -y

You will be in a position to see the following as output.

The following additional packages will be installed:
  apache2 apache2-bin apache2-data apache2-utils libapache2-mod-php8.1 libapr1
  libaprutil1 libaprutil1-dbd-sqlite3 libaprutil1-ldap liblua5.3-0 php-common
  php8.1-cli php8.1-common php8.1-opcache php8.1-readline ssl-cert
Suggested packages:
  apache2-doc apache2-suexec-pristine | apache2-suexec-custom www-browser
  php-pear
The following NEW packages will be installed:
  apache2 apache2-bin apache2-data apache2-utils libapache2-mod-php8.1 libapr1
  libaprutil1 libaprutil1-dbd-sqlite3 libaprutil1-ldap liblua5.3-0 php-common
  php8.1 php8.1-cli php8.1-common php8.1-opcache php8.1-readline ssl-cert
0 upgraded, 17 newly installed, 0 to remove and 1 not upgraded.
Need to get 7227 kB of archives.
After this operation, 29.6 MB of additional disk space will be used.
Do you want to continue? [Y/n] y

Now we can check to see the version of PHP installed

php --version
PHP 8.1.7 (cli) (built: Jun 25 2022 08:13:46) (NTS)
Copyright (c) The PHP Group
Zend Engine v4.1.7, Copyright (c) Zend Technologies
    with Zend OPcache v8.1.7, Copyright (c), by Zend Technologies

Conclusion

We have learned how to install PHP 8.1 on Ubuntu 22.04, now you can proceed to write your programs using this awesome language. Consult PHP documentation in case you experience any difficulty. Happy coding!

How to install Android Studio on Ubuntu 22.04

In this tutorial, we will explore how to install Android Studio on Ubuntu 22.04.

Android Studio is the Integrated Development Environment for Android app development. Whenever you want to start developing android applications, the easiest and the most effective IDE is always the Android studio. It is well tested and offers all the functionalities other code editors provide.

Features of Android Studio

  • It is fast and has many features
  • It offers a unified environment for the development of all android based applications
  • It offers code templates and Github integration for easy code deployment
  • It has extensive testing tools and frameworks.
  • It has linting tools to catch performance, usability, version compatibility
  • It has built-in support for the Google Cloud environment making it easy to integrate the Google App Engine and messaging services

Install Android Studio on Ubuntu 22.04

1. Update system repositories

The first thing is to run system updates so that all the repositories are up to date.

sudo apt update && apt upgrade -y

2. Install required libraries

To begin, we need to install the required libraries. Let’s install those libraries with the following command.

sudo apt-get install libc6:i386 libncurses5:i386 libstdc++6:i386 lib32z1 libbz2-1.0:i386

You will get an output similar to this.

#output
The following additional packages will be installed:
  gcc-12-base:i386 krb5-locales libc6-i386 libcom-err2 libcom-err2:i386
  libcrypt1:i386 libgcc-s1:i386 libgpm2:i386 libgssapi-krb5-2:i386
  libidn2-0:i386 libk5crypto3:i386 libkeyutils1:i386 libkrb5-3:i386
  libkrb5support0:i386 libnsl2:i386 libnss-nis:i386 libnss-nisplus:i386
  libssl3 libssl3:i386 libtinfo5:i386 libtirpc3:i386 libunistring2:i386
Suggested packages:
  glibc-doc:i386 locales:i386 gpm:i386 krb5-doc:i386 krb5-user:i386
The following NEW packages will be installed:
  gcc-12-base:i386 krb5-locales lib32z1 libbz2-1.0:i386 libc6:i386 libc6-i386
  libcom-err2:i386 libcrypt1:i386 libgcc-s1:i386 libgpm2:i386
  libgssapi-krb5-2:i386 libidn2-0:i386 libk5crypto3:i386 libkeyutils1:i386
  libkrb5-3:i386 libkrb5support0:i386 libncurses5:i386 libnsl2:i386
  libnss-nis:i386 libnss-nisplus:i386 libssl3:i386 libstdc++6:i386
  libtinfo5:i386 libtirpc3:i386 libunistring2:i386
The following packages will be upgraded:
  libcom-err2 libssl3
2 upgraded, 25 newly installed, 0 to remove and 182 not upgraded.
Need to get 12.5 MB of archives.
After this operation, 41.0 MB of additional disk space will be used.
Do you want to continue? [Y/n] 

3. Download Android Studio

Head over to the Android Studio download page and hit on download options to download .gz version for Linux.

sudo wget https://redirector.gvt1.com/edgedl/android/studio/ide-zips/2021.2.1.15/android-studio-2021.2.1.15-linux.tar.gz

After the download is complete, we need to extract the Android Studio

sudo tar -xzvf android-studio-2021.2.1.15-linux.tar.gz

Next, we need to move Android Studio to an appropriate location, for us we are going to move to /opt to enable shared users to use it.

sudo mv android-studio /opt/

3. Launch Android Studio

To start using Android Studio, head over to android-studio/bin/ directory and execute studio.sh

$ cd /opt/android-studio/bin
$ sudo ./studio.sh

When you launch your studio.sh bash command, the configuration wizard will appear.

Select whether you want to import the Android settings or not and then click ok.

nextgentips Android studio welcome page
  • Choose the type of settings you want Android Studio to have. Select standard for now
  • Select the UI theme you want to use.
  • Verify settings that it is ok
  • Accept the license agreement and hit next and finish.

From here the Android Studio will start its installation.

You can now start your project by clicking new project.

4. Uninstall Android Studio

To remove Android studio from your system do the following from the command line.

sudo rm -rf /opt/android-studio/

Conclusion

Congratulations, you have installed Android Studio on Ubuntu 22.04. Happy coding.

How to install Sublime Text 4 Editor on Ubuntu 22.04

In this tutorial, we are going to learn how to install the Sublime Text 4 code editor on Ubuntu 22.04.

A sublime Text editor is a shareware cross-platform source code editor, it supports almost all the programming languages.

What’s new with Sublime Text 4?

Sublime Text 4 comes with new features such as:

  • GPU rendering. It can now utilize GPU on Linux, Mac, and windows giving fluid UI up to 8K resolutions.
  • Tab multi-select. File tabs have been enhanced to make split-view effortless with support throughout the interface and built-in commands.
  • Context-aware auto-complete. It has been rewritten to provide smart completion based on existing code.
  • Updated Python API. It has updated Python to 3.8 while keeping backward compatibility.
  • Superpowered syntax definition. It has improved the syntax highlighting engine a lot e.g inclusion of lazy embeds and syntax inheritance.
  • Typescript, JSX, and TSX support. You are now in a position to utilize all the smart syntax-based features of sublime Text.

Install Sublime Text 4 on Ubuntu 22.04

1. Update system repositories

Before we can begin the installation of Sublime Text 4 on Ubuntu 22.04, we need to update our system repositories in order to make them up to date.

sudo apt update && apt upgrade -y

2. Install Sublime Text 4 dependencies

Sublime Text 4 requires dependencies in order to run effectively such as HTTPs, so we are required to install this if not already installed on your system.

sudo apt install dirmngr gnupg apt-transport-https ca-certificates software-properties-common

3. Install Sublime Text 4 on Ubuntu 22.04

To begin installing Sublime Text, start by installing GPG keys on your system.

wget -qO - https://download.sublimetext.com/sublimehq-pub.gpg | gpg --dearmor | sudo tee /etc/apt/trusted.gpg.d/sublimehq-archive.gpg

When you have successfully added the GPG key add Sublime Text to the apt repository with the following command.

echo "deb https://download.sublimetext.com/ apt/stable/" | sudo tee /etc/apt/sources.list.d/sublime-text.list

Then the next thing is to update the repositories for the changes to take effect and then run the installation afterward.

$ sudo apt update
$ sudo apt install sublime-text

You should be in a position to see the following output

#output
The following NEW packages will be installed:
  sublime-text
0 upgraded, 1 newly installed, 0 to remove and 184 not upgraded.
Need to get 16.4 MB of archives.
After this operation, 50.6 MB of additional disk space will be used.
Get:1 https://download.sublimetext.com apt/stable/ sublime-text 4126 [16.4 MB]
Fetched 16.4 MB in 24s (685 kB/s)                                              
Selecting previously unselected package sublime-text.
(Reading database ... 260078 files and directories currently installed.)
Preparing to unpack .../sublime-text_4126_amd64.deb ...
Unpacking sublime-text (4126) ...
Setting up sublime-text (4126) ...
Processing triggers for mailcap (3.70+nmu1ubuntu1) ...
Processing triggers for desktop-file-utils (0.26-1ubuntu3) ...
Processing triggers for hicolor-icon-theme (0.17-2) ...
Processing triggers for gnome-menus (3.36.0-1ubuntu3) ...

And you have successfully installed Sublime Text on your ubuntu 22.04.

4. Start using Sublime Text

To start using Sublime Text, you can open via the terminal or via the activities in the applications section.

Open Sublime Text on the terminal

$ subl

Open via the activities menu.

show applications >> Search for sublime >> Click on sublime icon

To start using Sublime you can import your existing project or you can create a new project.

Sublime Text 4 interface

To check the version of Sublime Text go to help then about, you will find your number there.

help >> about sublime text
Sublime Text version

The build number is your current version (Build 4126)

Conclusion

Congratulations, you have successfully installed the Sublime Text 4 editor on Ubuntu 22.04. For more information, you can head over to Sublime Text documentation.

How to install go1.19beta on Ubuntu 22.04

In this tutorial, we are going to explore how to install go on Ubuntu 22.04

Golang is an open-source programming language that is easy to learn and use. It is built-in concurrency and has a robust standard library. It is reliable, builds fast, and efficient software that scales fast.

Its concurrency mechanisms make it easy to write programs that get the most out of multicore and networked machines, while its novel-type systems enable flexible and modular program constructions.

Go compiles quickly to machine code and has the convenience of garbage collection and the power of run-time reflection.

In this guide, we are going to learn how to install golang 1.19beta on Ubuntu 22.04.

Go 1.19beta1 is not yet released. There is so much work in progress with all the documentation.

Related Articles

Installing Go 1.19beta on Ubuntu 22.04

1. Run system updates

To begin with, we need to run system updates in order to make our current repositories up to date. To do so we need to run the following command on our terminal.

sudo apt update && apt upgrade -y

When both upgrades and updates are complete, go ahead to download go from its download page.

2. Installing Go

To install go we need to download it from go download page. we are going to download the beta release. We are going to use the curl command to download.

$ wget https://go.dev/dl/go1.19beta1.linux-amd64.tar.gz

when the download is complete, extract the archive downloaded to your desired location. I will be using /usr/local directory.

sudo tar -C /usr/local -xzf go1.19beta1.linux-amd64.tar.gz

After extraction is complete move ahead and set up the go environment.

3. Setting Go Environment

To set up go environment we need to define the root of golang packages. We normally use GOROOT and GOPATH to define that environment. We need to set up the GOROOT location where the packages are installed.

export GOROOT=/usr/local/go

Next, we will need to set up the GOPATH. Let’s set up GOPATH in the $HOME/go directory.

export GOPATH=$HOME/go

Now we need to append the go binary PATH so that we can be able to access the program system-wide. Use the following command.

export PATH=$GOPATH/bin:$GOROOT/bin:$PATH

To apply the changes we have made above, run the following command:

source ~/.bashrc

Lastly, we can do the verification with the following;

$ go version
go version go1.19beta1 linux/amd64

Let’s create a program to check all our settings. We will create a simple one.

Create a file main.go on the main directory.

touch main.go

On your favorite text editor do the following

sudo nano main.go

Insert the below code

$ package main

import "fmt"

func main(){
	fmt.Println("This is go1.19beta1 on Ubuntu 22.04")
}

To run the program use the following command;

$ go run main.go
This is go1.19beta1 on Ubuntu 22.04

Conclusion

Now you know how to install golang 1.19beta in Ubuntu 22.04. You can consult the go documentation in case you have any problems.

How to create Django Templates

In this tutorial, we will learn how to create Django models. We are going to use Django 4.0. In the previous tutorial, we saw how to create your first project. We displayed hello world in our browser.

As a recap of what we saw in the previous lesson, let’s create a new project once more.

On your terminal, we can create a new directory for our project first. Let’s call new_project

$ cd Desktop
$ sudo mkdir new_project
$ cd new_project

When you are inside the new_project folder, now is the time to install Django. As a good practice, I always advise creating a requirements.txt file so that you can store all your installed applications. So to create a requirements.txt file, go to the terminal. Remember we are at the new_project directory.

$ sudo touch requirements.txt

Now that we have the requiremets.txt file, we can now use nano or vim to write into it. I am going to use vim text editor, you can use any you prefer.

sudo vi requirements.txt

Inside django inside this file.

django~=4.0

Create a Virtual Environment

Let’s begin by creating a virtual environment. Use the following code to accomplish that.

$ sudo python3 -m venv myvenv

Myvenv here is the name of our virtual environment.

Then we need to activate our virtual environment before we can begin our project.

source myvenv/bin/activate

Please make sure you see your terminal being prefixed by the name of your terminal like this.

(myvenv) nextgen@zx-pc:~/Desktop/new_project$ 

Install Django

Let’s now install Django using the pip command inside the virtual environment. Remember the requirements.txt we created earlier, it’s now time we use it to install Django.

$ pip install -r requirements.txt
Collecting django
  Using cached Django-4.0.4-py3-none-any.whl (8.0 MB)
Collecting asgiref<4,>=3.4.1
  Using cached asgiref-3.5.2-py3-none-any.whl (22 kB)
Collecting sqlparse>=0.2.2
  Using cached sqlparse-0.4.2-py3-none-any.whl (42 kB)
Installing collected packages: sqlparse, asgiref, django
Successfully installed asgiref-3.5.2 django-4.0.4 sqlparse-0.4.2

Now that we have installed Django successfully, we can proceed to create a project.

Start Django Project

To start a Django project, use the following command inside the virtual environment.

$ django-admin startproject main .

The name of our project is main and please don’t forget the period in the end. It shows that we are creating a project in the current directory.

After we have created the project, we can now move ahead and create Django app

python manage.py startapp products 

The name of the app we are creating is products

Create Django views

A view function is a Python function that takes the web request and returns a web function. Let’s see with an example what we mean.

from django.shortcuts import render

from django.http import HttpResponse


def home_view(request):
    return HttpResponse('<h2>Hello world<h2>')

Inside the products app, we need to create a urls.py file where the routing logic will occur. Add this file and proceed.

from django.urls import path
from . views import home_view

urlpatterns = [
    path('', home_view, name='home'),
]

Go to main/urls.py file and create the following

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('products.urls')),
]

The next thing we need to do is to add our product name inside the settings.py file. Under installed apps, we need to add products app there like this.

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'products.apps.ProductsConfig',# add this file 
]

To run our app use the following command inside the root of your django project. Here root is where you are having manage.py file.

$ python manage.py runserver

This is what we are going to see.

System check identified no issues (0 silenced).

You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
May 24, 2022 - 18:02:56
Django version 4.0.4, using settings 'main.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

Don’t worry about unapplied migrations we will deal with that in a while. Open your browser and use this http://127.0.0.1:8000/ to open our development server.

django view

Hurray! We have run our first Django program. If you are getting what you can see above, then we can proceed.

Creating Templates

From what we have created so far lies one big problem, here we are not in a position to render templates meaning we are not in a position to scale our project. What we ought to do is make use of templates. Here templates I mean make use of HTML files. Let’s see how we can implement this.

From the views.py file, we have what we have created above, I want us to delete return HttpResponse(‘<h1> Hello world </h1>’) and use return render(request, ‘html’)

from django.http import HttpResponse
from django.shortcuts import render


def home_view(request):
    return render(request, 'products/index.html')# add this file 

We need first to create a template file inside our products app. To do that, go to the products folder and create another folder and call it templates, make sure you spelled it correctly. Inside templates create an index.html file.

templates

Before we can write anything inside the index.html file, we need first to move to the settings.py file and add our template path

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            BASE_DIR / 'templates' # add this file 
        ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

First, let’s apply those unapplied migrations with the following command. This will populate our database.

$ python manage.py migrate
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying admin.0003_logentry_add_action_flag_choices... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying auth.0010_alter_group_name_max_length... OK
  Applying auth.0011_update_proxy_permissions... OK
  Applying auth.0012_alter_user_first_name_max_length... OK
  Applying sessions.0001_initial... OK

Run python manage.py runserver again and open your browser.

Django using template

We have arrived at the same thing but this time using template form.

In the next lesson, we are going to see how to perform CRUD operations using Django.

How to install go 1.18 on Fedora 36

Golang is an open-source programming language that is easy to learn and use. It is built-in concurrency and has a robust standard library. It is reliable, builds fast, and efficient software that scales fast.

Its concurrency mechanisms make it easy to write programs that get the most out of multicore and networked machines, while its novel-type systems enable flexible and modular program constructions.

Go compiles quickly to machine code and has the convenience of garbage collection and the power of run-time reflection.

In this guide, we are going to learn how to install golang 1.18 on Fedora 36.

There is so much work in progress with all the documentation so keep checking the go documentation for any changes.

The changes that have been introduced are the following:

  • Go 1.18 includes an implementation of generic features. This includes backward-compatibility changes to the language.
  • The syntax for function and type declarations now accepts type parameters.
  • Parameterized functions and types can be instantiated by following them with a list of type arguments in square brackets.
  • The syntax for interface types now permits the embedding of arbitrary types and unions.
  • The new predeclared identifier is an alias for the empty interface. It may be used instead of interface {}.
  • The go 1.18 compiler now correctly reports declared but not used errors for variables that are set inside a function literal but are never used.
  • The go 1.18 compiler now reports an overflow when passing a rune constant expression.
  • Go 1.18 introduces the new GOAMD64 environment variable which selects a version of AMD64 architecture.
  • Go 1.18 get no longer builds or installs packages in the module-aware mod.
  • gofmt now reads and formats input files concurrently with a memory limit proportional GOMAXPROCS.
  • The vet tool is updated to support generic code.
  • The garbage collector now includes non-hip sources of garbage collector work when determining how frequently to run.

Related Articles

Installing Go 1.18 on Ubuntu 20.04

1. Run system updates

To begin with, we need to run system updates in order to make our current repositories up to date. To do so we need to run the following command on our terminal.

sudo dnf update -y

When updates are complete, go ahead to download go from its download page.

2. Installing Go

To install go we need to download it from go download page. we are going to download the beta release. We are going to use the curl command to download.

$ curl -LO https://go.dev/dl/go1.18.2.linux-amd64.tar.gz

when the download is complete, extract the archive downloaded to your desired location. I will be using /usr/local directory.

$ sudo tar -C /usr/local -xzf go1.18.2.linux-amd64.tar.gz

After extraction is complete move ahead and set up the go environment.

3. Setting Go Environment

To set up go environment we need to define the root of golang packages. We normally use GOROOT and GOPATH to define that environment. We need to set up the GOROOT location where the packages are installed.

$ export GOROOT=/usr/local/go

Next, we will need to set up the GOPATH. Let’s set up GOPATH in the $HOME/go directory.

$ export GOPATH=$HOME/go

Now we need to append the go binary PATH so that we can access the program system-wide. Use the following command.

$ export PATH=$GOPATH/bin:$GOROOT/bin:$PATH

To apply the changes we have made above, run the following command:

source ~/.bashrc

Lastly, we can do the verification with the following;

go version
go version go1.18.2 linux/amd64

Let’s create a program to check all our settings. We will create a simple one.

Create a file main.go on the main directory.

touch main.go

On your favorite text editor do the following

sudo vi main.go

Insert the below code

$ package main

import "fmt"

func main(){
	fmt.Println("Hello Fedora 36")
}

To run the program use the following command;

go run main.go
Hello Fedora 36

Conclusion

Now you know how to install golang 1.18 in Fedora 36. You can consult the go documentation in case you have any problems.

How to set up a Python Django Application using Django 4.0

Django is a backend development language, it is a language for perfectionists. This is called so because it gives you many components out of blue. Whenever you want to develop an application, Django is the go-to language.

To start using Django, you need to be well conversant with Python language first. Begin by knowing all Python-related stuff such as variables, how to do looping in python, tuples, and dictionaries because this is what you encounter every time while working with Django.

In this tutorial, I will take you through setting the Python Django project. The easiest way to do what I usually use is using Pycharm text editor.

Steps to follow:

Step 1: Open Pycharm text editor.

On the upper left corner click on file->New project->Name of the project->create

file->New project->Name of the project->create

Here Pycharm automatically creates a project for you.

Alternatively, you can create a virtual environment on your terminal using this process: How to install Python Django on Ubuntu 20.04

Step 2: Creating a Project

Creating a project is the easiest part, first install Django using the following command on the build-in terminal on Pycharm.

$pip install django~=4.0
Collecting django
  Using cached Django-4.0.4-py3-none-any.whl (8.0 MB)
Collecting asgiref<4,>=3.4.1
  Using cached asgiref-3.5.1-py3-none-any.whl (22 kB)
Collecting sqlparse>=0.2.2
  Using cached sqlparse-0.4.2-py3-none-any.whl (42 kB)
Installing collected packages: sqlparse, asgiref, django
Successfully installed asgiref-3.5.1 django-4.0.4 sqlparse-0.4.2

You can check the version of Django using this command.

$ python -m django --version
4.0.4

Next is to start your project.

On your command line use the following to start a new project.

django-admin startproject myproject .

Make use of the period at the end, it is necessary because it’s instructing that the project be created in the current directory.

If you do an ls inside the project directory, you should see the following:

$ls
manage.py  myproject

Inside my project, this should be what you can find inside

asgi.py  __init__.py  settings.py  urls.py  wsgi.py

Step 3: Start development server

When you are satisfied with your setup, start the development server while inside the root of the Django project. The root of the Django project is the directory where manage.py is located. in our case its inside myproject folder.

nextgentips-Root of Django project

Use the following command to run the development server.

$ python manage.py runserver

This will start the development server and you will the following from your terminal.


System check identified no issues (0 silenced).

You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
May 03, 2022 - 18:39:21
Django version 4.0.4, using settings 'myproject.settings'
Starting development server at http://127.0.0.1:8000/

Don’t worry about the 18 unapplied migrations, we will fix those in a moment. Look the development server will run at port 8000 on our localhost. Copy that URL and paste it into your browser. This is what you will get.

Nextgentips-development server

Step 4: Creating an App

Whenever you are creating a project, there are modules that contain the element you want to implement. Let’s say you want to create an e-commerce website, you will want to divide your project into tiny modules called apps. For example, you will create a products app, cart app, customer app, etc. This will make your project more convenient and elegant.

So to create an app use the following command inside the root of your Django project.

python manage.py startapp product

Product is the name of our app in this example.

Inside the created project folder, this is what you will see.

admin.py  apps.py  __init__.py  migrations  models.py  tests.py  views.py

This will be the directory structure

nextgentips-directory structure

Step 5: Creating your first view

As you can see from the screenshot above, we have views.py. Click on it, this is where you will write your logic. Inside your view insert the following code.

from django.shortcuts import render

from django.http import HttpResponse


def home_view(request):
    return HttpResponse('<h2>Hello world<h2>')

I want you to create another file called URLs inside your app, then you will need to insert the following in that urls.py

product/urls.py

from django.urls import path


from .views import home_view

urlpatterns = [
    path('', home_view, name='home')
]

Then on the myproject/urls.py insert the following:

from django.contrib import admin
from django.urls import path, include 

urlpatterns = [
    path('', include('product.urls')),
    path('admin/', admin.site.urls),
]

On the settings.py you need to register your app. Go to settings.py->installed_apps->AddYour app name in our case its product.

Go to settings.py->installed_apps->'product.apps.ProductConfig'

Refresh your browser and you will see Hello world printed on your screen.

Hello world

In the next lesson, we will see how to create a project using templates and how to do our first database migration.

How to install Go 1.18 on Ubuntu 22.04

In this tutorial, we are going to explore how to install go on Ubuntu 22.04

Golang is an open-source programming language that is easy to learn and use. It is built-in concurrency and has a robust standard library. It is reliable, builds fast, and efficient software that scales fast.

Its concurrency mechanisms make it easy to write programs that get the most out of multicore and networked machines, while its novel-type systems enable flexible and modular program constructions.

Go compiles quickly to machine code and has the convenience of garbage collection and the power of run-time reflection.

In this guide, we are going to learn how to install golang 1.18 on Ubuntu 22.04.

Go is not yet released. There is so much work in progress with all the documentation.

The changes that have been introduced are the following:

  • Go 1.18 includes an implementation of generic features. This include backward-compatibity changes to the language.
  • The syntax for function and type declarations now accepts type parameters.
  • Parameterized functions and types can be instatiated by following them with a list of type arguments in square brackets.
  • the syntax for interface types now permits the embedding of arbitrary types as well as union.
  • The new predeclared identifier any is an alias for the empty interface. It maybe used instaead of interface {}.
  • The go 1.18 compiler now correctly reports declared but not used errors for variables that are set inside a function literal but are never used.
  • The go 1.18 compiler now reports an overflow when passing a rune constant expression.
  • Go 1.18 introduces the new GOAMD64 environment variable which selects a version of AMD64 architecture.
  • Go get no longer builds or install packages in module-aware mod.
  • gofmt now reads and formats input files concurrently with a memory limit proportional GOMAXPROCS.
  • The vet tool is updated to support generic code.
  • The garbage collector now includes non-hip sources of garbage colector work when determining how frequently to run.

Related Articles

Installing Go 1.18 on Ubuntu 20.04

1. Run system updates

To begin with, we need to run system updates in order to make our current repositories up to date. To do so we need to run the following command on our terminal.

sudo apt update && apt upgrade -y

When both upgrades and updates are complete, go ahead to download go from its download page.

2. Installing Go

To install go we need to download it from go download page. we are going to download the beta release. We are going to use the curl command to download.

curl -LO https://go.dev/dl/go1.18beta1.linux-amd64.tar.gz

when the download is complete, extract the archive downloaded to your desired location. I will be using /usr/local directory.

sudo tar -C /usr/local -xzf go1.18beta1.linux-amd64.tar.gz

After extraction is complete move ahead and set up the go environment.

3. Setting Go Environment

To set up go environment we need to define the root of golang packages. We normally use GOROOT and GOPATH to define that environment. We need to set up the GOROOT location where the packages are installed.

export GOROOT=/usr/local/go

Next, we will need to set up the GOPATH. Let’s set up GOPATH in the $HOME/go directory.

export GOPATH=$HOME/go

Now we need to append the go binary PATH so that we can be able to access the program system-wide. Use the following command.

export PATH=$GOPATH/bin:$GOROOT/bin:$PATH

To apply the changes we have made above, run the following command:

source ~/.bashrc

Lastly, we can do the verification with the following;

go version
go version go1.18beta1 linux/amd64

Let’s create a program to check all our settings. We will create a simple one.

Create a file main.go on the main directory.

touch main.go

On your favorite text editor do the following

sudo nano main.go

Insert the below code

$ package main

import "fmt"

func main(){
	fmt.Println("Hello Nextgentips")
}

To run the program use the following command;

go run main.go
Hello Nextgentips

Conclusion

Now you know how to install golang 1.18 in Ubuntu 20.04. You can consult the go documentation in case you have any problems.