Fahmida Yesmin – Linux Hint https://linuxhint.com Exploring and Master Linux Ecosystem Wed, 10 Mar 2021 03:31:26 +0000 en-US hourly 1 https://wordpress.org/?v=5.6.2 How to Create Django Views? https://linuxhint.com/create-django-views/ Tue, 09 Mar 2021 05:32:51 +0000 https://linuxhint.com/?p=93540 Different types of data of Django application, such as HTML content, XML data, JSON data, image, 404 error, etc. are transferred to the template through Django view. Each view is created for a specific purpose and associated with a particular template. The data of the view can be generated from the user through HTML form or from the database or business logic. Django views can be created using a method of python class or python function. The class-based views contain many functionalities compared to function-based views. For this, most of the Django applications use class-based views to represent the data of the Django application. The ways of creating the function-based view and class-based view have been explained in this tutorial.

Prerequisites:

Before practicing the examples of this tutorial, you have to complete the following tasks:

  1. Install the Django version 3+ on Ubuntu 20+ (preferably)
  2. Create a Django project
  3. Run the Django server to check whether the server is working properly or not

Setup a Django App:

A. To create a Django app named viewapp, run the following command:

$ python3 manage.py startapp viewapp

B. To create the user for accessing the Django database, run the following command. If you have created the user before then skip this part:

$ python3 manage.py createsuperuser

C. Add the app name in the INSTALLED_APP part of the settings.py file.

INSTALLED_APPS = [
    …..
    'viewapp'
]

D. Create a folder named templates inside the viewapp folder and set the template’s location of the app in the TEMPLATES part of the settings.py file.

TEMPLATES = [
    {
      ….
            'DIRS': ['/home/fahmida/django_pro/viewapp/templates'],
             ….
      },
]

Create a Simple function-based View:

Open the views.py file from the viewapp folder and replace the content of this file with the following script. index() function is used in the script to create the HTML content that will be sent to the browser using the HttpResponse() method. Here, the current date and time of the system will be read using the today() function and the current date value will be generated before sending to the browser.

Views.py

# Import the date module to read the current date
from datetime import date
# Import the HttpResponse module to send data from view to template
from django.http import HttpResponse

# Define function to create function-based view
def index(request):
    # Read the current date
    today = date.today()
    # Set static data for the view
    content = "<center><h1 style='color:green'>Welcome to LinuxHint</h1><h2>"
    content += "Today is " + today.strftime("%B") + " " + today.strftime("%d") + ", " + str(today.year) + "</h2></center>"
    # Sent the content to the browser
    return HttpResponse(content)

Modify the content of the urls.py file with the following script. In the script, the ‘welcome/’ path is defined to call the index() function that will send the HTML content to the template file.

urls.py

# Import path module
from django.urls import path
# Import view module
from viewapp import views

# Call index method to display the content
urlpatterns = [
   # Define path to call index() function
    path('welcome/', views.index)
]

Run the following URL from the browser that will show the following output. A formatted headline text and the current date value are shown in the output.

http://localhost:8000/welcome/

Create a Simple class-based View:

Create a views2.py file inside the viewapp folder and add the following script. MyView class is defined in the script that contains a method named get(). A list variable named listdata is declared in the script to create a list of 10 random numbers. The values of the list will be passed to the template through the HttpResponse() method when this view is called. the random module has been used in the script to generate a random integer number in each iteration of the for loop using the randint() function.

views2.py

# Import the HttpResponse module to send data from view to template
from django.http import HttpResponse
# Import view module
from django.views import View
# Import random module
import random

# Define class for class-based views
class MyView(View):

    def get(self, request):
        # Declare the list variable
        listdata = []
        # Add the first element of the list
        listdata.append('<center><h2>he list of 10 random numbers are:</h2>')
        # Iterate the loop for 10 times
        for n in range(10):
            # Generate a random number within 1 to 50
            random_number = random.randint(1, 50)
            # Add the random number in the list
            listdata.append(random_number)
            # Add a break element in the list
            listdata.append('<br/>')
        # Add the last element of the list
        listdata.append('</center>')
        # Send the list values to the browser
        return HttpResponse(listdata)

Modify the content of the urls.py file with the following script. In the script, the “number/” path is defined to call the MyView.as_view() method that will send the data of the list to the template file.

urls.py

# Import path module
from django.urls import path
# Import view module
from viewapp import views
# Import MyView class
from viewapp.views2 import MyView

# Call the get method of MyView class
urlpatterns = [
   # Define  path to call index() function
   path('welcome/', views.index),
   # Define path to call MyView.as_view() method
    path('number/', MyView.as_view()),
]

Run the following URL from the browser that will show the following output. The numbers of the output will be changed if the page is refreshed because each number of the list will be generated randomly.

http://localhost:8000/number/

Conclusion:

The output of the web application depends on the script of the view file that is a major part of any web application. Function-based views are mostly used in the early version of the Django app and now class-based vies are used in most applications of Django. The ways of creating both types of views have been shown in this tutorial to help the new Django users create their views based on their application.

]]>
How To Use Django Logging? https://linuxhint.com/how-to-use-django-logging/ Sat, 06 Mar 2021 17:05:44 +0000 https://linuxhint.com/?p=93026 Every programmer faces errors when writing code for developing any application. The debugging is used by the coder to solve the errors of the application. Its logging feature makes the debugging process easier by saving the output of error, warning, and information messages into a file. These messages help the coders to keep track of the events, understand the reason for the unwanted output, and modify the code properly for creating an error-free application. Python has a built-in logging module to perform logging-related tasks more efficiently. Django is a popular python framework that uses the python built-in logging module for debugging purposes. How the python logging module can be used in the Django application for debugging purposes will be explained in this tutorial.

Different parts of Django Logging

Django logging contains four types of configurations which are explained below.

1. Django Logger
The logger records the events when the application is executed, and the logging is called. The log entries are stored in a file by categorizing them in different log levels. Every log level indicates the severity of the events. The purposes of these log levels are mentioned below:

  1. DEBUG
    It provides low-level system information for debugging.
  1. INFO
    It provides general information.
  1. ERROR
    It provides information about the major problem of the application.
  1. WARNING
    It provides information about the minor problem of the application.
  1. CRITICAL
    It provides information about the critical problem of the application.

2. Django Handler
The main task of the handler is to transmit the log information that is stored in the log file. The logging module contains many types of handlers and multiple of them can be defined for the same logger.

3. Django Formatter
It is used to format the log data. The data of the handler cannot be sent directly to the log file and the handler data requires it to be converted by using the formatter before sending. The formatter converts the log records into the string. The format of the data depends on the business logic of the handler.

4. Django Filter
It is used to filter the log messages. It is unnecessary to store all log messages into the log file. Different handlers can be used for different messages and the required log messages can be filtered using the required filters.

Prerequisites

Before practicing the script of this tutorial, you must complete the following tasks:

  1. Install the Django version 3+ on Ubuntu 20+ (preferably)
  2. Create a Django project
  3. Run the Django server to check the server is working properly or not.

Setup a Django app

  1. Run the following command to create a Django app named logapp.
$ python3 manage.py startapp logapp
  1. Run the following command to create the user for accessing the Django database. If you have created the user before then don’t need to run the command.
$ python3 manage.py createsuperuser
  1. Add the app name in the INSTALLED_APP part of the py file.
INSTALLED_APPS = [
    …..
    'logapp'
]

Set the Logging Information in settings.py

Open the settings.py file from the Django project folder and add the following content to define the logging information. The properties of the handlers and loggers are set here. According to the logging property values, DEBUG level logging information will be stored in a log file named djangoapp.log when the Django app will be executed.

# Django Logging Information
LOGGING = {
    # Define the logging version
    'version': 1,
    # Enable the existing loggers
    'disable_existing_loggers': False,

    # Define the handlers
    'handlers': {
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': 'djangoapp.log',
        },

        'console': {
            'class': 'logging.StreamHandler',
        },
    },

   # Define the loggers
    'loggers': {
        'django': {
            'handlers': ['file'],
            'level': 'DEBUG',
            'propagate': True,

        },
    },
}

Open the djangoapp.log file to check log entries are stored in the file or not.

Set the Logging Information in views.py

Logging information can be defined using the view file also. Open the views.py file from the logapp folder and replace the content with the following script. In this script, formatters, handlers, and loggers parts of Django logging are defined in the config.dictConfig() method. DEBUG level logging information will be stored in a log file named djangoapp.log and will be printed in the console when the Django app will be executed. index() function is used to send a simple headline text to the browser and the display_log() function is defined to send a simple text in the terminal and a headline text to the browser.

views.py

# Import the logging module
import logging
# Import HttpResponse to send data to the browser
from django.http import HttpResponse

# Define the logging configurations
logging.config.dictConfig({
   # Define the logging version
    'version': 1,
    # Enable the existing loggers
    'disable_existing_loggers': False,
   
   # Define the formatters
    'formatters': {
        'console': {
            'format': '%(message)s'
        },
        'file': {
            'format': '%(message)s'
        },
   
   # Define the handlers
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
            'formatter': 'console'
        },
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'formatter': 'file',
            'filename': 'djangoapp.log'
        }
    },
   
   # Define the loggers
    'loggers': {
        'django': {
            'level': 'DEBUG',
            'handlers': ['file', 'console'],

        }
    }
}

})

# Create the loggers object
logger = logging.getLogger('__name__')

# Define the  function for the index page
def index(request):
    return HttpResponse("<h1 style='color:blue'>This is a Django Application</h1>")

# Define the  function for the log page
def display_log(request):
    # Send the Test!! log message to standard out
    logger.error("Testing Django log...")
    return HttpResponse("<h1 style='color:Red'>Django Logging Message</h1>")

Modify the content of the urls.py file with the following script. In the script, the empty path(”) path is defined to call the index() function of the views and the ‘log/’ path is used to call the display_log() function of the views.

urls.py

from django.urls import path
from logapp import views

urlpatterns = [
    path('', views.index),
    path('log/', views.display_log)
]

Run the following URL to display the index page.

http://localhost:8000

Run the following URL to call the display_log() method that will display a text message in the browser and a text message in the terminal. Log entries will be appended in the djangoapp.log file.

Conclusion

Two ways of using python logging in the Django application to keep the DEBUG level logging information are shown in this tutorial. The basic concept regarding Django logging is expected to be understood by the readers after reading this tutorial.

]]>
How to Filter Data in Django? https://linuxhint.com/filter-data-in-django/ Fri, 05 Mar 2021 14:05:48 +0000 https://linuxhint.com/?p=92969 It is a very common requirement for the web application to display data on the web page based on the user’s interest. The searching feature of the application makes it more user-friendly.  Django framework has a built-in filter() method to filter data from the database tables. A table can contain many records and sometimes determining some specific data are required based on the particular criteria. This task becomes easier by using the filter() method in different ways. How the data from a database table can be filtered using the filter method in four different ways will be discussed in this tutorial.

Prerequisites

Before practicing the examples of this tutorial, you must complete the following tasks:

  1. Install the Django version 3+ on Ubuntu 20+ (preferably)
  2. Create a Django project
  3. Run the Django server to check the server is working properly or not.

Setup a Django App

A. Run the following command to create a Django app named filterapp.

$ python3 manage.py startapp filterapp

B. Run the following command to create the user for accessing the Django database. If you have created the user before then don’t need to run the command.

$ python3 manage.py createsuperuser

C. Add the app name in the INSTALLED_APP part of the py file.

INSTALLED_APPS = [
    …..
    'filterapp'
]

D. Create a folder named templates inside the filterapp folder and set the template’s location of the app in the TEMPLATES part of the py file.

TEMPLATES = [
    {
….
            'DIRS': ['/home/fahmida/django_pro/filterapp/templates'],
             ….
      },
]

Create a Model for the Database Table

Open the models.py file from the filterapp folder and add the following script to define the structure of employees tables. Employee class is defined to create a table named employees with name, post, email, department, and joining_date fields. Here, name, post, and department fields will store character data, the email field will store the email address and the joining_date field will store date data.

models.py

# Import models module
from django.db import models

# Define class to create employees table
class Employee(models.Model):
    name = models.CharField(max_length=50)
    post = models.CharField(max_length=40)
    email = models.EmailField()
    department = models.CharField(max_length=30)
    joinning_date = models.DateField()

Run the makemigrations command to create a new migration based on the changes made by the models.

$ python3 manage.py makemigrations filterapp

Run the migrate command to execute the SQL commands and create all tables in the database that are defined in the models.py file.

$ python3 manage.py migrate

Modify the content of the admin.py file with the following content. Here, the Employee class of the models is registered using the register() method to display the records of employees tables in the Django administration dashboard.

admin.py

# Import admin module
from django.contrib import admin
# Import Employee model
from .models import Employee

# Register employee model
admin.site.register(Employee)

Run the following URL to open the Django admin login page. Provide the valid username and password to open the Django Administration Dashboard to access the database tables.

Insert two or more Employee records to apply the filter on the data. Here five records are inserted.

Create the search.html file inside the filterapp/templates/ folder with the following script. The data from the employee table will be displayed in this template file. for loop is used to read the content of the object_list variable that will be passed from the view file. The name, post, and department values of the employees table will be displayed by using the list.

search.html

    <title>
        Django Filter Tutorial
    </title>




<h1 style="margin-left:20px">Employee List</h1>

<ol>
  {% for emp in object_list %}
    <li>
        <p style="font-size:20px"><b>{{ emp.name }}</b> ({{ emp.post }})</p>
        <p style="font-size:18px">{{ emp.department }} department</p>
    </li>
  {% endfor %}
</ol>

Open the views.py file from the filterapp folder and modify the content of the file with the following script. Model and template names are defined in the script.

views.py

# Import ListView module
from django.views.generic import ListView
# Import Employee module
from .models import Employee
# Import Q module
from django.db.models import Q

# Define class for filtering data
class SearchEmployee(ListView):
    # Define model
    model = Employee
    # Define template
    template_name = 'search.html'

Modify the content of the urls.py file with the following content. In the script, the ‘searchEmp’ path is defined to call the SearchEmployee.as_view() method that will send all data and the filtered data of the employees table to the template file.

urls.py

# Import admin module
from django.contrib import admin
# Import path and include module
from django.urls import path, include
# Import SearchEmployee module
from filterapp.views import SearchEmployee

urlpatterns = [
    # Define the path for admin
    path('admin/', admin.site.urls),
    # Define the path for search
    path('searchEmp/', SearchEmployee.as_view()),
]

The following output will appear without applying any filtering for the following URL.

http://localhost:8000/SerachEmp

Filter Data by Simple Filtering

Add the following line at the end of the views.py file to filter the records of the employees table where the value of the post field is ‘Accountant’.

# Apply basic filtering
queryset = Employee.objects.filter(post ='Accountant')

The following output will appear after applying basic filtering.

Filter Data with Multiple Fields

Add the following line at the end of the views.py file to filter the records of the employees table where the value of the department field is ‘HT’ and the email field is [email protected].

# Apply filtering with multiple fields
queryset = Employee.objects.filter(department='HR', email='[email protected]')

The following output will appear after applying multiple filtering.

Filter Data with Q Object

Add the following line at the end of the views.py file to filter the records of the employees table where the value of the post field is ‘Manager’ or the value of the department field is ‘Sales’.

# Apply filtering by using Q objects
queryset = Employee.objects.filter( Q(post='Manager') | Q(department='Sales'))

The following output will appear after applying Q object filtering.

Filter Data by Using Filter Chaining

Add the following line at the end of the views.py file to filter the records of the employees table where the value of the department field will be checked first and if it returns true then the value of the name field will be checked.

# Apply filtering by chaining
queryset = Employee.objects.filter(department='HR').filter(name='Mehrab Hossain')

The following output will appear after applying filter chaining.

Conclusion

The data can be filtered in Django in many ways based on the application requirements. Four different ways of filtering were explained in this tutorial to understand the basics of Django filtering. These are simple filtering, multiple filtering, filtering with Q object, and filter chaining.

]]>
How to Create Django Templates? https://linuxhint.com/how-to-create-django-templates/ Fri, 05 Mar 2021 10:18:13 +0000 https://linuxhint.com/?p=92885 A template contains HTML data that is generated from a view and displayed in the browser. The static and dynamic HTML pages can be created using the template. Logic and design have been kept separately in the Django application. Python code can’t be used directly in the Django template because the browser can’t interpret the python code. The designer can design the HTML pages only with the necessary format or styling, and the coder adds the static or dynamic data into the template using Django Template Language (DTL).

How the Django template can be created and how the DTL can be used to add static or dynamic content to the template have been shown in this tutorial.

Advantages of using DTL:

There are many benefits of using DTL in Django templates. Some of them are mentioned below.

  1. The logical part and the presentational part of the application are created separately.
  2. It becomes easier to extend the application.
  3. It helps reduce the redundancy of the data.
  4. It assures the application’s security.

Prerequisites:

Before practicing the script of this tutorial, you have to complete the following tasks:

  1. Install the Django version 3+ on Ubuntu 20+ (preferably)
  2. Create a Django project
  3. Run the Django server to check whether the server is working properly or not

Setup a Django app:

Run the following command to create a Django app named tempapp:

$ python3 manage.py startapp tempapp

Run the following command to create the user for accessing the Django database, but if you have created the user before, then don’t need to run the command shown below:

$ python3 manage.py createsuperuser

Add the app name in the INSTALLED_APP part of the settings.py file, as shown below:

INSTALLED_APPS = [
    …..
    'tempapp'
]

Create a folder named templates inside the tempapp folder and set the template’s location of the app in the TEMPLATES part of the settings.py file, as shown below:

TEMPLATES = [
    {
….
            'DIRS': ['/home/fahmida/django_pro/tempapp/templates'],
             ….
      },
]

Create a Simple Django Template:

Create the index.html file inside the tempapp/templates/ folder with the following HTML script to display the formatted static text of two lines in the browser. HTML file can’t be displayed directly in the browser and the views.py file is used to render the HTML file in the Django application.

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Django Tutorials</title>
</head>
<body>
  <center>
    <h1 style="color:blue">Learn Django Template Language</h1>
    <p style="font-size:20px; color:red">Django is popular python framework to design web application</p>
  </center>
</body>
</html>

Open the views.py file from tempapp folder and add the following script. The rander() method is used in the views.py file to display any template file into the browser.

In the following script, the index() function is defined to display the content of the index.html file. When this function call from the urls.py file, then the template file will be displayed in the browser.

views.py

# Import render module from django
from django.shortcuts import render

# Create index function to display the HTML file into the browser
def index(request):
    return render(request, "index.html")

Modify the content of the urls.py file with the following script. According to the script, the index() function of the views.py will be called for the path, ‘index/’.

urls.py

# Import path module
from django.urls import path
# Import views
from tempapp import views

# Define method for index path
urlpatterns = [
    path('index/', views.index)python3 manage.py createsuperuser

]

Run the following URL from the browser to get the following output. The static data is displayed in the output.

http://localhost:8000/index/

Create a Django Template with DTL:

Create the customers.html file inside the tempapp/templates/ folder with the following HTML script. DTL is used in this script to display the data of the dictionary variable that is initialized by the data of nested lists in the views2.py file. The first for loop is used to read the values of the outer list and the second for loop is used to read the values of the inner list.

customers.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Customer Information</title>
  <style>
   .table, th, tr, td{
   border:1px solid blue;
   }
  </style>
</head>
<body>
 <center>

        <h2>List of Customers</h2>
        <table>
            <tr>
                <th>ID</th><th>Name</th><th>Email</th><th>Phone</th>
            </tr>
            {% for rows in customers %}
            <tr>
                {% for col in rows %}
                <td>{{ col }}</td>
                {% endfor %}
            </tr>
            {% endfor %}
        </table>

 </center>
</body>
</html>

Create another view file named views2.py under tempapp folder with the following script. A dictionary variable named data is declared in the script that contains a nested list to generate tabular data of 4 rows and 4 columns. The data variable will be sent to the template when the customers() function of this script will be called from the urls.py file.

views2.py

# import render module from django
from django.shortcuts import render

# create a function to send tabular data to template
def customers(request):
    # define a dictionary of nested list
    data = {"customers": [['6745', 'Monir Hossain', '[email protected]', '880191345234'],
                          ['7845', 'Keya Akter', '[email protected]', '880189045673'],
                          ['9056', 'Mohammed Ali', '[email protected]', '880179893922'],
                          ['4536', 'Mostafa Kamal', '[email protected]', '880157665433']]
            }

    # return response with template and data
    return render(request, "customers.html", data)

Modify the urls.py file with the following script. ‘customers/’ path is defined in the script to load the customers.html file in the browser with the data of the dictionary.

urls.py

# Import path module
from django.urls import path
# Import views
from tempapp import views
# Import views2
from tempapp import views2

# Define methods for index and customers paths
urlpatterns = [
    path('index/', views.index),
    path('customers/', views2.customers)
]

Run the following URL from the browser to get the following output. The records of all customers from the database tables have been displayed in the browser using the DTL.

http://localhost:8000/customers/

Conclusion:

The ways of creating a simple template and a template with Django Template Language (DTL) have been shown in this tutorial. The new Django users will be able to create the template for the Django app properly after practicing the script of this tutorial.

]]>
How to Create Django Form? https://linuxhint.com/how-to-create-django-form/ Fri, 05 Mar 2021 10:05:53 +0000 https://linuxhint.com/?p=92869 The use of the form is an essential part of any web application. The input from the website users can be taken using the form. It can contain different types of fields, such as text box, combo box, check box, radio button, etc. to take data from the users. Django framework contains a large number of libraries to help the web developer to design an HTML form for taking input from the user, process the input, and respond to the user’s input.

How HTML form can be used to take data from the user, read the input values, and print the values in the browser using Django is shown in this tutorial.

Prerequisites:

You have to create a Django project before creating the Django form. To create a new Django project and go to the project folder, run the following commands:

$ django-admin startproject django_pro
$ cd django_pro

To create necessary files and apply migrations for the project, run the following command:

$ python3 manage.py migrate

To check if the Django server is working properly or not, run the following command:

$ python3 manage.py runserver

To create the formapp under django_pro project, run the following command:

$ python3 manage.py startapp formapp

Create HTML Form Using Django:

Open the views.py file that is inside formapp folder and modify its content with the following content. The following script will check whether the form is submitted or not. If the form is submitted then the value of the request.method will be POST and request.POST.get() method is used to read its submitted values. The is_valid() function will check whether the data of the form is valid or not. If this function returns true, then a success message with the valid user’s data will be printed in the browser, otherwise, the error message that appears on the particular field of the form will be displayed. Other than that, the render() method is used to load the form in the browser and HttpResponse() method is used to send the response from the server to the browser after submitting the form.

# Import necessary modules
from django.shortcuts import render
from formapp.forms import StudentForm
from django.http import HttpResponse


def form_request(request):
    # Check the form is submitted or not
    if request.method == 'POST':
        student = StudentForm(request.POST)
        # Check the form data are valid or not
        if student.is_valid():
            # Read the submitted values
            name = request.POST.get("name")
            email = request.POST.get("email")
            username = request.POST.get("username")
            # Merge the values
            data = ['Your registration is completed successfully.<br />', 'Name:', name, '<br />', 'Email:', email, '<br />', 'Username:', username]
            # Return the form values as response
            return HttpResponse(data)
    else:
        # Display the html form
        student = StudentForm()
        return render(request, "form.html", {'form': student})

Create forms.py inside the formapp folder and add the following content. The following script will create a form of four fields. The name field is defined to take the character data and it can be 40 characters long. The email field is defined to take any valid email address using the character data and it can be 50 characters long. The username field is defined to take the character data, and it can be 20 characters long. The password field is defined to take the character data and it can be a minimum of 10 characters and a maximum of 20 characters long. The forms.PasswordInput widget is used for the password field to hide the content of the password field.

# Import form modules
from django import forms

# Create class to define the form fields
class StudentForm(forms.Form):
    name = forms.CharField(label="Full name", max_length=40)
    email = forms.EmailField(label="Email", max_length=50)
    username = forms.CharField(label="Username", max_length=20)
    password = forms.CharField(label="Password", min_length=10, max_length=20, widget=forms.PasswordInput)

Create a folder named templates inside the formapp folder. Go to the TEMPLATES section of the settings.py file and set the location of the template folder for the DIRS property.

settings.py

TEMPLATES = [
    {
        'DIRS': ['/home/fahmida/django_pro/formapp/templates']
    },
]

Create form.html inside the template folder with the following content.

{% csrf_token %} is used in the HTML script to prevent CSRF(Cross-Site Request Forgeries) attacks. {{ form.as_p }} will load the Django form that is designed by the forms.py file. When the Submit button is pressed, the form data will be submitted to the server.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>User Registration Form</title>
  </head>
  <body>

  <form method="POST" class="post-form" >
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit" class="save btn btn-default">Submit</button>

  </form>

  </body>

</html>

Open the urls.py from the django_pro folder and modify the content with the following content.

Here, the ‘register/’ path is used to load the form in the browser.

# Import necessary modules
from django.urls import path
from formapp import views

# Call method to display the form
urlpatterns = [
    path('register/', views.form_request)
]

Open any browser and type the following URL to load the user registration form in the browser.

http://localhost:8000/register

The following output will appear after running the URL. The validation for the empty field, the maximum length value of name, email, and password fields, and the minimum and maximum length values of the password field will be checked after submitting the form.

The following output shows that the password field is invalid. According to the form, the length of the password value must be within 10 to 20 characters. 5 characters have been given as input in the following form. For this, the form is showing the error message.

After entering the valid output in every field of the form, the following output will appear.

Conclusion:

The way of creating a very simple user registration form in the Django application has been shown in this tutorial. Django has many methods for creating different types of fields of the form, such as CharField(), EmailField(), TextFiled, etc. The form validation task becomes very easier when the form is designed by Django form.

]]>
How to Use the Model in Django? https://linuxhint.com/use-model-django/ Thu, 04 Mar 2021 12:39:23 +0000 https://linuxhint.com/?p=92828 Model is used in Django application to create a web application with a database. It is a built-in feature of Django to create relational database tables by defining the table structure for the Django project. Each attribute of the model indicates the type of the particular field of the table. A model class will require to define each table of the database. Generally, the name of the model class is defined in the singular form, and Django will create a table name in plural form based on the model class name. Any modifications of the table designed by the model, such as create or update or delete, can be done very easily using the Django admin panel. The same tasks can also be done from the python command line. Creating Django models that will create two relational tables and how they can be accessed using the Django Administration dashboard is shown in this tutorial.

Prerequisites

Before practicing the examples of this tutorial, you have to complete the following tasks.

  1. Install the Django version 3+ on Ubuntu 20+ (preferably)
  2. Create a Django project
  3. Run the Django server to check the server is working properly or not.

Setup a Django app:

Run the following command to create a Django app named model app.

$ python3 manage.py startapp modelapp

Run the following command to create the user for accessing the Django database. If you have created the user before, then you don’t need to run the command.

$ python3 manage.py createsuperuser

Add the app name in the INSTALLED_APP part of the py file.

INSTALLED_APPS = [
    …..
    'model app
]

Create a folder named templates inside the model app folder and set the template’s location of the app in the TEMPLATES part of the py file.

TEMPLATES = [
    {
….
            'DIRS': ['/home/fahmida/django_pro/modelapp/templates'],
             ….
      },
]

Create a model for the database table:

Open the models.py file from the model app folder and add the following script to define the structure of two relational tables. Teacher class is defined to create a table named teachers with name, department, email, and phone fields. Course class is defined to create a table named courses with code, name, credit, and teacher fields. Here, the teacher field of Courses table is the foreign key that will appear from the Teachers table.

models.py

# Import models module
from django.db import models

# Create class to define the structure of Teachers table
class Teacher(models.Model):
    name = models.CharField(max_length=50)
    department = models.CharField(max_length=20)
    email = models.EmailField(max_length=100)
    phone = models.CharField(max_length=50)

# Create class to define the structure of Courses table
class Course(models.Model):
    code = models.CharField(max_length=10)
    name = models.CharField(max_length=50)
    credit = models.FloatField()
    teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE)

Run the makemigrations command to create a new migration based on the changes made by the models.

$ python3 manage.py makemigrations model app

Run the migrate command to execute the SQL commands and create all tables in the database defined in the models.py file.

$ python3 manage.py migrate

Modify the content of the admin.py file with the following content. Here, Teacher and Course classes of the models are registered by using the register() method to display the Teachers and Courses tables in the Django administration dashboard.

admin.py

# Import admin module
from django.contrib import admin

# Import the models
from .models import Teacher
from .models import Course

# Register the models
admin.site.register(Teacher)
admin.site.register(Course)

Set URL for admin login:

The path for admin login is defined in the urls.py file for any Django app by default. If the path is not defined in the file, modify the urls.py file with the following script to open the built-in Django Administration Dashboard for the path’ admin/‘.

urls.py

# Import admin module
from django.contrib import admin
# Import path module
from django.urls import path

# Define the path for admin
urlpatterns = [
    path('admin/', admin.site.urls),
]

Insert records in the tables:

Run the following URL from the browser to open the Django Administration Dashboard.

http://localhost:8000/admin

The following tables will be shown for the model app. Any record of the tables can be read, inserted, updated, and deleted from this page.

Click on the Teachers table to insert some records into the table. A form with the necessary fields like the following image will appear for inserting record. There are three buttons in the form to insert records in the table. ‘Save and add another‘ button is used to insert the record and open the form again for inserting the next record. The ‘Save and continue editing‘ button is used to insert the record and open the form again with the data for editing. The ‘Save‘ button is used to insert the record only. Every entry form will contain these three buttons.

After inserting the two teacher’s records, the following information will appear in the browser.

The following form will appear after clicking on the courses table. The Teacher field of the Courses table is related to the Teachers table by the foreign key. The dropdown list with inserted Teacher objects will appear to add the data in this field from the list.

After inserting three records into the Courses table, the following information will appear in the browser. If you want to modify any records of the Courses or the Teachers table, then click on that particular object to open the edit form with the existing data.

You can display the records of both tables in the browser by using the views.py file and creating the temples in the defined template location.  You can check the Django View and Django Template tutorials for these.

Conclusion

The table data can be accessed or modified by Django Administration Dashboard, as explained in this tutorial. But the data can be inserted into the tables by writing a script in the views.py file with or without using the template file.

]]>
How to Use bulk_create() in Django? https://linuxhint.com/use-bulk-create-in-django/ Tue, 02 Mar 2021 21:27:05 +0000 https://linuxhint.com/?p=92777

Django framework can be used to create a web application with a database by writing script in models.py and views.py files of the Django app. The data can be inserted into the database tables by using Django Administration Dashboard or by writing a script in the views.py file. Django Administration Dashboard requires a login for an authenticated user to access the tables of the database. Single or multiple records can be inserted into the database tables by writing a script. bulk_create() method is one of the ways to insert multiple records in the database table. How the bulk_create() method is used to insert the multiple data in a Django database table will be shown in this tutorial.

Prerequisites:

Before practicing the script of this tutorial, you have to complete the following tasks:

  1. Install the Django version 3+ on Ubuntu 20+ (preferably)
  2. Create a Django project
  3. Run the Django server to check the server is working properly or not

Setup a Django app:

Run the following command to create a Django app named bookapp.

$ python3 manage.py startapp bookapp

Run the following command to create the user to access the Django database. If you already created one, then you don’t need to run the command.

$ python3 manage.py createsuperuser

Add the app name in the INSTALLED_APP part of the settings.py file.

INSTALLED_APPS = [

    …..

    'bookapp'

]

Create a folder named templates inside the bookapp folder and set the template’s location of the app in the TEMPLATES part of the settings.py file.

TEMPLATES = [

    {

….

                'DIRS': ['/home/fahmida/django_pro/bookapp/templates'],

                   ….

      },

]

Create a model for the database table:

Open the models.py file from the bookapp folder and add the following script to define the structure of books tables. Book class is defined to create a table named books with title, author, price, and published_year fields. According to the script, title and author fields will store character data, and price and published_year fields will store the integer data. Here, the title field is defined with the unique attribute. That means that the value of the title field will not accept any duplicate data.

models.py

# Import models module

from django.db import models

# Define the Book class for the books table

class Book(models.Model):


    title = models.CharField(max_length=100, unique=True)

    author = models.CharField(max_length=100)

    price = models.IntegerField()

    published_year = models.IntegerField()

Run the makemigrations command to create a new migration based on the changes made by the models.

$ python3 manage.py makemigrations bookapp

Run the migrate command to execute the SQL commands and create all tables in the database that are defined in the models.py file.

$ python3 manage.py migrate

Modify the content of the admin.py file with the following content. Here, the Book class of the models is registered using the register() method to display the books tables in the Django administration dashboard.

admin.py

# Import admin module

from django.contrib import admin

# Import Book model

from .models import Book

# Register Book model

admin.site.register(Book)

Create a template file named DisplayBookList.html inside the bookapp/templates/ folder with the following script. This script will display all data of books table in tabular form. Other than that, for loop is used in the script to iterate the data passed from the views.py file.

DisplayBookList.html

<html>

<head>

    <title>

        Django bulk_create() Tutorial

    </title>

    <style>

       th { text-align:left; }

       table, th, td { border: 1px solid;}

       h1{ color:Blue;}

       #name{ width:350px;}

    </style>

</head>

<body>

<center><h1 style="margin-left:20px;">Python Book List</h1></center>

<center>

    <table>

       <tr>

            <th>ID</th><th id="name">Name</th><th>Author</th><th>Publication Year</th><th>Price</th>

       </tr>

       {% for book in object_list %}

       <tr>

           <td>{{book.id}} </td> <td>{{book.title}}</td> <td>{{book.author}}</td><td>{{book.published_year}}</td><td style="text-align:right">${{book.price}}</td>

        </tr>

          {% endfor %}


    </table>

</center>

</body>

</html>

Modify the content of the views.py file with the following script. The model and template names are defined in the BulkInsert class. get_queryset() method of the class is defined in the script to return all records of the books table. On the other hand, Book.objects.all() method is used to return all records of the books table. exists() method is used in the script to check the books table is empty or not. If this method returns False then five records will be inserted into the books table using the bulk_create() method.

views.py

from django.shortcuts import render

# Import ListView module

from django.views.generic import ListView

# Import Book model

from .models import Book


# Define class for inserting multiple data

class BulkInsert(ListView):

    # Define model

    model = Book

    # Define template

    template_name = 'DisplayBookList.html'

   # Read all existing records of books table

    queryset = Book.objects.all()

    # Check the books table is empty or not

    if queryset.exists() == False:

       # Insert 5 records in the books table at a time

        Book.objects.bulk_create([

            Book(title='Python Crash Course, 2nd Edition', author='Eric Matthes', price=15, published_year=2019),

            Book(title='Automate the Boring Stuff with Python, 2nd Edition', author='Al Sweigart', price=30,

                  published_year=2019),

            Book(title='Learning Python', author='Mark Lutz', price=15, published_year=2019),

            Book(title='Head First Python', author='Paul Barry', price=45, published_year=2016),

            Book(title='A Byte of Python', author='Swaroop C H', price=15, published_year=2013),


        ])

   

    # Return all records of the books table

    def get_queryset(self):

        # Set the default query set

        return Book.objects.all()

Modify the content of the urls.py file with the following script. In the script, the ‘admin/’ path is defined to open the Django Administration Dashboard and the ‘books/’ path is defined to call the BulkInsert.as_view() method that will insert five records to the books table and return the records to the template file.

urls.py

# Import admin module

from django.contrib import admin

# Import path and include module

from django.urls import path



from bookapp import views



urlpatterns = [

    # Define the path for admin

    path('admin/', admin.site.urls),

    path('books/', views.BulkInsert.as_view()),



]

Open the Django Administration Dashboard to check whether the data is inserted properly or not using the bulk_create() function.

The inserted records of the books table will be displayed in the browser after executing the following URL.

http://localhost:8000/books/

Conclusion:

Multiple records can be inserted into the Django database table in different ways using the bulk_create(). A simple way of inserting multiple records in the database table using this method was shown in this tutorial to help Django users understand the logic behind the process.

]]>
How to Use Django Channel https://linuxhint.com/use-django-channel/ Tue, 02 Mar 2021 14:29:13 +0000 https://linuxhint.com/?p=92505 Django is a popular Python framework used to develop web apps using the WGSI (Web Server Gateway Interface) and ASGI (Asynchronous Server Gateway Interface) server specifications. WGSI is used for developing synchronous Python apps, and AGSI is used for developing asynchronous and synchronous web apps. Channel is a useful feature of Django that is used to handle WebSocket, chat protocol, etc. alongside the HTTP protocol. Channel is built on the ASGI server specifications. A two-way interactive communication session between the user’s browser and the server can be opened using a WebSocket. The client initiates the WebSocket connection and the server responds with an accept or close message. The WebSocket messages are pushed into the channel using producers and sent to the consumers that are listening on the channel. This tutorial shows you how to use channels to handle WebSocket messages.

Prerequisites

Before practicing the script shown in this tutorial, be sure to complete the following tasks.

  • Install Django version 3+ on Ubuntu 20+ (preferably)
  • Create a Django project
  • Run the Django server to check whether the server is working properly

Set Up a Django App

Run the following command to create a Django app named socketapp:

$ python3 manage.py startapp socketapp

Run the following command to install the channel:

$ pip install channels

Add the channels and app name to the INSTALLED_APP part of the settings.py file:

INSTALLED_APPS = [
    …..
     'channels',
     'socketapp'
]

Define the value of ASGI_APPLICATION in the settings.py file:

ASGI_APPLICATION = 'channel_pro.asgi.application'

Create a folder named templates inside the socketapp folder and set the template’s location of the app in the TEMPLATES part of the settings.py file:

TEMPLATES = [
    {
….
            'DIRS': ['/home/fahmida/channel_pro/socketapp/templates'],
             ….
      },
]

The following output will appear in the terminal after running the Django server. The output shows that ASGI/Channels version 3.0.3 is running.

Create a template file named index.html in the defined template location to display the data sent by the WebSocket. The socket object that is created using JavaScript will read the data using the JSON.parse() method, then pass the value into the content of the <h1> tag that contains the ID value, ‘msg.’

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Django Channel Tutorials</title>

  <script>
        socket = new WebSocket("ws://localhost:8000/msg/");
        socket.onmessage = function(e) {

               var data = JSON.parse(e.data);
               document.querySelector('#msg').innerText = data.timeValue;
        }


  </script>

</head>

<body>

  <center>

   <h1 style="color:blue" id ="msg">{{ text }}</h1>

  </center>

</body>

</html>

Modify the views.py file of the socketapp with the following content. The index.html template file will be displayed in the browser with the text variable when the index() method of this script is called from the urls.py file. If no message is transmitted from the socket, then the text ‘LinuxHint’ will be displayed in the browser.

views.py

# Import render module from Django
from django.shortcuts import render

# Create index function to display the HTML file into the browser
def index(request):
    return render(request, "index.html", context={'text': 'LinuxHint'})

Modify the urls.py file of the socketapp with the following content. Two paths are defined in the script: the ‘admin/’ path is used to open the Django Administration Dashboard, and the ‘msg/‘ path is used to read the WebSocket message.

urls.py

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

from socketapp import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('msg/', views.index)
]

When the following URL is executed without defining the consumer and routing files, the HTTP protocol will work and the following output will appear.

http://localhost:8000/msg

Now, create a consumers.py file inside the socketapp folder with the following script. The connect() method of ws_consumer will be used to accept the socket connection, read the current time value every second, and send the current time in JSON format via WebSocket when this method is called from the routing file.

consumers.py

# Import JSON module
import json
# Import WebsocketConsumer
from channels.generic.websocket import WebsocketConsumer
# Import datetime module
from datetime import datetime
# Import  sleep module
from time import sleep


# Define the consumer class to send the data through WebsocketConsumer
class ws_consumer(WebsocketConsumer):
    def connect(self):
        self.accept()
        while(True):
            now = datetime.now()
            self.send(json.dumps({'timeValue': now.strftime("%H:%M:%S")}))
            sleep(1)

Create the routing.py inside the socketapp folder with the following script. The ‘msg/’ path is defined in the script to call the consumer for sending the data to the socket.

routing.py

from django.urls import path
from .consumers import ws_consumer

# Set the path to call the consumer
ws_urlpatterns = [
    path('msg/', ws_consumer.as_asgi())
]

Modify the asgi.py file with the following script. The modules that are required to handle HTTP and WebSocket requests are imported in the script.

asgi.py

# Import os module
import os
# Import get_asgi_application to handle http protocol
from django.core.asgi import get_asgi_application
# Import ProtocolTypeRouter and URLRouter to set the websocket routing
from channels.routing import ProtocolTypeRouter, URLRouter
# Import AuthMiddlewareStack to handle websocket
from channels.auth import  AuthMiddlewareStack
# Import websocket routing
from socketapp.routing import ws_urlpatterns

# Assign value for DJANGO_SETTINGS_MODULE
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'channel_pro.settings')

# Define application variable to handle http and websocket
application = ProtocolTypeRouter({
    'http': get_asgi_application(),
    'websocket': AuthMiddlewareStack(URLRouter(ws_urlpatterns))

})

Now, run the following URL from the browser again to read the data from the WebSocket.

http://localhost:8000/msg/

If the consumer and router are working properly, then the following digital clock will be displayed in the browser. Here, the router has sent the WebSocket request using the ‘msg/‘ path to the consumer that has accepted the request and sent the data to the template to show the digital clock in the browser where the second value of the current time is updating every second.

Conclusion

This tutorial showed you how to implement a real-time application using the Django framework and channels by creating a simple digital clock. Other types of real-time applications can also be implemented using Django and channels, such as online chatting systems. The scripts used in this tutorial work for Django versions 3+ and Channel versions 3+ only. So, if you are using an earlier Django or Channel version, then you will need to upgrade the version before testing the script provided in this tutorial.

]]>
How to use Django Serializers https://linuxhint.com/use-django-serializers/ Wed, 24 Feb 2021 17:17:16 +0000 https://linuxhint.com/?p=91436 Serializer is used in Django to convert the model instances or querysets into python supported data types that can be easily rendered into JSON, XML, or other formats. The deserialization can also be done by serializers to get back the original data from the serialized data. This feature is available in Django REST Framework. So, the users have to install this framework to use the serializers. Any webpage of the website may contain HTML, CSS, and data from the database tables. But the API does not understand these types of content, and it can understand the raw data only, that is, JSON data. How the serializers can be used to convert the model instance into JSON format has shown in this tutorial.

Prerequisites:

Before practicing the script of this tutorial, you have to complete the following tasks.

  1. Install the Django version 3+ on Ubuntu 20+ (preferably)
  2. Create a Django project
  3. Run the Django server to check the server is working properly or not.

Setup a Django app for Serializers:

Run the following command to create a Django app named serialapp.

$ python3 manage.py startapp serialapp

Run the following command to create the user for accessing the Django database. If you have created the user before, then you don’t need to run the command.

$ python3 manage.py createsuperuser

Run the following command to install Django REST Framework.

$ pip3 install djangorestframework

Add the rest_framework and app name in the INSTALLED_APP part of the settings.py file.

INSTALLED_APPS = [
         ….
     'rest_framework',
     'serialapp'
]

Create a model for the database table:

Open the models.py file from the serialapp folder and add the following script to define the structure of customers tables. Customer class is defined to create a table named customers with name, address, email, contact_no, and created fields. Here, name, email, and contact_no fields will store character data, the address field will store the text data, and created field will store the DateTime data.

models.py

# Import the models module
from django.db import models

# Define the model class for the customers table
class Customer(models.Model):

    name = models.CharField(max_length=100)
    address = models.TextField()
    email = models.CharField(max_length=50)
    contact_no = models.CharField(max_length=20)
    created = models.DateTimeField(auto_now_add=True)

Run the makemigrations command to create a new migration based on the changes made by the models.

$ python3 manage.py makemigrations serialapp

Run the migrate command to execute the SQL commands and create all tables in the database defined in the models.py file.

$ python3 manage.py migrate

Modify the content of the admin.py file with the following content. Here, the Customer class of the models is registered by using the register() method to display the customers tables in the Django administration dashboard.

admin.py

# Import admin module
from django.contrib import admin
# Import the Customer model
from .models import Customer
# Register the customer model
admin.site.register(Customer)

urls.py

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

urlpatterns = [
    # Define the path for admin
    path('admin/', admin.site.urls),
]

Add records into the table:

Open the Django Administration page and add some records into the customers table displayed to the browser in JSON format. Here, three records have been inserted.

Modify the views.py:

Open the views.py file from the serialapp and replace the content with the following script. CustomerList class is defined to serialize all the customers’ records and return the data to the browser in JSON format. CustomerDetail class is defined to serialize the particular customer record based on the ID value and return the browser’s data in JSON format. CustomerSerializer is a serializers file that has been created in the next part of this tutorial.

views.py

# Import generics from the Django REST Framework
from rest_framework import generics

# Import Customer model
from .models import Customer

# Import CustomerSerializer from serializers
from .serializers import CustomerSerializer

# Define class to convert all records of the customers table into JSON
class CustomerList(generics.ListCreateAPIView):
    queryset = Customer.objects.all()
    serializer_class = CustomerSerializer

# Define class to convert the particular record of the customers table into JSON
class CustomerDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = Customer.objects.all()
    serializer_class = CustomerSerializer

Create Serializer:

Create serializers.py file in the same location of the views.py file with the following script. ModelSerializer class is used here to create CustomerSerializer class that returns the serializers class with the fields of the Customer model. The Customer model fields that will be converted into JSON format are mentioned in the Meta class.

serializers.py

# Import serializers module from Django REST Framework
from rest_framework import serializers
# Import Customer model
from .models import Customer

# Define the custom serializers class to convert the Customer model fields into JSON
class CustomerSerializer(serializers.ModelSerializer):

    class Meta:
        model = Customer
        fields = ('id', 'name', 'address', 'email', 'contact_no')

Modify the urls.py file:

Modify the content of the urls.py file with the following script. In the script, the ‘customers/‘ path is defined to display all records of the customers table in JSON format, and the ‘customers/<int:pk>/‘ path is defined to display the particular data of the customers table in JSON format based on ID value.

urls.py

# Import admin module
from django.contrib import admin
# Import path and include module
from django.urls import path
# Import the views
from serialapp import views
# Import format_suffix_patterns from Django REST Framework
from rest_framework.urlpatterns import format_suffix_patterns

urlpatterns = [
    # Define the path for admin
    path('admin/', admin.site.urls),
    # Define the path to get all customers data in JSON format
    path('customers/', views.CustomerList.as_view()),
    # Define the path to get the particular customer data based on ID in JSON format
    path('customers//', views.CustomerDetail.as_view()),


]
urlpatterns = format_suffix_patterns(urlpatterns)

All records of the customers table will be shown in JSON format if the following URL will execute.

 

http://localhost:8000/customers

The record of the second customer will be shown in JSON format if the following URL executes.

http://localhost:8000/customers/2

Conclusion:

The use of serializers in the Django application to convert the model instance into JSON format has shown in this tutorial by using a simple script. The Django users will understand the purpose of using serializers and apply them in their application if required after reading this tutorial.

]]>
How to use queryset in django https://linuxhint.com/use-queryset-django/ Wed, 24 Feb 2021 16:53:23 +0000 https://linuxhint.com/?p=91391 Most of the web applications are implemented with the database now. queryset is used in the Django application to retrieve records by filtering or slicing or ordering the database table without changing the original data. The model used Django to create the table in the database. So, the knowledge of using the model in Django is necessary to understand the use of queryset. The main function of the queryset is to iterate the records of database tables by converting them into SQL queries. It can be used from the python command line or by writing the python script to display the browser’s output. The uses of queryset for retrieving data from a database table in different ways have been explained in this tutorial.

Prerequisites:

Before practicing the script of this tutorial, you have to complete the following tasks.

  1. Install the Django version 3+ on Ubuntu 20+ (preferably)
  2. Create a Django project
  3. Run the Django server to check the server is working properly or not.

Setup a Django app:

Run the following command to create a Django app named queryapp.

$ python3 manage.py startapp queryapp

Run the following command to create the user for accessing the Django database. If you have created the user before, then you don’t need to run the command.

$ python3 manage.py createsuperuser

Add the app name in the INSTALLED_APP part of the settings.py file.

INSTALLED_APPS = [
    …..
    'queryapp'
]

Create a folder named templates inside the queryapp folder and set the template’s location of the app in the TEMPLATES part of the settings.py file.

TEMPLATES = [
    {
….
            'DIRS': ['/home/fahmida/django_pro/queryapp/templates'],
             ….
      },
]

Create a model for the database table:

Open the models.py file from the queryapp folder and add the following script to define the structure of products tables. Product class is defined to create a table named products with name, type, brand, and price fields. Here, name, type, and brand fields will store character data, and the price field will store the integer data.

models.py

# Import models module
from django.db import models

# Define class to create products table
class Product(models.Model):
    name = models.CharField(max_length=100)
    type = models.CharField(max_length=30)
    brand = models.CharField(max_length=50)
    price = models.IntegerField()

Run the makemigrations command to create a new migration based on the changes made by the models.

$ python3 manage.py makemigrations queryapp

Run the migrate command to execute the SQL commands and create all tables in the database that are defined in the models.py file.

$ python3 manage.py migrate

Modify the content of the admin.py file with the following content. Here, the models’ Product class is registered by using the register() method to display the products tables in the Django administration dashboard.

admin.py

# Import admin module
from django.contrib import admin
# Import Product model
from .models import Product

# Register Product model
admin.site.register(Product)

Create a template file named productList.html inside the queryapp/templates/ with the following script. This script will display all data of products table in tabular form with a search box. The user will be able to search the particular records from the products table by using the search form. for loop is used in the script to iterate the data passed from the views.py file.

productList.html

<html>
<head>
  <title>
    Django QuerySet Tutorial
  </title>

  <style>
    th { text-align:left; color:blue; }
    table, th, td { border: 1px solid;}
    h1{ color:green;}
    #name{ width:350px;}
  </style>
</head>
<body>
<center><h1 style="margin-left:20px;">Searching Product</h1>
<form method="get" action="">
  {% csrf_token %}
  Search Product: <input name="src" type="text" placeholder="Search..." value="">
</form>
</center>
<center>
  <table>
   <tr>
    <th>ID</th><th id="name">Name</th><th>Brand</th><th>Price</th>
    </tr>
    {% for product in object_list %}
    <tr>
       <td>{{product.id}} </td> <td>{{product.name}}</td> <td>{{product.brand}}</td><td
style="text-align:right">${{product.price}}</td>
    </tr>
    {% endfor %}
  </table>
</center>
</body>
</html>

Modify the content of the views.py file with the following script. The model and template names are defined in the ProductList class. get_queryset() method of the class is defined in the script to filter the data based on the content submitted by the search box of the template. Product.objects.all() method returns all records of the products table. request.GET.keys() method is used in the script to check any data is submitted by the search form. If this method returns true, then the request.GET.get(‘src’) method is used to check the submitted value is empty or not. If this method returns a non-empty value, then the value will be stored in the variable, keyword, and it will be used for filtering the data based on the brand and type fields from the products table.

views.py

# Import ListView module
from django.views.generic import ListView
# Import Product module
from .models import Product
# Import Q module
from django.db.models import Q

# Define class for Querying data
class ProductList(ListView):
    # Define model
    model = Product
    # Define template
    template_name = 'productList.html'


    def get_queryset(self):
        # Set the default query set
        queryset = Product.objects.all()
        # Check the form value is submitted or not
        if self.request.GET.keys():
            # Check the search keyword
            if self.request.GET.get('src') != '':
                keyword = self.request.GET.get('src')
                # Set the query set based on search keyword
                queryset = Product.objects.filter(Q(brand=keyword.capitalize()) | Q(type=keyword.capitalize()))
        return queryset

Modify the content of the urls.py file with the following script. In the script, the ‘searchPro/’ path is defined to call the ProductList.as_view() method that will send all data and the filtered data of the products table to the template file.

urls.py

# Import admin module
from django.contrib import admin
# Import path and include module
from django.urls import path

# Import SearchEmployee module
from queryapp.views import ProductList

urlpatterns = [
    # Define the path for admin
    path('admin/', admin.site.urls),

    # Define the path to search product
    path('searchPro/', ProductList.as_view()),

Add records into the table:

Open the Django Administration page and add some records into the products table to apply the queryset on then. Here, five records have been inserted.

All records of the products with the search box will be displayed in the browser after executing the following URL.

http://localhost:8000/searchPro


All the shampoo products displayed if the product type, ‘shampoo‘ will be searched in the search box.

The milk powder products of the Fresh brand will be displayed if the product brand, ‘fresh‘ will be searched in the search box.

Conclusion:

The way of filtering the data of a simple database table by using queryset has explained in this tutorial. The data can be filtered in different ways. The readers will understand using a queryset to filter or search data in the browser after reading this tutorial.

]]>
How to Use PyQt QTimer https://linuxhint.com/use-pyqt-qtimer/ Sun, 14 Feb 2021 17:19:42 +0000 https://linuxhint.com/?p=89948 The QTimer class of the PyQt library allows users to create a digital clock, time counter, progress bar, and more. This class is used to create a regular timer that sends out a signal when the timer fires and it inherits from the QObject class. The object of the QTimer class is created as a child of a widget. When the widget deletes, the timer object also deletes. The QTimer class provides a static function called singleShot() that can be used to call a function after a specific period. This tutorial shows you how to use the QTimer class to create time-related PyQt applications.

QTimer Usage

The following sections provide examples that illustrate how to implement two different applications using the QTimer class.

Example 1: Create a Stopwatch

The following script will implement a stopwatch application in Python using the QTimer class. This application will count the number of seconds and the number of minutes. Two buttons are used to start, stop, resume, and reset the counter. When the user clicks the Start button, the counter will start counting, and the caption of the Start button will be changed to Stop. When the user clicks the Start button with the caption Stop, the counter will stop temporarily, and the caption of the Start button will be changed to Resume to continue the counter to the next time. When the user clicks the Reset button, all the values of the counter will be initialized to 0.

# Import necessary modules
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *

# Define class to create the stop watch
class StopWatchWindow(QMainWindow):

    def __init__(self):
        # Call the parent constructor
        super().__init__()

        # Set the title of the window
        self.setWindowTitle("Stop Watch using QTimer")
        # Set the geometry for the window
        self.setGeometry(100, 100, 300, 200)

        # Set the necessary variables
        self.counter = 0
        self.minute = '00'
        self.second = '00'
        self.count = '00'
        self.startWatch = False

        # Create label to display the watch
        self.label = QLabel(self)
        # Set geometry for the label
        self.label.setGeometry(100, 40, 150, 70)


        # Create start button
        self.start = QPushButton("Start", self)
        # Set geometry to the start button
        self.start.setGeometry(50, 120, 100, 40)
        # Call start() method when the start button is clicked
        self.start.pressed.connect(self.Start)

        # Create reset button
        resetWatch = QPushButton("Reset", self)
        # Set geometry to the stop button
        resetWatch.setGeometry(160, 120, 100, 40)
        # Call reset() method when the reset button is clicked
        resetWatch.pressed.connect(self.Reset)


        # Create timer object
        timer = QTimer(self)
        # Add a method with the timer
        timer.timeout.connect(self.showCounter)
        # Call start() method to modify the timer value
        timer.start(100)

        # Move the position of the window
        self.move(900, 400)
        # Display the window
        self.show()

    # Define a method to modify the values of minutes and seconds based on the timer value
    def showCounter(self):
        # Check the value of startWatch  variable to start or stop the Stop Watch
        if self.startWatch:
            # Increment counter by 1
            self.counter += 1

            # Count and set the time counter value
            cnt = int((self.counter/10 - int(self.counter/10))*10)
            self.count = '0' + str(cnt)

            # Set the second value
            if int(self.counter/10) < 10 :
                self.second = '0' + str(int(self.counter / 10))
            else:
                self.second = str(int(self.counter / 10))
                # Set the minute value
                if self.counter / 10 == 60.0 :
                    self.second == '00'
                    self.counter = 0
                    min = int(self.minute) + 1
                    if min < 10 :
                        self.minute = '0' + str(min)
                    else:
                        self.minute = str(min)


        # Merge the mintue, second and count values
        text = self.minute + ':' + self.second + ':' + self.count
        # Display the stop watch values in the label
        self.label.setText('<h1 style="color:blue">' + text + '</h1>')

    # Define method to handle the start button
    def Start(self):
        # Set the caption of the start button based on previous caption
        if self.start.text() == 'Stop':
            self.start.setText('Resume')
            self.startWatch = False
        else:
            # making startWatch to true
            self.startWatch = True
            self.start.setText('Stop')

    # Define method to handle the reset button
    def Reset(self):
        self.startWatch = False
        # Reset all counter variables
        self.counter = 0
        self.minute = '00'
        self.second = '00'
        self.count = '00'
        # Set the initial values for the stop watch
        self.label.setText(str(self.counter))

# Create app object and run the app
app = QApplication(sys.argv)
stopWt = StopWatchWindow()
app.exec()

The following window will appear after the above script is executed.

The stopwatch will start working after the user clicks the Start button.

The counter will stop counting after the user clicks the Stop button.

Example 2: Create A Digital Clock

The following script will implement a digital clock in Python using the QTimer class. The script will display the digital clock in a label by reading the current system time once every second.

# Import necessary modules
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QVBoxLayout
from PyQt5.QtCore import QTimer, QTime, Qt
from PyQt5.QtGui import QFont

# Define class to create the digital clock
class DigitalClock(QWidget):
    def __init__(self):
        super().__init__()

        # Create a label with font and alignment
        self.lblTimer = QLabel()
        font = QFont('Times', 50)
        self.lblTimer.setFont(font)
        self.lblTimer.setAlignment(Qt.AlignCenter)

        # Create the vartical layout object
        v_layout = QVBoxLayout()
        v_layout.addWidget(self.lblTimer)
        self.setLayout(v_layout)

        # Create the timer object and call necessary methods to display the clock
        timer = QTimer(self)
        timer.timeout.connect(self.showClock)
        timer.start(1000)

        # Set the title of the window
        self.setWindowTitle("Digital Clock using QTimer")
        # Resize the window
        self.resize(270, 120)
        # Move the position of the window
        self.move(800, 400)
        # Call method to display the time
        self.showClock()
        # Display the window
        self.show()

    def showClock(self):
        # Read the current time
        Current_Time = QTime.currentTime()
        # Display the digital clock
        self.lblTimer.setText('<p style="color:green">' + Current_Time.toString('hh:mm:ss AP') + '</p>')

# Create app object and run the app
app = QApplication(sys.argv)
win = DigitalClock()
app.exec()

The following output window will appear after the above script is executed.

Conclusion

The date and time value of the current system time can be read in various ways using the QTimer class of the PyQt library. The QTimer class was used in this tutorial to execute various example time-related scripts.

]]>
How to Use PyQt QTableWidget https://linuxhint.com/use-pyqt-qtablewidget/ Sun, 14 Feb 2021 14:45:37 +0000 https://linuxhint.com/?p=89940 A table is used to display data in a structured format, according to rows and columns. The QTableWidget class of PyQt can be used in Python to display data in tabular form for tasks related to research or data analysis. The content of the table can be generated from different types of storage, such as two-dimensional lists or tables, database tables, JSON files, etc.  One or more tables can be created using QTableWidget in the PyQt application. This tutorial shows how to use QTableWidget to create various types of tables using Python script.

Necessary Methods

The QTableWidget class includes many methods to perform tasks related to table creation. Some of the more commonly used methods of this class are explained below:

Method Name Purpose
setRowCount() Used to define the number of rows.
setColumnCount() Used to define the number of columns.
setHorizontalHeaderLabels() Used to set the header labels of the table.
setItem() Used to set the cell value of the table.
resizeColumnsToContents() Used to resize the columns of the table based on the content.
resizeRowsToContents() Used to resize the rows of the table based on the content.
setMinimumWidth() Used to set the minimum width of the table.
setMinimumHeight() Used to set the minimum height of the table.
show() Used to display the table.

QTableWidget Usage

The following sections provide simple examples to explain how to create a table in the PyQt application using static data and list data.

Example 1: Create Simple Table Using Static Data

The following script creates a table of static data with five rows and four columns using the QTableWidget class. Two for loops with range values have been used in the script to add the static data into the table cells. The row and column positions of each cell have been added as the content of each cell. The QDesktopWidget is used in the script to display the window with the table in the center of the screen.

# Import necessary libraries
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QTableWidget, QTableWidgetItem, QDesktopWidget
from PyQt5.QtCore import QSize

# Define class to create the table with static data
class SimpleTable(QMainWindow):
    def __init__(self):
        # Call the parent constructor
        super().__init__()

        # Set the size and title of the window
        self.setMinimumSize(QSize(420, 150))
        self.setWindowTitle("Simple Table with Static Data")

        # Create the table with necessary properties
        table = QTableWidget(self)
        table.setColumnCount(4)
        table.setRowCount(5)
        table.setMinimumWidth(500)
        table.setMinimumHeight(500)

        # Set the table headers
        table.setHorizontalHeaderLabels(["Header-1", "Header-2", "Header-3", "Header-4"])

        # Set the table values
        for i in range(5):
            for j in range(4) :
                table.setItem(i, j, QTableWidgetItem("Row-" + str(i+1) + " , Col-" + str(j+1)))

        # Resize of the rows and columns based on the content
        table.resizeColumnsToContents()
        table.resizeRowsToContents()

        # Display the table
        table.show()

        # Display the window in the center of the screen
        win = self.frameGeometry()
        pos = QDesktopWidget().availableGeometry().center()
        win.moveCenter(pos)
        self.move(win.topLeft())
        self.show()

# Create app object and execute the app
app = QApplication(sys.argv)
mw = SimpleTable()
mw.show()
app.exec()

The following window with a table will appear the above script is executed. According to the values of the for loops, the cell value of the first row and the first column is ‘Row-1, Col-1,’ and the cell value of the last row and last column is ‘Row-5, Col-4.

Example 2: Create Table with Tool-Tip Using Dictionary and List Data

The following script creates a table with the content of a Python dictionary and list using the QTableWidget class. The script also adds a tool-tip text for the table header. A Python dictionary named marks is also declared in the script. The course codes are used as the key values of the dictionary. A Python list is declared to define the student IDs. The key values of the dictionary are added to the header of the table, the values of the list are added to the first column of the table, and the values of the dictionary are added to the other columns of the table.

# Import necessary modules
import sys
from PyQt5.QtWidgets import QApplication, QTableWidget, QTableWidgetItem, QDesktopWidget

# Declare a dictionary variable with marks
marks = {'CSE-401': [78, 93, 67, 88, 78],
         'CSE-404': [90, 59, 82, 73, 89],
         'CSE-406': [81, 80, 74, 83, 67],
         'CSE-407': [81, 80, 98, 83, 72]}


class TableFromList(QTableWidget):
    def __init__(self, data, *args):
        # Call parent constructor
        QTableWidget.__init__(self, *args)

        # Declare a list of the student IDS
        self.ID_list = ['0189945', '0154590', '0196734', '0185611', '0178956']
        # Set the necessary configurations fot the table
        self.data = data
        self.resizeColumnsToContents()
        self.resizeRowsToContents()
        self.setColumnWidth(0, 100)
        for i in range(4):
            self.setColumnWidth(i, 80)
        self.setMinimumWidth(400)
        self.setWindowTitle("Mark Sheet")

        # Declare the variable to set the header content
        headers = []
        headers.append('')
        # for loop to read the keys of the dictionary
        for n, key in enumerate(sorted(self.data.keys())):
            headers.append(key)
            # for loop to read the values of the dictionary
            for m, item in enumerate(self.data[key]):
                ID = QTableWidgetItem(self.ID_list[m])
                self.setItem(m, 0, ID)
                newVal = QTableWidgetItem(str(item))
                self.setItem(m, n+1, newVal)

        # Set the header label of the table
        self.setHorizontalHeaderLabels(headers)

        # Set the tooltips for the headers
        self.horizontalHeaderItem(1).setToolTip("Multimedia ")
        self.horizontalHeaderItem(2).setToolTip("Artificial Intelligent")
        self.horizontalHeaderItem(3).setToolTip("Advanced Database")
        self.horizontalHeaderItem(4).setToolTip("Unix Programming")

        # Read the particular cell value
        self.clicked.connect(self.on_click)

        # Display the window in the center of the screen
        win = self.frameGeometry()
        pos = QDesktopWidget().availableGeometry().center()
        win.moveCenter(pos)
        self.move(win.topLeft())
        self.show()

    def on_click(self):
        for ItemVal in self.selectedItems():
            # Read the header value based on the selected cell
            subject = self.horizontalHeaderItem(ItemVal.column()).text()
            # Print the detail information of the mark
            print("\n", self.ID_list[ItemVal.row()], " got ", ItemVal.text(), " in ", subject)

# Create app object and execute the app
app = QApplication(sys.argv)
table = TableFromList(marks, 5, 5)
table.show()
app.exec()

The following window with the table will appear after the above script is executed.

Conclusion

This tutorial showed you how to create tables with fixed data, dictionary data, and list data using two examples. Tables can also be created with dynamic data using database tables or other data sources.

]]>
How to Use PyQt QPushButton https://linuxhint.com/use-pyqt-qpushbutton/ Sun, 14 Feb 2021 14:05:35 +0000 https://linuxhint.com/?p=89931 Buttons are used in GUI applications to perform various operations based on the events generated by the user. The QPushButton class of PyQt is used in Python to create buttons required by the application. This class inherits the core functionalities of the QAbstractButton class. Text or icons can be used to caption the button. Buttons can be activated using a mouse and keyboard. Any button event, including the button being clicked or double-clicked, can be associated with a function or method to handle the event. This tutorial shows you how to create various types of buttons using the QPushButton class of PyQt in Python.

QPushButton Methods

The QPushButton class has many methods to perform various button-related tasks. Some of the more commonly used methods of this class are mentioned below:

Method Name Purpose
text() Used to read the caption of the button.
setText() Used to set text in the caption of the button.
setIcon() Used to set an icon in the caption of the button.
setDefault() Used to set the default button.
setEnabled() Used to enable or disable buttons. A value of True is used to enable the button, and a value of False is used to disable the button.
setCheckable() Used to identify whether the button is pressed or released.
isChecked() Used to read the state of the button that is a boolean value.
toggle() Used to toggle between states. If the current value of the button state is True, then the value will change to False, and vice versa.

QPushButton Usage

The following sections provide several simple examples to explain the usage of QPushButton.

Example 1: Create A Simple Push Button

The following script is used to create a single button in the window. The script will attach a custom function with the clicked event of the button to check whether the button has been clicked. The window will display a button following the execution of the code. If the user clicks the button, the text ‘Button is pressed’ will show in the label.

# Import necessary modules
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QLabel

# Define class to create a single push button
class ButtonExample(QWidget):

    def __init__(self):
        # Call parent constructor
        super().__init__()

        # Create a button
        self.btn = QPushButton('Click Me', self)
        # Set tooltip text for the button
        self.btn.setToolTip('This is a simple button')
        # Set the geometry of the button
        self.btn.setGeometry(100, 20, 100, 30)

        # Call function when the button is clicked
        self.btn.clicked.connect(self.onClicked)

        # Define label at the bottom of the button
        self.msgLabel = QLabel('', self)
        # Set the geometry of the label
        self.msgLabel.setGeometry(90, 60, 290, 60)

        # Set the title of the window
        self.setWindowTitle('Use of PushButton')
        # Set the geometry of the main window
        self.setGeometry(10, 10, 300, 150)

        # Set the position of the main window in the screen
        self.move(850, 300)
        # Display the window
        self.show()

    # Define function to handle the click event of the button
    def onClicked(self):
        # Set text for the label
        self.msgLabel.setText('Button is pressed.')

# Create app object and execute the app
app = QApplication(sys.argv)
button = ButtonExample()
app.exec()

The following window will appear after executing the script.

If the user clicks the Çlick Me button, then the following text will appear in the caption beneath the button.

Example 2: Create Multiple Push Buttons

The following script will create multiple pushbuttons using the QPushButton class. Two buttons are created in the script. The clicked event of the ‘Yes’ button is attached to a method named btn1_onClicked(), and the clicked event of the ‘No’ button is attached to a method named btn2_onClicked(). A caption created below the buttons will display the specified message based on the button clicked by the user. The setGeometry() function is used for each label and button to set the position of the objects in the window.

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QLabel


class MultiButtons(QWidget):

    def __init__(self):
        # Call parent constructor
        super().__init__()

        # Define label at the top of the button
        self.topLabel = QLabel('<h2>Do you like python?</h2>', self)
        # Set the geometry of the label
        self.topLabel.setGeometry(100, 20, 290, 50)

        # Create the first button
        self.btn1 = QPushButton('Yes', self)
        # Set the geometry of the button
        self.btn1.setGeometry(130, 70, 60, 40)
        # Call function when the button is clicked
        self.btn1.clicked.connect(self.btn1_onClicked)

        # Create the second button
        self.btn2 = QPushButton('No', self)
        # Set the geometry of the button
        self.btn2.setGeometry(200, 70, 60, 40)
        # Call function when the button is clicked
        self.btn2.clicked.connect(self.btn2_onClicked)

        # Define label at the bottom of the button
        self.msgLabel = QLabel('', self)
        # Set the geometry of the label
        self.msgLabel.setGeometry(130, 120, 300, 80)

        # Set the title of the window
        self.setWindowTitle('Use of multiple PushButtons')
        # Set the geometry of the main window
        self.setGeometry(10, 10, 400, 200)

        # Set the position of the main window in the screen
        self.move(850, 300)
        # Display the window
        self.show()


    def btn1_onClicked(self):
        # Set text for the bottom label
        self.msgLabel.setText('<h3>You clicked Yes.</h3>')


    def btn2_onClicked(self):
        # Set text for the bottom label
        self.msgLabel.setText('<h3>You clicked No.</h3>')


# Create app object and execute the app
app = QApplication(sys.argv)
button = MultiButtons()
app.exec()

The following window will appear after executing the script.

If the user clicks the Yes button, the message, ‘You clicked Yes’ will be displayed as the label text.

If the user clicks the No button, the message, ‘You clicked No’ will be displayed as the label text.

Conclusion

The QPushButton class allows users to create one or more buttons based on the application requirements. This tutorial showed the usage of this class for creating one or multiple buttons, as well as how to handle click events of buttons using custom event handler functions.

]]>
How to Use PyQt QMessageBox https://linuxhint.com/use-pyqt-qmessagebox/ Sun, 14 Feb 2021 10:06:51 +0000 https://linuxhint.com/?p=89915 The message box is used in the GUI application to provide necessary information for the user or to ask the user to take actions based on the message. Four types of message boxes can be created for any GUI application, including the informational message box, warning message box, critical message box, and question message box. The QMessageBox class of PyQt is used in Python to create a message box. This tutorial shows you how to use the QMessageBox class to create various message boxes.

Necessary Methods

The QMessageBox class has many methods for creating various types of message boxes. Some of the more commonly used methods of the QMessageBox class are described below:

Method Names  Purpose
setTitle() Used to display the custom title.
setText() Used to set the text of the main message.
setDetailText() Used to display a window with a details button; the message text will appear after the user clicks on the button.
setInformativeText Used to display the additional message.
setIcon() Used to set an icon in the message box based on the message type.
setWindowTitle() Used to set the title of the message window.
setDefaultButton() Used to set the button in the message box default; the button will release a clicked signal when the Enter key is pressed.
setEscapeButton() Used to set any button to work as an escape key; the button will release a clicked signal when the Escape key is pressed.
setStandardButtons() Various standard buttons can be used in the message box based on the message type, such as OK, Yes, No, Cancel, Close, etc.

QMessageBox Usage

The following sections of this tutorial provide examples that will show you how to create different message boxes using the QMessageBox class.

Example 1: Create an Informational Message Box

The following script will create a simple informational message box using the QMessageBox class. This type of message box provides the informational message for the user only. OK is the default button in the message box. Here, QMessageBox.Information is used in the setIcon() method to display the information icon in the message box.

# Import necessary modules
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBox

# Define class to to display an informational message
class MessageWindow(QMainWindow):
    def __init__(self):
        # Call the parent constructor
        super().__init__()
        # Create the messagebox object
        self.msg = QMessageBox()
        # Set the information icon
        self.msg.setIcon(QMessageBox.Information)
        # Set the main message
        self.msg.setText("The task is completed successfully.")
        # Set the title of the window
        self.msg.setWindowTitle("Informational Message")
        # Display the message box
        self.msg.show()

# Create app object and run the app
app = QApplication(sys.argv)
Win = MessageWindow()
app.exec()

The following message box will appear after the above script is executed.

Example 2: Create a Warning Message Box

The following script will create the warning message box using the QMessageBox class. This type of message box provides the warning message for the user. The warning is used in the setIcon() method to display the warning icon in the message box. The OK and Cancel buttons are added to the message box using the setStandardButtons() method. A custom method called msgButton() is defined in the class to trace the button in the message box that has been clicked by the user. If the user clicks the OK button, then the text, ‘OK button is pressed,’ will print; otherwise, the ‘Cancel button is pressed’ text will print.

# Import necessary modules
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBox

# Define class to to display an informational message
class MessageWindow(QMainWindow):
    def __init__(self):
        # Call the parent constructor
        super().__init__()
        # Create the messagebox object
        self.msgWarning = QMessageBox()
        # Set the Warning icon
        self.msgWarning.setIcon(QMessageBox.Warning)
        # Set the main message
        self.msgWarning.setText("<b>Name</b> variable is undefined.")
        # Set two buttons for the message box
        self.msgWarning.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
        # Call the custom method on button clicked
        self.msgWarning.buttonClicked.connect(self.msgButton)
        # Set the title of the window
        self.msgWarning.setWindowTitle("Warning Message")
        # Display the message box
        self.msgWarning.show()

    # Define function for the buttons
    def msgButton(self, i):
        if i.text() == '&OK' :
            print("OK Button is pressed.")
        else:
            print("Cancel Button is pressed.")

# Create app object and run the app
app = QApplication(sys.argv)
Win = MessageWindow()
app.exec_()

The following message box will appear after the above script is executed.

If the user clicks the OK button, the following output will appear.

Example 3: Create a Question Warning Message

The following script will create the question message box using the QMessageBox class. This type of message box provides the question message for the user to take the particular action based on the user’s decision. Here, QMessageBox.Question is used in the setIcon() method to display the question icon in the message box. The Yes and No buttons are added to the message box using the setStandardButtons() method. The No button is set as the default button using the setDefaultButton() method. A custom method called msgButton() is defined in the class to trace the button in the message box that has been clicked by the user.

# Import necessary modules
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBox

# Define class to to display an informational message
class MessageWindow(QMainWindow):
    def __init__(self):
        # Call the parent constructor
        super().__init__()
        # Create the messagebox object
        self.msgQuestion = QMessageBox()
        # Set the Warning icon
        self.msgQuestion.setIcon(QMessageBox.Question)
        # Set the main message
        self.msgQuestion.setText("Do you want to continue?")
        # Set two buttons for the message box
        self.msgQuestion.setStandardButtons(QMessageBox.Yes | QMessageBox.No)

        self.msgQuestion.setDefaultButton(QMessageBox.No)
        # Call the custom method on button clicked
        self.msgQuestion.buttonClicked.connect(self.msgButton)
        # Set the title of the window
        self.msgQuestion.setWindowTitle("Asking Question to user")
        # Display the message box
        self.msgQuestion.show()

    # Define function for the buttons
    def msgButton(self, i):
        if i.text() == '&Yes' :
            print("The task is continuing...")
        else:
            print("You have cancelled the task.")

# Create app object and run the app
app = QApplication(sys.argv)
Win = MessageWindow()
app.exec_()

The following message box will appear after the above script is executed.

If the user clicks the Enter key without selecting any buttons, then the No button will be activated by default, and the following output will appear:

Conclusion

In this tutorial, three different types of message boxes were created using the QMessageBox class. Hopefully, this tutorial helped you to better understand the usage of this class. You should now be able to create a message box for the PyQt application.

]]>
How to Use PyQt QComboBox https://linuxhint.com/use-pyqt-qcombobox/ Sat, 13 Feb 2021 07:38:30 +0000 https://linuxhint.com/?p=89825

A ComboBox is used to select one item from a list of items, much like the radio button. The QComboBox class of PyQt is used to create drop-down lists using Python script. It brings up a list of items for the user to select. The items of the ComboBox can be added, changed, and removed using the script. Multiple items can be selected like the CheckBox button from the list of items from the ComboBox then it is called ListBox. This tutorial shows you how to use QComboBox to create a drop-down list in Python.

QComboBox Methods

The QComboBox class contains many methods for performing various tasks related to ComboBox. Some of the more commonly used methods of this class are described below:

Method Name Purpose
count() Used to count the total number of items in the list.
addItem() Used to add a single new item to the list.
addItems() Used to add multiple items to the list.
itemText() Used to read the text of a particular item based on an index.
setItemText() Used to set the text of a particular item based on an index.
currentText() Used to read the text of the selected item.
currentIndex() Used to read the index of the selected item.
clear() Used to delete all items from the list.
highlighted() Used when an item in the list is highlighted.
activated() Used when an item is selected by the user.
currentIndexChanged() Used when the item in the list has changed.

ComboBox Usage

The following sections provide examples that explain some different uses of the ComboBox using the QComboBox module of the PyQt library.

Example 1: Create a Simple Drop-Down List

This example shows you how to create a simple drop-down list using the QComboBox class. Here, a drop-down list of five elements is created and is attached to a custom function that will print the selected value from the list. One label is used in the function of the drop-down list to display static text, and another label is used below the drop-down list to show the selected value.

# Import necessary modules

import sys

from PyQt5.QtWidgets import (QApplication, QWidget, QLabel, QVBoxLayout, QComboBox)

# Declare class to create the ComboBox

class ComboExample(QWidget):

    def __init__(self):

        super().__init__()


        # Set the label before the ComboBox

        self.topLabel = QLabel('Select your favorite programming language:', self)


        # Define the combobox with items

        combobox = QComboBox(self)

        combobox.addItem('PHP')

        combobox.addItem('Python')

        combobox.addItem('Perl')

        combobox.addItem('Bash')

        combobox.addItem('Java')


        # Set the label after the ComboBox

        self.bottomLabel = QLabel('', self)

        self.bottomLabel.adjustSize()


        # Define vartical layout box

        v_layout = QVBoxLayout()

        v_layout.addWidget(self.topLabel)

        v_layout.addWidget(combobox)

        v_layout.addWidget(self.bottomLabel)


        # Call the custom method if any item is selected

        combobox.activated[str].connect(self.onSelected)


        # Set the configurations for the window

        self.setContentsMargins(20, 20, 20, 20)

        self.setLayout(v_layout)

        self.move(800, 300)

        self.setWindowTitle('Use of ComboBox')


    # Custom function to read the value of the selected item

    def onSelected(self, txtVal):

        txtVal = "\nYou have selected: " + txtVal

        self.bottomLabel.setText(txtVal)


# Create app object and execute the app

app = QApplication(sys.argv)

combobox = ComboExample()

combobox.show()

app.exec()

If the user clicks on the drop-down list after executing the script, the following list will appear.

If the user selects the value Bash from the drop-down list, the value of the second label will be changed to ‘You have selected: Bash.

Example 2: Create a ComboBox Using the List

In the previous example, the drop-down list was created with static data using the addItem() method of the QComboBox class. This example shows you how to add multiple items in the drop-down list by defining a Python list. First, we will add static text to the first item of the drop-down list using the addItem() method. Next, we will define a list of five elements in the script, and we will add these elements to the drop-down list using the addItems() method. A custom function is attached to the drop-down list to display the message in the label based on the user selection.

# Import necessary modules

import sys

from PyQt5.QtWidgets import *

# Declare the class to create combobox by using list data

class ComboExample(QMainWindow):

    def __init__(self):

        super().__init__()


        # Set the tittle of the window

        self.setWindowTitle("ComboBox with List data ")

        # Set the geometry for the window

        self.setGeometry(100, 100, 350, 150)


        # Create combobox

        self.combobox = QComboBox(self)

        # Set the geometry for the combobox

        self.combobox.setGeometry(30, 30, 200, 30)


        # Define list items for the combobox

        src_engines = ["google.com", "yahoo.com", "ask.com", "baidu.com", "yandex.com"]

        # Enable the editable option of the combobox

        self.combobox.setEditable(True)

        # Set the first item for the combobox

        self.combobox.addItem("Select Search Engine")

        # Add multiple items in the combobox using list

        self.combobox.addItems(src_engines)


        # Define label at the bottom of the combobox to provide message for the user

        self.msgLabel = QLabel('', self)

        # Set the geometry for the label

        self.msgLabel.setGeometry(30, 60, 290, 60)


        # Call the custom function when any item is selected

        self.combobox.activated[str].connect(self.onClicked)


        # Move the position of the window

        self.move(800, 400)

        # Display the Window

        self.show()


    # Define a method to handle the click event of the Combobox

    def onClicked(self, val):

        # Check any item is selected by the user or not

        if val == "Select Search Engine":

            message = "You have selected nothing."

        else:

            message = "Your favorite search engine is " + val


        # Display the message text in the label

        self.msgLabel.setText(message)

        # Display the message in the console

        print(message)


# Create the app object

app = QApplication(sys.argv)

# Create an object of the class object

combo = ComboExample()

# Execute the app

app.exec()

If the user clicks the drop-down list after executing the script, then the following list will appear.

If the user selects any item except the first item in the drop-down list, then the selected value will be shown in the label by combining with the other text.

If the user selects the first item in the drop-down list, then the value, ‘You have selected nothing’ will be shown in the label.

Conclusion

This article showed you how to create and use drop-down lists in Python using the QComboBox class using simple examples to help you to better understand the use of this class.

]]>
How to Use PyQt GUI Builder https://linuxhint.com/use-pyqt-gui-builder/ Sat, 13 Feb 2021 07:24:14 +0000 https://linuxhint.com/?p=89815

PyQt is a popular Python library used to implement graphical applications in Python more easily. This library comes with a GUI (Graphical User Interface) builder tool called Qt Designer. The GUI can be built quickly in Python using the drag-and-drop feature of this library, though this tool has no debugging facility like the standard IDE. This tutorial shows you how to implement the GUI using the Qt Designer class of PyQt.

Prerequisites

You must install the Qt Designer tool before practicing the examples provided in this tutorial. Run the following commands to install the Qt Designer on your system:

$ sudo apt-get install qttools5-dev-tools

$ sudo apt-get install qttools5-dev

Open the Qt Designer

Run the following command to change the current directory location to the Qt Designer folder.

$ cd /usr/lib/x86_64-linux-gnu/qt5/bin/

Run the following command to open the Qt Designer application.

$ ./designer

If the Qt Designer has been installed properly, the following window will appear. The Widget box shown on the left side of the main window contains various widgets that you can use to design the user interface of the application. The New Form window is used to create a new window using the default buttons. The windows shown on the right side of the main window provides information about the widgets that can be read or modified.

Create the First Form Using the Qt Designer

To begin designing the interface for the Python application, we will click the Create button in the following window to open the dialog box with two default buttons.

Next, we will design a login form using the Label, Text Edit, and Push Button widgets. The dialog box will be saved with the name Login.ui, which will be used later in the Python script. The QObject name will be changed to Logindialog using the Property Editor Window of this application.

Using the Login Dialog Box

The user interface file created by the Qt Designer can be used in the Python script in two ways. The file can be used directly in the Python script, or the converted Python file of the Qt Designer file can be used in the Python script. Both ways of using the dialog box of Qt Designer are shown in the following section of the tutorial.

Run Qt Designer File Directly

The UIC module of the PyQt library is used to load the file created by the Qt Designer, and the loadUI() method of the UIC module is used to load the UI file. The following script shows how to load the Qt Designer file named Login.ui that we created before. The necessary modules are imported at the beginning of the script. The object of the application is created using the QApplication(), and the Qt Designer file is loaded using the loadUI() method. Next, the exec() method is called to start the event loop of the application.

# Import sys module

import sys

# Import QtWidgets and uic modules

from PyQt5 import QtWidgets, uic

# Create app object

app = QtWidgets.QApplication(sys.argv)

# Load GUI form and display

window = uic.loadUi("Login.ui")

window.show()

# Start the event loop of the app or dialog box

app.exec()

The following dialog box will appear after executing the above script.

Run UI File by Converting into Python File

The UI file created by the Qt Designer can be converted into a Python file using the pyuic5 command. Run the following command to convert the Login.ui file into the loginForm.py file. The Login.ui file must be stored in the current location to run the following command; otherwise, an error will be generated.

$ pyuic5 Login.ui -o loginForm.py

The following code will be generated in the loginForm.py file after executing the above command.

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'Login.ui'

#

# Created by: PyQt5 UI code generator 5.12.3

#

# WARNING! All changes made in this file will be lost!

from PyQt5 import QtCore, QtGui, QtWidgets


class Ui_Logindialog(object):

    def setupUi(self, Logindialog):

        Logindialog.setObjectName("Logindialog")

        Logindialog.resize(400, 224)

        self.textEdit = QtWidgets.QTextEdit(Logindialog)

        self.textEdit.setGeometry(QtCore.QRect(130, 70, 221, 31))

        self.textEdit.setObjectName("textEdit")

        self.textEdit_2 = QtWidgets.QTextEdit(Logindialog)

        self.textEdit_2.setGeometry(QtCore.QRect(130, 120, 221, 31))

        self.textEdit_2.setObjectName("textEdit_2")

        self.label = QtWidgets.QLabel(Logindialog)

        self.label.setGeometry(QtCore.QRect(140, 20, 131, 31))

        font = QtGui.QFont()

        font.setPointSize(18)

        self.label.setFont(font)

        self.label.setObjectName("label")

        self.label_2 = QtWidgets.QLabel(Logindialog)

        self.label_2.setGeometry(QtCore.QRect(36, 70, 81, 20))

        self.label_2.setObjectName("label_2")

        self.label_3 = QtWidgets.QLabel(Logindialog)

        self.label_3.setGeometry(QtCore.QRect(40, 120, 67, 17))

        self.label_3.setObjectName("label_3")

        self.btnLogin = QtWidgets.QPushButton(Logindialog)

        self.btnLogin.setGeometry(QtCore.QRect(150, 170, 89, 25))

        self.btnLogin.setObjectName("btnLogin")

        self.btnCancel = QtWidgets.QPushButton(Logindialog)

        self.btnCancel.setGeometry(QtCore.QRect(250, 170, 89, 25))

        self.btnCancel.setObjectName("btnCancel")


        self.retranslateUi(Logindialog)

        QtCore.QMetaObject.connectSlotsByName(Logindialog)


    def retranslateUi(self, Logindialog):

        _translate = QtCore.QCoreApplication.translate

        Logindialog.setWindowTitle(_translate("Logindialog", "Dialog"))

        self.label.setText(_translate("Logindialog", "Login Form"))

        self.label_2.setText(_translate("Logindialog", "Username"))

        self.label_3.setText(_translate("Logindialog", "Password"))

        self.btnLogin.setText(_translate("Logindialog", "Login"))

        self.btnCancel.setText(_translate("Logindialog", "Cancel"))

The following will display the Login dialog box by importing the loginForm.py file created using the pyuic5 command. The object of the application is created using QApplication(), and the Login dialog box is loaded using the setupUi() method. The Login button is attached with the loginClicked() method to check whether the username and password taken from the user are valid. The Cancel button is attached to the cancelClicked() method to quit from application. The exec() method is called to start the event loop of the application.

# Import QtWidgets

from PyQt5 import QtWidgets

# Import sys

import sys

# Import login form ui

import loginForm

# Define a class to setup the UI

class MyApp (QtWidgets.QMainWindow, loginForm.Ui_Logindialog):

    def __init__(self, parent=None):

        super(MyApp, self).__init__(parent)

        # Load the login form

        self.setupUi(self)

        # Call loginClicked() method

        self.btnLogin.clicked.connect(self.loginClicked)

        # Call cancelClicked() method

        self.btnCancel.clicked.connect(self.cancelClicked)


    # Declare method to check username and password when Login button will click

    def loginClicked(self):

        if self.textEdit.toPlainText() == 'admin' and self.textEdit_2.toPlainText() == 'superuser':

            print('Authenticated User')

        else:

            print('Unauthenticated User')


    # Declare method to terminate the script when Cancel button will click

    def cancelClicked(self):

        exit()

# Create app object

app = QtWidgets.QApplication(sys.argv)

# Create class object

form = MyApp()

# Display the form

form.show()

# Start the event loop of the app or dialog box

app.exec()

The following dialog box will appear after executing the above script.


If the user enters the wrong username or password in the Login form, then the following output will appear after clicking the Login button.


If the user enters the correct username and password in the Login form, then the following output will appear after clicking on the Login button.


If the user clicks the Cancel button in the Login form, then the dialog box will disappear.

Conclusion

This tutorial showed you how to install Qt Designer and how to design a simple form using this application. The tutorial also showed you how to load the UI dialog box directly and after converting it into the Python script have shown in the other part of this tutorial. Hopefully, this article helped you to better understand the usage of Qt Designer for building and using the GUI in applications.

]]>
Build a PyQt Application by Example https://linuxhint.com/build-pyqt-application-by-example/ Fri, 12 Feb 2021 09:20:15 +0000 https://linuxhint.com/?p=89779 PyQt is a very useful library of Python used to develop graphical applications. It uses the Qt GUI framework of Python that is developed using C++ language. The graphical user interface of the application can be developed by importing the PyQt library in a Python script or using the Qt Designer module of PyQt. If you don’t want to write code to implement the GUI of the application, then it is better to install Qt Designer and create a graphical user interface using it. The way of creating a PyQt application in Python is shown in this tutorial, step-by-step.

Create a Simple PyQt Application for Addition:

The steps of implementing a simple PyQt application to calculate the sum of two numbers are shown in this section of the tutorial. Here, the number values will be taken from the user using textboxes, after executing the script, then the sum of the values will be displayed after clicking a button. A window with the necessary fields has been created here to build the design of the application; next, the Python script is used to calculate the sum.

Steps:

Step 1. Create PyQt application object

You have to import the required modules of Python to design the PyQt application of this tutorial. To design this application, it will require two labels, two text boxes, and a push-button.

QApplication, QMainWindow, QLabel, QTextEdit, and QPushButton modules will be required to design the application.

Add the following lines at the beginning of the script to use these modules.

# Import necessary modules
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel, QTextEdit, QPushButton

Add the following lines to create the application object and start the event loop. Nothing will appear after executing the script now.

# Create object PyQt application
app = QApplication([])
# Start the event loop for executing the application
app.exec()

Step 2: Create class and window object

Create the class to add the necessary objects in this step to design the application window.

Add the following lines to create a class with a window object. Here, the title, size, and position of the window are set. Next, the show() method is called to display the window as output.

class addition(QMainWindow):

    def __init__(self):
        # Call the parent constructor
        super().__init__()

        # Set the title of the window
        self.setWindowTitle("PyQt Addition Application")
        # Set the width and height of the window
        self.resize(350, 200)
        # Move the position of the window
        self.move(800, 400)
        # Display the window
        self.show()

You have to create the object of the class before running the event loop.

# Create window object
window = addition()

The following blank window will appear after executing the script.

Step 3: Add necessary widgets in the window for addition

Now, add the necessary objects required to implement the application. The three objects of the QLabel widget, two objects of the QTextEdit widget, and a button object of the QPushButton widget are created in this step. The first two label objects will be used to provide the helping text before the textboxes. QTextEdit objects will be used to take two number values from the user. QPushButton object will be created to calculate the sum of the input numbers using an event handler function that will be created in the next step. The last label object will be used to display the summation of the two numbers. Here, the setGeometry() function is called for every object to set the position of the object in the window.

# Create label for the first number
self.lbl1 = QLabel('Number 1', self)
self.lbl1.setGeometry(80, 20, 80, 50)
# Create textbox for the first number
self.textbox1 = QTextEdit(self)
self.textbox1.setGeometry(80, 60, 70, 30)

# Create label for the second number
self.lbl2 = QLabel('Number 2', self)
self.lbl2.setGeometry(200, 20, 80, 50)
# Create textbox for the second number
self.textbox2 = QTextEdit(self)
self.textbox2.setGeometry(200, 60, 70, 30)

# Create push button for calculate the sum
self.submit = QPushButton('Calculate Sum', self)
self.submit.setGeometry(80, 100, 190, 30)
# Create label for show the result of summation
self.lblResult = QLabel('', self)
self.lblResult.setGeometry(80, 130, 200, 50)

The following output will appear after executing the script. No event handler function is created in this step, which is used to calculate the sum of the numbers. So, if the user clicks the button, nothing will happen.

Step 4: Create and call the function to handle the click event of the button

Create a method named onClicked() with the following lines inside the addition class to handle the click event of the button. The values of the textboxes are converted into integer numbers using the int() function and stored into the num1 and num2 variables. Next, the sum of num1 and num2 are stored in the result variable. The values of num1, num2, and result variables are converted into string values using the str() function, before storing the values in the output variable. The third label object is used to display the content of the output variable.

def onClicked(self):

    num1 = int(self.textbox1.toPlainText())
    num2 = int(self.textbox2.toPlainText())
    result = num1 + num2
    output = "<p style='color:blue'>The sum of " + str(num1) + " and " + str(num2) + " is " + str(result) + '</p>'
    self.lblResult.setText(output)

Add the following lines in the class after the button object to call onClicked() method when the button will be clicked.

# Call function when the button is clicked
self.submit.clicked.connect(self.onClicked)

After executing the script, if the user entered 12 and 18 in the textboxes and clicked on the Calculate Sum button, and the following formatted output will appear below the button.

Conclusion:

The implementation of a very simple PyQt application has been explained in this tutorial starting from the basic to help the new Python users. Hopefully, the user will be able to design and create a simple PyQt application after completing and understanding the steps of this tutorial properly.

]]>
How to Use PyQtGraph? https://linuxhint.com/use-pyqtgraph/ Wed, 10 Feb 2021 07:21:19 +0000 https://linuxhint.com/?p=89432

The scientific or numerical visualization tasks can be done in python easily using various Python libraries, such as Plotly, Matplotlib, Seaborn, ggplot, PyQt, etc. PyQtGraph is a useful module of the PyQt library to create a graph. This module can create graphs very fast. 2D and 3D graphics can be created by using this module. How to use the PyQtGraph module to draw different types of graphs has shown in this tutorial.

Prerequisites

You have to install the PyQtGraph module in your system before creating the graph. Run the following command to install PyQtGraph by using pip3.

$ sudo pip3 install pyqtgraph

Draw Line Graph

A line chart or line graph is a chart that displays information by using a series of data plots. PlotWidget widget is used to create all plots of PyQtGraph. This widget contains a canvas on which any plot can be added or removed.

Example-1: Draw a simple line graph

The following script shows the way to draw a line graph using random numbers. range() function is used to generate 10 sequential numbers that are used for x-axis values. The random module of python is used to generate 10 random integer numbers used for y-axis values. plot() method is used to draw each plot of the line graph based on the values of the x-axis and y-axis. When the code is executed in interactive mode, then sys.flags.interactive flag will be True. If this flag’s value is not True, then it indicates that the Qt event loop does not require to run because the REPL (Run, Evaluate, Print, Loop) already has an event loop.

# Import random module
# Import random module

import random as rd

# Import PyQtGraph Module

import pyqtgraph as pg

# Import QtGui from the PyQtGraph Module

from pyqtgraph.Qt import QtGui



# Generate x-axis values

x = range(0, 10)

# Generate y-axis values

y = [ ]

for i in range(0, 10):

    n = rd.randint(0, 20)

    y.append(n)


# Initialize the plot

plt = pg.plot()

# Set the label for x axis

plt.setLabel('bottom', 'Sequentially Generated Values')

# Set the label for y-axis

plt.setLabel('left', 'Randomly Generated Values')

# Set horizontal range

plt.setXRange(0, 10)

# Set vertical range

plt.setYRange(0, 20)

# Set the title of the graph

plt.setTitle("Simple Line Graph")

# Set the plot values

line = plt.plot(x, y)



# Main method

if __name__ == '__main__':


    # Import sys module

    import sys


    # Start Qt event loop unless running in interactive mode

    if sys.flags.interactive != 1:

        QtGui.QApplication.instance().exec()

Output:

The following similar line graph will be appeared after executing the above script. The graph will vary in each execution for the random values.

Example-2: Draw a Line graph with styling and marker

The following script shows how to draw a stylist line graph based on the values of a python list. mkPen() function is used to set the color and width of the line. ‘o‘ is used as the marker in the graph, and the color and width of the marker are set by using symbolPen and symbolSize properties.

# Import PyQtGraph Module
# Import PyQtGraph Module

import pyqtgraph as pg

# Import QtGui from the PyQtGraph Module

from pyqtgraph.Qt import QtGui


# Generate x-axis values

x = range(0, 10)

# Generate y-axis values

y = [3, 7, 5, 11, 8, 13, 9, 16, 15, 12]


# Initialize the plot

plt = pg.plot()

# Set the label for x axis

plt.setLabel('bottom', 'X-axis Values')

# Set the label for y-axis

plt.setLabel('left', 'Y-axis Values')

# Set horizontal range

plt.setXRange(0, 10)

# Set vertical range

plt.setYRange(0, 20)

# Set the title of the graph

plt.setTitle("Line Graph with styling and marker")


# Set the background color

plt.setBackground('d5ecf2')

# Set the plot values with pen color and width

line = plt.plot(x, y, pen=pg.mkPen('r', width=6), symbol='o', symbolPen='b', symbolSize=20)

# Add legend

plt.addLegend()

# Show grids

plt.showGrid(x=True, y=True)


# Main method

if __name__ == '__main__':


    # Import sys module

    import sys


    # Start Qt event loop unless running in interactive mode

    if sys.flags.interactive != 1:

        QtGui.QApplication.instance().exec_()



# Main method

if __name__ == '__main__':


    # Import sys module

    import sys


    # Start Qt event loop unless running in interactive mode

    if sys.flags.interactive != 1:

        QtGui.QApplication.instance().exec_()

Output:

The following line graph will be appeared after executing the above script.

Draw Bar Graph

A set of data can be visualized by using a bar graph. A simple bar creates by comparing the list of data with a related range of data. BarGraphItem class is used to create the bar graph by using PyQtGraph.

Example-3: Draw a bar graph

The following script shows how to draw a bar graph based on the values of a NumPy array. BarGraphItem is used to draw a bar graph with blue color and a width value of 0.5.

# Import PyQtGraph module

# Import PyQtGraph module

import pyqtgraph as pg

# Import QtGui from the PyQtGraph Module

from pyqtgraph.Qt import QtGui

# Import NumPy Library

import numpy as np


# Generate x-axis

x = np.arange(0, 10)

# Generate y-axis

y = np.array([3, 5, 7, 9, 5, 8, 10, 6, 5, 2])

# Set bar chart values and brush color and width

bg = pg.BarGraphItem(x=x, height=y, width=0.5, brush='b')


# Define the plot variable

plt = pg.plot()

# Set the label for x axis

plt.setLabel('bottom', '<p style="font-size:20px;color:green">X-axis Values</p>')

# Set the label for y-axis

plt.setLabel('left', '<p style="font-size:20px;color:green">Y-axis Values</p>')

# Set the bar title

plt.setTitle('<h3>Bar Graph using PyQtGraph</h3>')

# Add the bar chart items

plt.addItem(bg)


# Main method

if __name__ == '__main__':


    # Import sys module

    import sys


    # Start Qt event loop unless running in interactive mode

    if sys.flags.interactive != 1:

        QtGui.QApplication.instance().exec_()

Output:

The following bar graph will be appeared after executing the above script.

Conclusion

Creating three different types of graphs with random values, list items, and NumPy array have shown in this tutorial by using three simple examples. The readers will be able to use the PyQtGraph module for implementing line and bar graphs after reading this tutorial.

]]>
How to Use PyQt Checkbox? https://linuxhint.com/use-pyqt-checkbox/ Wed, 10 Feb 2021 07:21:14 +0000 https://linuxhint.com/?p=89424

The checkbox is used to select zero or more options from many options using the graphical user interface. A form with a checkbox can be created by using QCheckBox class in a Python script or using the QCheckBox widget of Qt Designer without writing any script.

When a form with a checkbox is created using QCheckBox class, then stateChanged.connect() function is called to apply the action done by the user’s input. If the user checked any checkbox option, then the value of QtCore.Qt.checked will be True. Multiple checkboxes with a single selection like Radio Button can be created using QbuttonGroup class.

How a form with a checkbox can be created by writing a Python script is shown in this tutorial.

Necessary methods of QCheckBox

QCheckBox class has many functions to do different types of tasks with the checkbox. Some most commonly used methods of this class are described below:

Method Name Purpose
isChecked() It returns a boolean value. When the user clicks to check the checkbox, it returns True, otherwise, it returns False.
setChecked() It is used to change the state of the checkbox. True value is set to make the checkbox checked, and False value is set to make the checkbox unchecked.
text() It is used to read the label of the checkbox.
setText() It is used to set the label of the checkbox.
isTriState() It returns a boolean value. It is used to check the tri-state to know whether the checkbox is enabled or not.
setTriState() It is used to enable the third state of the checkbox that indicates the neutral state.

Create a Form with Checkbox using QCheckBox Class:

The uses of the checkbox are shown in this section using different types of examples. The use of a single checkbox, as shown in the first example, and the use of multiple checkboxes are shown in the second example.

Example 1: Creating a Single Checkbox

The way of creating a single checkbox using QCheckBox class and reading the input value of the checkbox provided by the user are shown in this example. The necessary modules are imported at the beginning of the script. A label is used in the above checkbox for providing the information for the user. If the user clicks on the checkbox to check, then the script will print, “Wow! You like programming”, otherwise the script will print, “Oh no!, You don’t like programming”.

# Import necessary modules

import sys

from PyQt5 import QtCore, QtWidgets

from PyQt5.QtWidgets import QMainWindow, QCheckBox, QLabel, QVBoxLayout, QDesktopWidget

# Define class for creating the form with single checkbox

class SingleCheckbox(QMainWindow):

    def __init__(self):

        super().__init__()


        # Create the label text for the user

        lb = QLabel("Do you like programming?", self)

        lb.setGeometry(20, 20, 200, 20)

        lb.move(20, 20)


        # Create a checkbox with the label

        cb = QCheckBox('Yes', self)

        cb.stateChanged.connect(self.Check_Answer)

        cb.move(20, 50)


        # Set the vertical Qt Layout

        vbox = QVBoxLayout()

        vbox.addWidget(lb)

        vbox.addWidget(cb)


        # Set the window title and size

        self.setWindowTitle('Form with Single Checkbox')

        self.setGeometry(60, 60, 300, 100)


        # Display the window in the center of the screen

        win = self.frameGeometry()

        pos = QDesktopWidget().availableGeometry().center()

        win.moveCenter(pos)

        self.move(win.topLeft())

        self.show()


    # Define function to check the user's input

    def Check_Answer(self, state):


        if state == QtCore.Qt.Checked:

            print("Wow! You like programming.")

        else:

            print("Oh no!, You don't like programming.")

# Create app object and execute the app

app = QtWidgets.QApplication(sys.argv)

form = SingleCheckbox()

app.exec()

The following window with a checkbox will appear after executing the script.


In the following output, the user has checked the checkbox twice and unchecked the checkbox once.

Example 2: Creating Multiple Checkboxes

The method of creating multiple checkboxes using QCheckbox class and reading multiple values of the multiple checkboxes are shown in this example. Two labels and three checkboxes are added to the window. The first label is added at the beginning of the checkboxes to provide information for the user, while the second label is added at the end of the checkboxes to display the values of the selected checkbox or checkboxes.

# Import necessary modules

import sys

from PyQt5.QtWidgets import (QWidget, QCheckBox, QApplication, QVBoxLayout, QLabel, QDesktopWidget)

# Define class for creating the form with multiple checkboxes

class MultipleCheckbox(QWidget):

    def __init__(self):

        super().__init__()


        # Set the label text for the user

        lb = QLabel("Select your favorite food(s):", self)

        lb.setGeometry(20, 20, 100, 20)

        lb.move(20, 20)


        # Create three checkboxes

        cb1 = QCheckBox('Chocolate Cake', self)

        cb1.move(20, 70)

        cb1.stateChanged.connect(lambda: self.Selected_Value(cb1))

        cb2 = QCheckBox('Ice-Cream', self)

        cb2.move(20, 90)

        cb2.stateChanged.connect(lambda: self.Selected_Value(cb2))

        cb3 = QCheckBox('Pasta', self)

        cb3.move(20, 110)

        cb3.stateChanged.connect(lambda: self.Selected_Value(cb3))

        self.label = QLabel('Nothing Selected')

        self.label.move(20, 150)


        # Set the vertical Qt Layout

        vbox = QVBoxLayout()

        vbox.addWidget(lb)

        vbox.addWidget(cb1)

        vbox.addWidget(cb2)

        vbox.addWidget(cb3)

        vbox.addWidget(self.label)

        self.setLayout(vbox)

        self.setWindowTitle('Form with Multiple Checkboxes')

        self.setGeometry(60, 60, 350, 200)

        self.lblText = ''


        # Display the window in the center of the screen

        win = self.frameGeometry()

        pos = QDesktopWidget().availableGeometry().center()

        win.moveCenter(pos)

        self.move(win.topLeft())

        self.show()


    # Define function to read the user's input

    def Selected_Value(self, btn):

        if self.lblText != '':

            str = self.lblText

            strArray = str.split(' ,')

            self.lblText = ''

            for val in strArray:

                if btn.text() != val:

                   if self.lblText == '':

                        self.lblText = val

                   else:

                        self.lblText += ' ,' + val


            if btn.isChecked() == True:

                if self.lblText == '':

                    self.lblText = btn.text()

                else:

                    self.lblText += ' ,' + btn.text()

        else:

            if btn.isChecked() == True:

                if self.lblText == '':

                    self.lblText = btn.text()


                else:

                    self.lblText += ' ,' + btn.text()


        self.label.setText('You have selected \n' + self.lblText)

# Create app object and execute the app

app = QApplication(sys.argv)

ex = MultipleCheckbox()

sys.exit(app.exec_())

The following window will appear after executing the script. The default value of the second label is “Nothing is selected” and the value of the label will be changed when any checkbox is checked or unchecked by the user.


In the following output, two checkboxes are checked by the user, and the value of the second label is changed to “Chocolate, Pasta”.

Conclusion

The way of defining one or multiple checkboxes and reading the values of the selected checkbox(es) have been explained in this tutorial using two simple examples. The groups of checkboxes can be defined to select a particular checkbox from a group that is not shown here.

]]>
How to use Python NumPy mean(), min() and max() functions? https://linuxhint.com/use-python-numpy-mean-min-max-functions/ Sun, 31 Jan 2021 10:06:16 +0000 https://linuxhint.com/?p=88541

Python NumPy library has many aggregate or statistical functions for doing different types of tasks with the one-dimensional or multi-dimensional array. Some of the useful aggregate functions are mean(), min(), max(), average(), sum(), median(), percentile(), etc. The uses of mean(), min(), and max() functions are described in this tutorial. The mean() function is used to return the arithmetic mean value of the array elements. The arithmetic mean is calculated by dividing the sum of all elements of the array by the total number of array elements. If the particular axis is mentioned in the function, then it will calculate the mean value of the particular axis. max() function is used to find out the maximum value from the array elements or the elements of the particular array axis. min() function is used to find out the minimum value from the array elements or the particular array axis.

Use of mean() function

The syntax of the mean() function is given below.

Syntax:

numpy.mean(input_array, axis=None, dtype=None, out=None, keepdims=<no value>)

This function can take five arguments. The purposes of these arguments are described below:

input_array

It is a mandatory argument that takes an array as the value and the average of the array values is calculated by this function.

axis

It is an optional argument, and the value of this argument can be an integer or the tuple of integers. This argument is used for the multi-dimensional array. If the value of the axis is set to 0, then the function will calculate the mean of the column values, and if the value of the axis is set to 1, then the function will calculate the mean of the row values.

dtype

It is an optional argument that is used to define the data type of the mean value.

out

It is an optional argument and is used when the output of the function will need to store in an alternative array. In this case, the dimension of the output array must be the same as the input array. The default value of this argument is None.

keepdims

It is an optional argument, and any Boolean value can be set in this argument. It is used to transmit the output properly based on the input array.

This function returns an array of mean values if the value of the out argument is set to None, otherwise the function returns the reference to the output array.

Example: Using mean() function

The following example shows how the mean value of a one-dimensional and two-dimensional array can be calculated. Here, the first mean() function is used with a one-dimensional array of integer numbers, and the second mean() function is used with a two-dimensional array of integer numbers.

# import NumPy library

import numpy as np

# Create a one-dimensional array

np_array = np.array([6, 4, 9, 3, 1])

# Print array and mean values

print("The values of the one-dimensional NumPy array are:\n ", np_array)

print("The mean value of the one-dimensional array is:\n", np.mean(np_array))

# Create a two-dimensional array

np_array = np.array([[5, 3, 5], [5, 4, 3]])

# Print array and mean values

print("\nThe values of the two-dimensional NumPy array are:\n  ", np_array)

print("The mean values of the two-dimensional array are:\n", np.mean(np_array, axis=0))

Output:

The following output will appear after executing the above script.

Use of max() function

The syntax of the max() function is given below.

Syntax:

numpy.max(input_array, axis=None, out=None, keepdims=None, initial=None, where=None)

This function can take six arguments. The purposes of these arguments are described below:

input_array

It is a mandatory argument that takes an array as the value, and this function finds out the maximum value of the array.

axis

It is an optional argument, and its value can be an integer or the tuple of integers. This argument is used for the multi-dimensional array.

out

It is an optional argument and is used when the output of the function will need to store in an alternative array.

keepdims

It is an optional argument, and any Boolean value can be set in this argument. It is used to transmit the output properly based on the input array.

initial

It is an optional argument that is used to set the minimum value of the output.

where

It is an optional argument that is used to compare the array elements to find out the maximum value. The default value of this argument is None.

This function returns the maximum value for the one-dimensional array or an array of the maximum values for the multi-dimensional array.

Example: Using max() function

The following example shows the use of the max() function to find out the maximum value of a one-dimensional array.

# import NumPy library

import numpy as np

# Create NumPy array of integers

np_array = np.array([21, 5, 34, 12, 30, 6])

# Find the maximum value from the array

max_value = np.max(np_array)

# Print the maximum value

print('The maximum value of the array is: ', max_value)

Output:

The following output will appear after executing the above script.

Use of min() function

The syntax of the min() function is given below.

Syntax:

numpy.min(input_array, axis=None, out=None, keepdims=None, initial=None, where=None)

The purposes of the arguments of this function are the same as the max() function that has been explained in the part of the max() function. This returns the minimum value of the input array.

Example: Using min() function

The following example shows the use of the min() function to find out the minimum value of a one-dimensional array.

# import NumPy library

import numpy as np

# Create NumPy array of integers

np_array = np.array([21, 5, 34, 12, 30, 6])

# Find the maximum value from the array

max_value = np.max(np_array)

# Print the maximum value

print('The maximum value of the array is: ', max_value)

Output:

The following output will appear after executing the above script.

Conclusion

The purposes of three useful aggregate functions (mean(), max(), and min()) have been explained in this tutorial to help the readers to know the ways of using these functions in python script.

]]>
How to use python NumPy where() function with multiple conditions https://linuxhint.com/use-python-numpy-where-function/ Sun, 31 Jan 2021 05:39:20 +0000 https://linuxhint.com/?p=88397 NumPy library has many functions to create the array in python. where() function is one of them to create an array from another NumPy array based on one or more conditions. Some operations can be done at the time of array creation based on the condition by using this function. It can be used without any conditional expression also. How this function can be used with multiple conditions in python is shown in this tutorial.

Syntax:

numpy.where(condition,[x,y])

where the () function can take two arguments. The first argument is mandatory, and the second argument is optional. If the value of the first argument (condition) is true, then the output will contain the array elements from the array, x otherwise from the array, y. This function will return the index values of the input array if no optional argument is used.

Use of where() function:

Different types of Boolean operators can be used to define the condition of this function. The uses of where a () function with multiple conditions are shown in this part of the tutorial.

Example -1: Use of multiple conditions with logical OR

The following example shows the use of the where() function with and without the optional argument. Here, the logical OR has used to define the condition. The first where() function has applied in a one-dimensional array that will return the array of indices of the input array where the condition will return True. The second where() function has applied in two one-dimensional arrays will retrieve the values from the first array when the condition will return True. Otherwise, it will retrieve the values from the second array.

# Import NumPy library

import numpy as np

# Create an array using the list

np_array1 = np.array([23, 11, 45, 43, 60, 18,  33, 71, 52, 38])
print("The values of the input array :\n", np_array1)


# Create another array based on the multiple conditions and one array
new_array1 = np.where((np_array1  50))

# Print the new array
print("The filtered values of the array :\n", new_array1)

# Create an array using range values
np_array2 = np.arange(40, 50)

# Create another array based on the multiple conditions and two arrays
new_array2 = np.where((np_array1  60), np_array1, np_array2)

# Print the new array
print("The filtered values of the array :\n", new_array2)

Output:

The following output will appear after executing the above script. Here, the condition has returned True for the values 23,11,18,33, and 38 of the first array. The condition has returned False for the values 45, 43, 60, 71, and 52. So, 42, 43, 44, and 48 have been added from the second array for the values 45, 43, 60, and 52. Here, 71 is out of range.

Example -2: Use of multiple conditions with logical AND

The following example shows how the () function can be used with the multiple conditions defined by logical and applied in two one-dimensional arrays. Here, two one-dimensional NumPy arrays have been created by using the rand() function. These arrays have been used in the where() function with the multiple conditions to create the new array based on the conditions. The condition will return True when the first array’s value is less than 40 and the value of the second array is greater than 60. The new array has printed later.

# Import NumPy library

import numpy as np

# Create two arrays of random values
np_array1 = np.random.rand(10)*100
np_array2 = np.random.rand(10)*100


# Print the array values
print("\nThe values of the first array :\n", np_array1)
print("\nThe values of the second array :\n", np_array2)


# Create a new array based on the conditions
new_array = np.where((np_array1  60), np_array1, np_array2)

# Print the new array
print("\nThe filtered values of both arrays :\n", new_array)

Output:

The following output will appear after executing the above script. The condition has returned False for all elements. So, the returned array contains the values from the second array only.

Example-3: Use of multiple conditions in the multi-dimensional array

The following example shows how where the () function can be used with the multiple conditions defined by logical AND that will be applied in two multi-dimensional arrays. Here, two multi-dimensional arrays have been created by using lists. Next, these functions have applied in where() function to create the new array based on the condition. The condition used in the function will return True where the value of the first array is even and the value of the second array is odd; otherwise, the condition will return False.

# Import NumPy library

import numpy as np

# Create two multidimensional arrays of integer values
np_array1 = np.array([[5, 12, 21, 6, 11],  [6, 10, 15, 31, 8]])
np_array2 = np.array([[43, 19, 7, 34, 9],  [99, 22, 41, 5, 12]])

# Print the array values
print("\nThe values of the first array :\n", np_array1)
print("\nThe values of the second array :\n", np_array2)

# Create a new array from two arrays based on the conditions
new_array = np.where(((np_array1 % 2 == 0) & (np_array2 % 2 == 1)), np_array1, np_array2)

# Print the new array
print("\nThe filtered values of both arrays :\n", new_array)

Output:

The following output will appear after executing the above script. In the output, 43, 12, 7, 34, 9, 22, 41, 5, and 12 have added in the new array from the second array because the condition is False for these values. The first 12 value in the new array has added from the first array because the condition is True for this value only.

Conclusion:

where the () function of the NumPy library is useful for filtering the values from two arrays. Creating a new array by filtering the data from two arrays based on multiple conditions defined by logical OR and logical AND has been explained in this tutorial. I hope the readers will be able to use this function in their script properly after practicing the examples of this tutorial.

]]>
Python NumPy histogram() tutorial https://linuxhint.com/python-numpy-histogram/ Sun, 31 Jan 2021 02:24:46 +0000 https://linuxhint.com/?p=88131 A histogram is a mapping of intervals to frequencies. It is used to approximate the probability density function of the particular variable. It is known as the bar graph also. Many options are available in python for building and plotting histograms. NumPy library of python is useful for scientific and mathematical operations. One of this library’s important features is to implement histogram by using the histogram() function. This function is used to create the histogram that represents the frequency distribution of data graphically. In the histogram, the class intervals are represented by bins that look like horizontal rectangles, and the variable height represents the frequencies. The knowledge of creating NumPy array is necessary to understand the examples shown in this tutorial.

Syntax:

numpy.histogram(input_array, bins=10, range=None, normed=None, weights=None, density=None)

This function can take six arguments to return the computed histogram of a set of data. The purposes of these arguments are explained below.

  • input_array: It is a mandatory argument that is used to calculate the histogram data set.
  • bins: It is an optional argument that can take integer or a set of integer or string values. It is used to define the number of equal-width bins. An array of bin edges can be defined that increases monotonically. It can include the rightmost edge also which can use non-uniform bin widths. In the new NumPy version, the string value can be used for this argument.
  • range: It is an optional argument that is used to define the lower-upper ranges of the bins. The default range value is set by using max() and min() functions. The first element of the range must be less than or equal to the second element.
  • normed: It is an optional argument that is used to retrieve the number of samples in each bin. It may return false output for unequal bin widths.
  • weights: It is an optional argument that is used to define the array that contains weight values.
  • density: It is an optional argument that can take any Boolean value. If this argument’s value is True, then the number of samples in each bin will be returned; otherwise, the probability density function’s values will be returned.

This function can return two arrays. One is the hist array that contains the set of histogram data. Another is the edge array that contains the values of the bin.

Example 1: Print the histogram array

The following example shows the use of the histogram() function with a one-dimensional array and the bins argument with the sequential values. An array of 5 integer numbers has been used as an input array, and an array of 5 sequential values has been used as bins value. The content of the histogram array and bin array will print together as output.

# Import NumPy library
import numpy as np
# Call histogram() function that returns histogram data
np_array = np.histogram([10, 3, 8, 9, 7], bins=[2, 4, 6, 8, 10])
# Print the histogram output
print("The output of histogram is : \n", np_array)

Output:

The following output will appear after executing the above script.

Example 2: Print the histogram and bin arrays

The following example shows how the histogram array and the bin array can be created by using the histogram() function. A NumPy array has been created by using arrange() function in the script. Next, the histogram() function has called to return the histogram array and bin array values separately.

# Import NumPy library
import numpy as np

# Create NumPy array using arange()
np_array = np.arange(90)
# Create histogram data
hist_array, bin_array = np.histogram(np_array, bins=[0, 10,  25, 45, 70, 100])

# Print histogram array
print("The data of the histogram array is: ", hist_array)
# Print bin array
print("The data of the bin array is: ",  bin_array)

Output:

The following output will appear after executing the above script.

Example 3: Print the histogram and bin arrays based on density argument

The following example shows the use of the density argument of the histogram() function to create the histogram array. A NumPy array of 20 numbers is created by using arange() function. The first histogram() function is called by setting the density value to False. The second histogram() function is called by setting the density value to True.

# import NumPy array
import numpy as np
# Create a NumPy array of 20 sequential numbers
np_array = np.arange(20)
# Calculate the histogram data with false density
hist_array, bin_array = np.histogram(np_array, density=False)
print("The histogram output by setting density to False: \n", hist_array)
print("The output of bin array : \n", bin_array)
# Calculate the histogram data with true density
hist_array, bin_array = np.histogram(np_array, density=True)
print("\nThe histogram output by setting density to True: \n", hist_array)
print("The output of bin array : \n", bin_array)

Output:

The following output will appear after executing the above script.

Example 4: Draw a bar chart using histogram data

You have to install the matplotlib library of python to draw the bar chart before executing this example’s script. hist_array and bin_array have been created by using the histogram() function. These arrays have been used in the bar() function of the matplotlib library to create the bar chart.

# import necessary libraries
import matplotlib.pyplot as plt
import numpy as np

# Create histogram dataset
hist_array, bin_array = np.histogram([4, 10, 3, 13, 8, 9, 7], bins=[2, 4, 6, 8, 10, 12, 14])

# Set some configurations for the chart
plt.figure(figsize=[10, 5])
plt.xlim(min(bin_array), max(bin_array))
plt.grid(axis='y', alpha=0.75)
plt.xlabel('Edge Values', fontsize=20)
plt.ylabel('Histogram Values', fontsize=20)
plt.title('Histogram Chart', fontsize=25)

# Create the chart
plt.bar(bin_array[:-1], hist_array, width=0.5, color='blue')
# Display the chart
plt.show()

Output:

The following output will appear after executing the above script.

Conclusion:

The histogram() function has been explained in this tutorial by using various simple examples that will help the readers know the purpose of using this function and apply it properly in the script.

]]>
How to Use Python NumPy unique() Function https://linuxhint.com/use-python-numpy-unique-function/ Sat, 30 Jan 2021 16:21:40 +0000 https://linuxhint.com/?p=88115

NumPy library is used in python to create one or more dimensional arrays, and it has many functions to work with the array. The unique() function is one of this library’s useful functions to find out the unique values of an array and return the sorted unique values. This function can also return a tuple of array values, the array of the associative indices, and the number of times each unique value appears in the main array. The different uses of this function are shown in this tutorial.

Syntax:

The syntax of this function is given below.

array numpy.unique(input_array, return_index, return_inverse, return_counts, axis)

This function can take five arguments, and the purpose of these arguments is explained below.

  • input_array: It is a mandatory argument that contains the input array from which the output array will be returned by retrieving the unique values. If the array is not a one-dimensional array, then the array will be flattened.
  • return_index: It is an optional argument that can take a Boolean value. If this argument’s value is set to True, it will return the input array’s indices.
  • return_inverse: It is an optional argument that can take a Boolean value. If this argument’s value is set to True, then it will return the indices of the output array that contains the unique values.
  • return_counts: It is an optional argument that can take a Boolean value. If this argument’s value is set to True, then it will return the number of times each element of the unique array appears in the input array.
  • axis: It is an optional argument that can take any integer value or None. If no value is set for this argument, then the input array will be flattened.

The unique() function can return four types of arrays based on the argument values.

Example-1: Print the unique values of the one-dimensional array

The following example shows the use of the unique() function to create an array with the unique values of a one-dimensional array. A one-dimensional array of 9 elements has been used as the unique() function’s argument value. The returned value of this function has printed later.

# Import NumPy library

import numpy as np

# Create array of an integer number

np_array = np.unique([55, 23, 40, 55, 35, 90, 23, 40, 80])

# Print the unique values

print("The array of unique values are:\n", np_array)

Output:

The following output will appear after executing the above script. The input array contains 6 unique elements that are shown in the output.

Example-2: Print the unique values and indices based on the input array

The following example shows how the unique values and indices of the two-dimensional array can be retrieved using the unique() function. A two-dimensional array of 2 rows and 6 columns has been used as the input array. The value of the return_index argument has been set to True to get the input array indices based on the unique array values.

# Import NumPy library

import numpy as np

# Create a two-dimensional array

np_array = np.array([[6, 4, 9, 6, 2, 9], [3, 7, 7, 6, 1, 3]])

# Print the two-dimensional array

print("The content of the two-dimensional array: \n", np_array)

# Create the unique array and the index array of unique values

unique_array, index_array = np.unique(np_array, return_index=True)

# Print the values of unique and index arrays

print("The content of the unique array:\n", unique_array)

print("The content of the index array:\n", index_array)

Output:

The following output will appear after executing the above script. The input array contains 7 unique values. The output shows the array of 7 unique values and 7 indices of those values from the input array.

Example-3: Print the unique values and indices based on the output array

The following example shows how the unique values of a one-dimensional array and the indices based on the unique values by using the unique() function. In the script, a one-dimensional array of 9 elements has used as the input array. The value of the return_inverse argument is set to True that will return another array of indices based on the unique array index. Both unique array and index array have printed later.

# Import NumPy library

import numpy as np

# Create an array of integer values

np_array = np.array([10, 60, 30, 10, 20, 40, 60, 10, 20])

print("The values of the input array:\n", np_array)

# Create the unique array and inverse array

unique_array, inverse_array = np.unique(np_array, return_inverse=True)

# Print the values of the unique array and inverse array

print("The values of the unique array: \n", unique_array)

print("The values of the inverse array: \n", inverse_array)

Output:

The following output will appear after executing the above script. The output showed the input array, unique array, and inverse array. The input array contains 5 unique values. These are 10, 20, 30, 40, and 60. The input array contains 10 in three indices that are the first element of the unique array. So, 0 has appeared three times in the inverse array. The other values of the inverse array have been placed in the same way.

Example-4: Print the unique values and the frequency of each unique value

The following example shows how the unique() function can retrieve the unique values and the frequency of each unique value of the input array. The value of the return_counts argument has been set to True for getting the array of frequency values. A one-dimensional array of 12 elements has been used in the unique() function as an input array. The array of unique values and the frequency values have been printed later.

# Import NumPy library

import numpy as np

# Create an array of integer values

np_array = np.array([70, 40, 90, 50, 20, 90, 50, 20, 80, 10, 40, 30])

print("The values of the input array:\n", np_array)

# Create unique array and count array

unique_array, count_array = np.unique(np_array, return_counts=True)

# Print the values of the unique array and inverse array

print("The values of the unique array: \n", unique_array)

print("The values of the count array: \n", count_array)

Output:

The following output will appear after executing the above script. The input array, unique array, and count array have been printed in the output.

Conclusion

The detailed uses of unique() functions have been explained in this tutorial by using multiple examples. This function can return the values of different arrays and have shown here by using one-dimensional and two-dimensional arrays.

]]>
How to Use Python NumPy Random Function? https://linuxhint.com/use-python-numpy-random-function/ Sat, 30 Jan 2021 15:52:38 +0000 https://linuxhint.com/?p=88102

When the value of the number changes in each execution of the script, then that number is called a random number. The random numbers are mainly used for the various types of testing and sampling. Many ways exist in Python to generate the random number, and using a random module of the NumPy library is one way to do it. Many functions exist in random module to generate random numbers, such as rand(), randint(), random(), etc. The uses of the random() function of the random module to generate random numbers in Python are shown in this tutorial.

Generate random numbers using the random() function

The syntax of the random() function of the random module is given below.

Syntax:

array numpy.random.random(size=None)

This function can take one optional argument, and the default value of this argument is None.  Any integer or the tuple of integers can be given as the argument value that defined the shape of the array that will be returned as the output. If no argument value is provided, then a single floating number will be returned instead of an array. Different uses of the random() function are shown below.

Example-1: Use of random() function without any argument value

The following example shows the use of random() function without any argument that generates a scalar random number. The returned value of this function is printed later.

# import NumPy library

import numpy as np

# Call random() function without argument

random_number = np.random.random()

# Print the random value

print ("The output of the random() function is: ", random_number)

Output:

The following output will appear after executing the above script. It shows fractional random numbers.

Example-2: Use of random() function with an integer

The following example shows the use of the random() function with an integer in the value of the size argument. Here, 4 is set to the size argument. The means that the random() function will generate an array of four fractional random numbers. The output of the function is printed later.

# import NumPy library

import numpy as np

# Create an array of 4 random numbers

np_array = np.random.random(size=4)

# Print the array

print("The output of the random() function is:\n", np_array)

Output:

The following output will appear after executing the above script. It shows the one-dimensional array of fractional numbers.

Example-3: Use of random() function with a tuple of two integers

The following example shows how the random() function can be used to create a two-dimensional array of fractional random numbers. Here, (2,5) is used as the value of size argument, and the function will return a two-dimensional array of fractional numbers with 2 rows and 5 columns.

# import NumPy library

import numpy as np

# Create a two-dimensional array of random numbers

np_array = np.random.random(size=(2, 5))

# Print the array

print("The output of the random() function is: \n ", np_array)

Output:

The following output will appear after executing the above script. It shows a two-dimensional array of fractional random numbers.

Example-4: Use of random() function with a tuple of three integers

The following example shows how the random() function can be used to create a three-dimensional array of fractional random numbers. Here, (2,3,4) is used as the value of size argument, and the function will return a three-dimensional array of fractional numbers with 3 rows and 4 columns of 2 times.

# import NumPy library

import numpy as np

# Create a three-dimensional array of random numbers

np_array = np.random.random(size=(2, 3, 4))

# Print the array

print("The output of the random() function is: \n ", np_array)

Output:

The following output will appear after executing the above script. It shows a three-dimensional array of fractional random numbers.

Example-5: Use of random() function to generate coin flips

The following example shows the way to generate coin flips using random numbers. A NumPy array of 10 random fractional numbers has been created using the random() function. heads array has been created with the boolean values by comparing the array values with 0.7.  Next, the values of the heads array and the total number of True values in the heads array have been printed.

# Import NumPy library

import numpy as np

# Create an array of 10 random numbers

np_array = np.random.random(10)

# Create the coin flips array based on array values

heads = np_array > 0.7

# Print the head array

print("The values of head array are:\n", heads)

# Print the number of heads

print("\nTotal numbers of head are", np.sum(heads))

Output:

The following similar output will appear after executing the script. The different outputs will be generated at different times for random numbers. According to the following output, the total number of True values is 4.

Example-6: Use of random() function for plotting

The following example shows the way to generate the plots of a chart using the random() function. Here, the values of the x-axis have been generated using random() and sort() functions. The values of the y-axis have been generated using arange() function. Next, the plot() function of matplotlib.pyplot has been used to draw the plots of the chart. show() function has been used to display the chart.

# Import necessary libraries

import numpy as np

import matplotlib.pyplot as plt

# Create sorted array of random numbers

x_axis = np.sort(np.random.random(500000))

# Create x-axis for CDF(Continues Probability Distribution)

y_axis = np.arange(1, 500000)

# Plot CDF from random numbers

plt.plot(x_axis[::500], y_axis[::500], marker='.', markersize=5, color='red')

# Display the chart

plt.show()

Output:

The following similar output will appear after executing the above script.

Conclusion

The random() function is a very useful function of Python to perform different types of tasks. Various uses of the random() function have been shown in this tutorial using multiple examples. The purpose of using this function will be cleared for the readers after practicing the examples of this tutorial properly.

]]>