Coder Tutorial

Coder Tutorial

1675257841

Building a Modern Login and Registration Forms Using HTML, CSS, & JavaScript

Please watch the video https://youtu.be/N0TAP4NGN0g

#html #css #javascript #jquery #login #registration #webdevelopement 

Please visit https://www.codertutorial.com for more such articles.

Please like, share and subscribe if you found this short helpful.

Building a Modern Login and Registration Forms Using HTML, CSS, & JavaScript

Google Signin and Facebook Login In Flutter

facebook_and_google_signin

A new Flutter project.

Getting Started

This project is a starting point for a Flutter plug-in package, a specialized package that includes platform-specific implementation code for Android and/or iOS.

For help getting started with Flutter, view our online documentation, which offers tutorials, samples, guidance on mobile development, and a full API reference.

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add facebook_and_google_signin

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  facebook_and_google_signin: ^0.0.5

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:facebook_and_google_signin/facebook_and_google_signin.dart'; 

example/lib/main.dart

import 'package:flutter/material.dart';
import 'dart:async';

import 'package:flutter/services.dart';
import 'package:facebook_and_google_signin/facebook_and_google_signin.dart';

import 'facebook_screen.dart';


void main() {
  runApp( MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home:  HomeScreen(),
    );
  }
} 

Download Details:

Author: Gaurav123

Source Code: https://github.com/Gaurav123/facebook_and_google_signin

#flutter #login 

Google Signin and Facebook Login In Flutter

Store Login Data in a Database

Figuring out authentication is part of a secure data storage strategy. Find out how to store auth data safely in your database.

Almost every application requires user authentication; that is why authentication data storage is a common feature of database and application design. Special attention is needed to ensure data is kept secure and to avoid breaches that can compromise sensitive information.

Do I Need Authentication or Authorization?

Although both words are frequently used in a similar way, they do not mean the same thing. Most systems require both authentication and authorization, so let’s first explain what each one means.

Authentication

Authentication is a process that verifies that a person (in software application terms, the user) is whoever they say they are. It uses different mechanisms (password, security questions, fingerprint recognition, etc.) to confirm that the user is the person they are claiming to be. Modern systems combine many of these mechanisms and add additional methods (like one-time codes sent to email or phone) to authenticate users.

Authorization

Authorization verifies that the user has permission to perform a specific task or access specific data. A set of policies or rules may be established to define the actions a user can perform. Authorization is usually processed AFTER authentication.

The article APPLYING SIMPLE ACCESS CONTROL TO A SMALL DATA MODEL explains more about the difference between authentication and authorization. For now, we’ll review some authentication methods and explain how to securely store authentication data in a database.

Common Data Authentication Methods

There are many authentication methods applications employ to verify a user’s identity:

  • Passwords are the most common method, where a user provides a password to confirm their
  • Biometric methods include scanning fingerprints, faces, or even retinas. This usually requires specific hardware and the user’s physical presence, so such methods are often used to grant physical access to buildings or areas.
  • Two-Factor Authentication requires the user to provide a password and a second value to verify their Popular second verification methods include:
    • Secret questions.
    • Security tokens.
    • Security codes sent to email, SMS, authenticator apps, etc.
    • Scratch codes that users can print out and manually enter.
  • Social Authentication: Authentication is delegated to a social network (like Facebook, Twitter, or LinkedIn) or other platforms (like Google or Microsoft).

Not all of these methods require data to be stored on your own databases, so we’ll concentrate on those authentication methods that require storing sensitive information on your database.

Storing Passwords in a Database

Now we are going to review some of the best practices to store passwords in a database.

Plain Text, Encrypted or Hashed?

It should be quite obvious that storing passwords as plain text in our database is not a good idea, since it would mean that anyone with access to the database would be able to see all user passwords. Once we discard the option to store passwords in plain text, should we choose encryption or hashing?

Encryption is a two-way process that "scrambles'' readable text and converts it into something that is "illegible" until it is decrypted (using a "decryption key") and converted back to readable text. There are many encryption algorithms (like AES, DES, Twofish, and Blowfish).

How to Store Login Data in a Database

Hashing is a one-way process that converts a string (usually a legible one) into another (illegible) string. No matter the size of the input string, a hashing mechanism returns a fixed length string output. As with encryption, there are several hashing algorithms (like MD5, SHA-1, SHA-2) that can be used to hash user passwords; we will see some of them later in the article.

How to Store Login Data in a Database

You may initially be tempted to use encryption to store your passwords, but that is not the right approach! If you store encrypted passwords, the application will have to decrypt the stored password (using a decryption key) and compare it – every single time the user logs in. But if someone gets to know the decryption key, that person would be able to decrypt and access all stored passwords. That is a security concern.

If you store hashed rather than encrypted passwords, the application can simply hash the entered password and compare it with the stored hash. This way, nobody can decrypt the stored values.

Adding Salt and Pepper

Don’t worry – you’re still reading an article about login data and not a cooking recipe! Salting and peppering in this context refer to additional security measures taken to ensure passwords stored in a database are kept secure. Let’s discuss them.

Salting consists of generating a long and random string for each user and adding it to each typed-in password before hashing. That "salt" value must be stored together with the hashed password. This mechanism offers some notable benefits:

  • If two users select the same password, the hashed values would be different and nobody could detect that both users share the same password. This is because the passwords are hashed after they’ve been concatenated with the random string. And since each salt string is randomly generated, the combination of password and string will be unique.
  • Since passwords are usually short (most users do not use more than 10 or 12 characters), hackers have developed “rainbow tables” containing already hashed values for short strings. They can compare these values with a stored hash. Adding a lengthy string to the password makes using pre-calculated tables like rainbow tables more difficult.

To generate the salt for each user, use a reliable random generator like SECURERANDOM, which is recommended by OWASP. The formula to calculate the hashed value would be:

Hashed Password = HASH(INDIVIDUAL SALT + PASSWORD)

Peppering is simply adding an additional string to the “password + salt” combination before hashing it. (This extra string is often called “Secret” or “Pepper”; it’s not as frequently implemented as salting.) We are not going to dig into all the details of peppering; you can find them on WIKIPEDIA. The main differences between peppering and salting are:

  • The pepper string is common to all passwords.
  • The pepper string is stored on a separate layer (like the application layer) than the database. Even if the database is compromised due to SQL Injection or a lost backup, passwords are not compromised; the pepper part of the formula is not available, as it is stored on a different server or
  • The general formula to calculate the hashed value is:

Hashed Password = HASH(INDIVIDUAL SALT + PASSWORD + COMMON PEPPER)

Selecting the Right Algorithm

Some cryptographic algorithms are older; their usage should be avoided for password hashing, since they present some vulnerabilities. MD5 and SHA-1 have been reported as vulnerable due to collisions; the SHA-2 family of algorithms is currently the standard for hashing passwords. Having said that, newer options like SHA-3 offer more secure options. Longer hashes require more computation time to calculate and generate dictionary-based, brute force, or rainbow table attacks.

A Basic Model for Login Information

Now that we have explained the best way to store login data in a database, let’s take a quick look to a simple data model that stores user information:

How to Store Login Data in a Database

In this diagram, we have a UserAccount entity with the following attributes:

  • UserAccountID: An auto generated ID.
  • LoginName: The name used by the user to login in the system. Some systems may use an email address as a login name, but I would recommend keeping this as a separate attribute and allowing several options like a username, an email, or even a phone number.
  • FirstName: The user’s first name.
  • LastName: The user’s last name.
  • Email: The user’s email address. This is used to confirm account creation or send password reset confirmations.
  • PasswordHash: A hash string for the user’s password plus the salt and pepper combination.
  • PasswordSalt: A unique, randomly-generated string that is concatenated with the user’s password before it is hashed and stored in the PasswordHash column.
  • PasswordDate: The date when the user last updated or created their password; this is useful when the password needs to be renewed.

After you have designed your data structure to store passwords in your database, you should consider reading the article EMAIL CONFIRMATION AND RECOVERING PASSWORDS to enhance your application with the features described in the article.

Open Authentication Standards

We have just reviewed some considerations and recommendations for safely storing passwords in our databases. But a secure platform is not easy to design and implement, so you may also need to think about relying on experts for authentication.

There are open standards that can be used to delegate authentication to a reliable third party, like Google, Facebook or Twitter. Let’s do a quick overview of them.

OpenID

This standard allows authentication against an IDENTITY PROVIDER. As shown in the image below, the user logs in to the identity provider and it sends a certificate or key that confirms the user’s identity to the application making the request.

How to Store Login Data in a Database

This standard is an extension (you can see it as a special defined use case) of the OAuth 2.0 Framework explained below. When you log in into Google to access your YouTube account, you are using OpenID. Open ID allows only the ID, profile, email, address and/or phone number to be shared to the calling application.

OAuth (Open Authentication)

OAuth is an authorization standard, not an authentication standard, but it can be used for “pseudo-authentication”. Rather than asking a third party to certify that a user is who they claim to be, this authorization API provides a key to access some part of the user’s account with the provider (usually containing basic information like name and email address) and/or to perform actions like sending messages, posting tweets, etc.

How to Store Login Data in a Database

Although the provider does not certify an identity, the fact that it provides a key to access a specific account can be considered as proof that the user sending the key is actually the person they say they are.

If you use your Google or Facebook account to access a third-party application and you receive a message that you’re sharing your basic information with the third party, then you are using the more generic OAuth protocol rather than OpenID. The third-party application is accessing some information or tasks on the authorization provided rather than just validating your identity.

Although each method was designed for a different purpose, they can both be used to allow access to an application by delegating the authentication process to a well-known provider. This allows you to avoid designing and implementing a proprietary authentication feature – and the security risks that may exist if this feature is not well designed and implemented.

More About Storing Authentication Data in a Database

If you want to review more on storing authentication data in a database, see the article HOW TO STORE AUTHENTICATION DATA IN A DATABASE PART 4. It includes a sample data model used to store delegated authentication information (like authentication or authorization tokens and additional data) in your database.

Original article source at: https://www.vertabelo.com/

#sql #store #login #database 

Store Login Data in a Database

How to Setup Bootstrap Auth Login & Registration in Laravel 9

Have you ever built a website or a web application that requires users to login and register to use its features? If so, you’ve probably realized how much work it can be to create your own authentication system from scratch.

Laravel already provided user authentication but it is not by default implemented on the project.

You need to manually run a few provided commands to set it up.

In this article, you will see how to implement Bootstrap auth Login and Registration in Laravel 9 applications.

Contents

  1. Create Laravel project
  2. Database Configuration
  3. Install Laravel/UI
  4. Setup Bootstrap auth
  5. Run npm install && npm run dev
  6. Run migration
  7. Run project
  8. Output
  9. Conclusion

1. Create Laravel project

Skip this step if you have already created a Laravel project.

Using composer to create a laravel project –

composer create-project --prefer-dist laravel/laravel laravelproj

2. Database Configuration

Open .env file to update the database connection.

Specify the host, database name, username, and password.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=tutorial
DB_USERNAME=root
DB_PASSWORD=

3. Install Laravel/UI

Run the following command –

composer require laravel/ui

4. Setup Bootstrap auth

Run the following command –

php artisan ui bootstrap --auth
  • This command will generate files and update the route.
  • You can update the view, model, and migration files according to your requirement.
  • Authentication view files are stored in the resources/auth/ folder.
  • Controller files in Controllers/Auth/ folder.
  • By default generated login page has Email and password elements, and the registration page has Name, Email, Password, and Confirm Password elements.

5. Run npm install && npm run dev

Run the following command –

npm install && npm run dev

You have to keep it running.


6. Run migration

Open another terminal or command line window and run the following command –

php artisan migrate

This will create tables in the database.


7. Run project

php artisan serve

It gives the URL to run the project – http://127.0.0.1:8000


8. Output

View Output


9. Conclusion

After setting up users can register and login to your website. You do not need to write any extra code for registration and login.

If you found this tutorial helpful then don't forget to share.

Original article source at: https://makitweb.com/

#laravel #bootstrap #auth #login 

How to Setup Bootstrap Auth Login & Registration in Laravel 9

What Is Django? | How to Create A Project using Django

In this Django article, we will learn together what is Django? | How to create a project using Django. Django is a popular python server-side web framework. It’s ideal for data-driven websites with commonly needed utilities prebuilt into the platform. It offers flexibility and a collection of community-built extensions. 

Django’s framework is ideally a library of reusable modules. The integrated Python libraries make it easy for rapid development. For instance, for a web framework like Django, we have modules to work with HTTP requests, URLs, sessions, cookies, etc. 

All these functionalities are already provided in Django, there’s no need to code from scratch, that is why we use a framework like Django. This web framework is suitable for both front-end and back-end web development. It provides consistency among various Django projects.

Application Types

Django provides everything you need for faster deployment of your projects. As a result, it is considered a framework of choice by many developers. By using Django, you can develop complex and database-driven web applications that include: 

  • Machine learning
  •  E-commerce platforms·
  • Data analysis 
  • Content management

What are the advantages and disadvantages of Django framework 

 Advantages of Django Framework

  1. Implemented in Python: Python is one of those programming languages that has seen exponential growth in its demand and popularity over the last 5-6 years. As a programming language, Python has been known for its simple syntax, code readability, and English-like commands that make it a beginner-friendly language.
  2. Batteries included Framework: Django is a battery-included framework, which means it provides a lot of built-in functionalities. Instead of writing your own code (power code), you just need to import the packages or modules that you want to use.

Django batteries provide a wide range of contents that include:

  • Authentication users with auth package 
  • Admin Control with admin package 
  • Sessions management with Sessions package 
  • Show or manage Messages with Messages package 
  • Generate Google sitemap with Sitemaps package 
  • Postgres features with Postgres package 
  • Hooking with content types framework 
  1. Fast Processing: Django uses the MVT architecture which makes the whole process of transmitting over the Internet easier and faster.
  2. Supported by a vast and active Community: Django provides a huge community who are actively working on making the framework more beginner-friendly and stabilizing the framework by adding new features. Django documentation is quite easy to go through and is useful as a standalone tutorial, it will help you wrap your head around various features so you can use it as a primary source of information.
  3. Django is Immensely Scalable: One of the greatest advantages of Django is that it can handle traffic and mobile app API usage of more than 400 million+ users. It is designed in such a way that it can handle any kind of hardware additions.

Disadvantages of Django Framework

  • It cannot handle multiple requests at the same time.
  • Impacts performance of small web applications.
  • Knowledge of the entire system is needed to work with Django.
  • Relieves heavily on the ORM system.
  • The URL specification with Regex is not easy.

Django – Overview

MVT web framework

Django is an MVT web framework that is used to build web apps. It defines itself as a “batteries included” web framework, with stability and simplicity to help developers to write clean, efficient, and powerful code. It is one of the most famous web frameworks used by web developers and it is also one of the most used frameworks as well. It is used by  Instagram, Youtube, Spotify, Google, and even NASA for their website. 

Django works on MVT architecture which stands for Models Views Templates. MVT is a Django framework which is a variation of the famous MVC structure which stands for Model View Control. 

Django – Environment

How to Install Django Framework? 

Step 1 – Installing Latest Python Version:

  • Download Python Link: https://www.python.org/downloads/
  • If you want to check the python version or if it’s previously installed in your system, just open the terminal/command prompt and just type python or python3.

Syntax: python

Code:

1

2

3

4

linux@root: ~$ python3

Python 3.8.5 (default, Jan 27 2021, 15:41:15)

[GCC 9.3.0] on linux

>>> |

Step 2 – Creating Virtual Environment (venv):

A virtualenv is a tool for creating an insulated virtual python environment for python projects. To develop a virtual environment we need to install and then we need to activate the virtual environment.

To install: “ pip install virtualenv ”

To create and activate virtualenv: 

Syntax: virtualenv <virtualenv_name> 

Code:

1

2

3

linux@root:~/django_project/CellShop$ virtualenv venv

linux@root:~/django_project/CellShop$ . venv/bin/activate  

(venv) linux@root:~/django_project/CellShop$   

Step 3 – Installing Django:

For easy installation of Django, we use the pip installer package. pip is a Python package installer which is used to manage and install python software packages. We can install several python modules easily using pip. 

Syntax: pip install <module_name>

Code:   

1(venv) linux@root:~/django_project/CellShop$  pip install Django==3.2

Django Latest Version Download Link: https://www.djangoproject.com/download/

Step 4 – Django Database:

By default, Django supports SQLite3  database. But Django also supports various other database engines like MySQL, Oracle, PostgreSQL, etc and you can easily set up any of them based on your requirements.

Step 5 – Django WebServer:

Django contains a lightweight web server for creating and testing web applications. This webserver is pre-configured to work on the Django framework, and it restarts the web server whenever you modify the app code.

Django also creates wsgi.py files while creating  Django projects. WSGI stands for web server gateway interface. The purpose of this module is to provide a standard interface between applications built with Django and web servers. 

Django supports Apache web server and also other popular web servers. On our local system, by default, mostly Django runs on 8000 ports, i.e., 127.0.0.1:8000 or localhost:8000 and http://127.0.0.1:8000/.

Django – Creating a Project

How to create a project using Django Python Framework?

Now that we have successfully installed Django, let’s start creating a website using the Django Python framework. In Django, all the web apps you create are known as a project and a project is an addition of applications. An application is a set of program files that are implemented based on the Model-View-Templates (MVT) pattern. 

For example, let’s say we want to create an e-commerce website – the website is our Django project and the products, accounts, carts engine are applications. So for that, this structure makes it simpler to move an app between Django projects hence every application acts as an independent.

Creating Django Project:

To create a Django project, we need to execute this command on the terminal or cmd prompt.

Syntax: django-admin startproject <project_name> .

Code:

1(venv) linux@root:~/django_project/CellShop$ django-admin startproject CellShop

When we install Django, it brings a command line called Django admin. We can execute this program using cmd prompt or terminal. Django-admin includes various arguments. With the help of these arguments we will then be able to create a project called Cell Shop in the current folder. 

A folder will then be created  named “CellShop” with the following structure −

1

2

3

4

5

6

7

CellShop/

  CellShop/

      __init__.py

      settings.py

      urls.py

      wsgi.py

   manage.py

  • init.py: It means the CellShop folder is a package, so we can import various modules from this package into other modules 
  • setting.py: It is a module we define various settings for our applications 
  • urls.py: From this module, we define what should the users see when they see /index. /about, /contact, etc.
  • WSGI: It acts as a web server gateway interface.
  • manage.py: As the name implies we use this module to manage the Django project. With this we can start our web server, we can work with our database, etc.

Setting Up Your Django Project:

You need to set up your project in the subfolder which is named CellShop/settings.py : Then set “ DEBUG = True ”  to start your debugging system. Debug mode helps you get more clear  information about your project error. Never set a DEBUG to True for a live project. However, this has to be set to True if you want the Django light webserver to serve static files. Always do it only in the development mode only.

The database can be set up through the ‘Database’ dictionary which is also located in settings.py. The default database Engine selected is the SQLite database. Django also supports MySQL, Oracle, PostgreSQL, MongoDB, NoSQL, etc. You can allocate a database engine as per your requirements. SQLite is not as secure and flexible as Mysql, Oracle database, etc. 

SQLite:   “DATABASE: {‘default’:{‘ENGINE’: ‘django.db.backends.sqlite3’, …. }}”

MySQL: “DATABASE: {‘default’ {‘ENGINE’: ‘django.db.backends.postgresql_psycopg2’,  }}”

Oracle:   “DATABASE: {‘default’:{‘ENGINE’: ‘django.db.backends.oracle’, …. }}”

MongoDB:  “DATABASE: {‘default’:{‘ENGINE’: ‘django_mongodb_engine’, …. }}”

Before setting up any new database engine, make sure you have the same related database driver installed in your system.

You also have to set other options like: TIME_ZONE, INSTALLED_APPS, LANGUAGE_CODE, TEMPLATE, etc.

Now your project is successfully created and well configured.

To view the working status of the project, we need to execute our project using the below command by typing in terminal or cmd prompt.

Syntax: python manage.py runserver

Code:

1(venv) linux@root:~/django_project/CellShop$ python3 manage.py runserver

Once the above code is executed successfully, it will generate a developer server as given below −

(venv) linux@root:~/django_project/CellShop$ python3 manage.py run server

Watching for file changes with StatReloader

Performing system checks…

System check identified no issues (0 silenced).

You have 18 unapplied migration(s).

Run ‘python manage.py migrate’ to apply them.

April 08, 2021 – 18:01:29

Django version 3.2, using settings ‘CellShop.settings’

Starting development server at http://127.0.0.1:8000/

Quit the server with CONTROL-C.

Django – Apps Life Cycle

A project contains multiple apps. These apps don’t represent the entire application, they are small functional areas of the Django project. For example: Imagine you have to build a website or web app like Amazon. Amazon is a big eCommerce website. It has various functions. 

Instead of implementing all these functions in a single Django project, we divide this project into small functional areas that focus on one functionality. Like, we can implement functional areas for product management, order management, customer management, etc. 

The functions we have for managing the customers are different from the function for managing the products. So with this analogy, we divide the Django project into multiple Django apps. Each app  focuses on one functional area. Each app is essentially a python package. 

A project is a group of several applications. All applications have an objective or goal and can be reused in other projects. For instance, login/registration form on a website or web app can be an application and can be reused for other projects.

How to Create a Django Application?

Now for creating an app, type the below command in your command line terminal or cmd prompt.

Syntax: python manage.py startapp <app_name>

Code: 

1(venv) linux@root:~/django_project/CellShop$ python3 manage.py startapp products

You have successfully created an application in your Django project. Django created a “products” folder with the following application structure −

1

2

3

4

5

6

7

8

products/

    migrations/

     __init__.py

     admin.py

     apps.py

     models.py

     tests.py

     views.py

  • __init__.py – Just to make sure python treats this folder as a package.
  • admin.py – This file helps you to make changes to the application in the  admin interface.
  • Apps.py – It is used to store various configuration settings for these apps and it also contains AppConfig functions.
  • models.py – This is where all system models are stored.
  • tests.py – This is where your unit test is located.
  • views.py – This is where your app views are.

How to connect new apps with Django projects:

We currently have “products” application, now we need to register it with our Django “CellShop” project. For this, update the INSTALLED_APPS which is located in your project settings.py file (add your application name) –

1

2

3

4

5

6

7

8

9

INSTALLED_APPS = (

   'django.contrib.admin',

   'django.contrib.auth',

   'django.contrib.contenttypes',

   'django.contrib.sessions',

   'django.contrib.messages',

   'django.contrib.staticfiles',

   'products.apps.ProductsConfig',

)

Django – Admin Interface

One of the most important aspect of Django is that, it contains default automated admin controller interface. Django administrator site reads metadata from your models to provide a quick, modular link where trusted users can manage content on your site. On the Django administrator site, the use of the controller is limited to the organization’s internal management tool. It is not intended to build your entire frontend work.

Administrator is enabled on the default project template used by startproject. Admin interface is based on the Django contrib module. To proceed further, you need to make sure that other modules are imported into INSTALLED_APPS and MIDDLEWARE_CLASSES tuples of the CellShop/ settings.py file.

For INSTALLED_APPS make sure you have –

1

2

3

4

5

6

7

8

INSTALLED_APPS = (

   'django.contrib.admin',

   'django.contrib.auth',

   'django.contrib.contenttypes',

   'django.contrib.sessions',

   'django.contrib.messages',

   'django.contrib.staticfiles',

   'products.apps.ProductsConfig',

MIDDLEWARE_CLASSES –

1

2

3

4

5

6

7

8

MIDDLEWARE_CLASSES = (

   'django.contrib.sessions.middleware.SessionMiddleware',

   'django.middleware.common.CommonMiddleware',

   'django.middleware.csrf.CsrfViewMiddleware',

   'django.contrib.auth.middleware.ConfirmationMiddleware',

   'django.contrib.messages.middleware.MessageMiddleware',

   'django.middleware.clickjacking.XFrameOptionsMiddleware',

)

Before launching your server, to access your Admin Interface, you need to start the database

1. You need to make migrations after creating the models in products/models.py

Syntax: $ python manage.py makemigrations

Code: 

1(venv) linux@root:~/django_project/CellShop$ python3 manage.py makemigrations

2. You need to simply write below code to do migrations:

Syntax: $ python manage.py migrate

Code:

1(venv) linux@root:~/django_project/CellShop$ python3 manage.py migrate

Syncdb is a django shell command to create tables for the first time for applications added to INSTALLED_APPS for settings.py. Syncdb will create the required tables or groups depending on your database type, which is required for the administrator interface to work. Even if you don’t have a superuser, you will be notified that you have created it.

If you need to create a user to sign in with, use the create super user command. 

By default, login to administrator requires that the user has the is_staff attribute set to True.

Finally, decide which models of your application should be configured in the controller interface. For each of these types, register with the administrator as described in ModelAdmin.

If you already have a superuser or have missed it, you can always build using the following code –

Syntax: $ python manage.py create superuser

Code:  

1(venv) linux@root:~/django_project/CellShop$ python3 manage.py createuperuser

After executing the above code on the terminal it will ask for username, email, and password. So according to your requirement, complete this process and it will create a superuser Django for you.

Now to start Admin Interface, we need to make sure we have prepared the URL of the administrator interface. Open CellShop / urls.py and you should have something in common. 

1

2

3

4

5

urlpatterns = [

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

path('', include('products.urls')),

path('accounts/', include('accounts.urls')),

]

Now just execute the project on webserver.

Code: $ python manage.py runserver

And your administrator interface is available at: http: // 127.0.0.1: 8000 / admin /

Once connected to your superuser account, you will see the default admin panel screen which consists of Users and Groups. 

This interface will allow you to control Django groups and users, with all the models registered in your app. The interface gives you the ability to use some “CRUD”operations (Create, read, update, delete) to your models.

Django – Creating Views

Django View is a layer of business logic. It is responsible for processing the user request and sending back a valid response. It downloads data from the model, gives each template access to the specific data to be displayed, and can perform further data processing. Nowadays, Django views can be a process of requesting and retrieving feedback.

The view function, or “view” for short, is simply a Python function that takes a web request and returns the answer to the web. This response could be HTML content on a Web page or redirect, or a 404 error, or an XML document, or an image, etc. 

Example: When using views to create web pages, note that you need to link a view to an appropriate URL to see it as a web page.

In Django, views should be created in the views.py app file.

Simple view

We will create a simple view on the products app to say “Hello to my app!”

Write below code in your products/view.py –

from django.http import HttpResponse

def new(request):

return HttpResponse(‘Hello to my app!’)

In this view, we use HttpResponse to provide HTML (as you may have noticed that we have HTML with a strong code in view). To view this as a page we just need to put it in a URL (this will be discussed in the next subtopics).

We used HttpResponse to provide HTML in preview. This is not the best way to provide pages. Django supports MVT pattern to create a preview, Django – MVT likes, we will need –

Template: products / templates / hello.html

To modify your project, i.e., CellShop / settings.py, go to TEMPLATE -> directories (DIRS) and add a BASE_DIR and template. This will merge the base directory and templates.

Before Changes DIRS: 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

TEMPLATES = [

{

'BACKEND': 'django.template.backends.django.DjangoTemplates',

'DIRS': [],

'APP_DIRS': True,

'OPTIONS': {

'context_processors': [

'django.template.context_processors.debug',

'django.template.context_processors.request',

'django.contrib.auth.context_processors.auth',

'django.contrib.messages.context_processors.messages',

],

},

},

]

After Changes DIRS:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

TEMPLATES = [

{

'BACKEND': 'django.template.backends.django.DjangoTemplates',

'DIRS': [BASE_DIR, 'templates'],

'APP_DIRS': True,

'OPTIONS': {

'context_processors': [

'django.template.context_processors.debug',

'django.template.context_processors.request',

'django.contrib.auth.context_processors.auth',

'django.contrib.messages.context_processors.messages',

],

},

},

]

Now we can write in our view like –

1

2

3

4

5

6

7

8

9

10

11

12

13

14

from django.shortcuts import render

from django.http import HttpResponse

def hello(request, id):

           return render(request, 'hello.html')

Views can also receive parameters -

from django.shortcuts import render

from django.http import HttpResponse

def hello(request, id):

    text = "<h1> welcome to my app id % s! </h1>"% id

           return HttpResponse(text')

Views can also receive parameters –

1

2

3

4

5

6

from django.shortcuts import render

from django.http import HttpResponse

def hello(request, id):

    text = "<h1> welcome to my app id % s! </h1>"% id

           return HttpResponse(text')

Views can also return objects in form of dictionary-

1

2

3

4

5

6

from django.shortcuts import render

from django.http import HttpResponse

from .models import Product

def product(request):

    products = Product.objects.all()

    return render(request, 'index.html', {'products': products})

When linked to a URL, the page will display the forwarded number as a parameter. Note that the parameters will be passed by URL.

Django – URL Mapping

The Django URL router is much more complex than other frameworks like Laravel, etc. It uses common expressions. However, creating the URL path itself is not difficult at all, it is just a syntax that you may not feel comfortable with at first.

Now we have a practical idea as explained in the previous topics. We want to access the project using the URL. Django has its own way to map URLs and this is done by editing the urls.py project of your file (CellShop / urls.py). The URLS.py file looks like –

1

2

3

4

5

6

7

8

9

10

11

"""Pyshop URL Configuration

     ....

"""

from django.contrib import admin

from django.urls import path, include

urlpatterns = [

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

path('', include('products.urls')),

path('accounts/', include('accounts.urls')),

]

When a user makes a page request to your web app, the Django controller replaces the corresponding view with the url.py file, and retrieves the HTML response or 404 error that is requested File not found, if a file is not available. In urls.py, the most important thing is listings for “urlpatterns”. This is where you define the map between URLs and views. Mapping is the motto of similar URL patterns –

1

2

3

4

5

6

7

8

from django.urls import path

from . import views

urlpatterns = [

path('', views.front, name='front'),

path('product', views.index, name='index'),

path('hello/', views.new),

]

In urls.py, the most important thing is listings for “urlpatterns”. This is where you define the mapping between URLs and views. Mapping is the motto of similar URL patterns –

The tagline lists the URL “hello/” to the hello view created in the myapp  products / view.py file. As you can see above the map is made up different elements are as follows-

  • Python mode of view – Same as when importing modules.
  • The route dispute must be a thread or gettext_lazy() containing the URL pattern.
  • Dispute view is a view function or an as_view() class-based viewing result. It can also be written as django.urls.include().
  • Name – In order to perform URL reversal, you will need to use the URL patterns named after them as in the examples above. When you’re done, just start the server to access your view via: http: //127.0.0.1/hello
  • Normally, the location of the application name should be specified by the installed module. If the application namespace is set, the namespace dispute can be used to set a different example location.
  • include() also acceptance as a dispute can be a retrieval of URL or 2-Tuple patterns that contain probability as well as system name names.

How to Edit URLs?

Till now we were creating URLs in the “Cell Shop / urls.py” file, however as mentioned earlier about Django and app building, the benefit is that it can be reused in various projects. You can easily see the errors  if you save all your URLs to the “projecturl.py” file. The best practice is to create a “urls.py” for each application and install it in the main urls.py file.

We need to create a urls.py file on myapp using the following code –

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

from django.urls import path

from . import views

urlpatterns = [

path('', views.front, name='front'),

path('product', views.index, name='index'),

path('hello/', views.new),

]

Thereafter CellShop / urls.py will switch to the following -

from django.contrib import admin

from django.urls import path, include

urlpatterns = [

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

path('', include('products.urls')),

path('accounts/', include('accounts.urls')),

]

Thereafter CellShop / urls.py will switch to the following –

1

2

3

4

5

6

7

8

from django.contrib import admin

from django.urls import path, include

urlpatterns = [

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

path('', include('products.urls')),

path('accounts/', include('accounts.urls')),

]

We’ve included all URLs from the myapp app. Home.html achieved with “/ hello” is now “/ myapp / hello” which is the best and most understandable web application.

Now let’s assume we have another idea for myapp “morning” and we want to put it in my app / urls.py, then we will change our myapp / urls.py into –

1

2

3

4

5

6

7

8

9

from django.urls import path

from . import views

urlpatterns = [

path('', views.front, name='front'),

path('product', views.index, name='index'),

path('hello/', views.new),

path('morning/', views.new, name=”morning”),

]

As you can see, we are now using the first item of our urlpatterns Tuple. This can be used when you want to change the name of your application.

Sending Parameters to Views

Now that we know how to map URL, how to edit them, now let’s see about errors handlers.

django.conf.urls jobs for use at URLconfs

static () 

1

2

3

4

5

6

7

8

9

from django.conf import settings

from django.conf.urls.static import static

urlpatterns = [

    # ... all your URLconf goes here ...

] + static (settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)

url ()

This function is alias in django.urls.re_path ().

url ()

This function is alias in django.urls.re_path ().

Error Handler:

1. 400:

A drive, or cable representing a full Python input line in view that should be called when an HTTP client has sent a request that created an error and a response with 400 status code.

By default, this is Django.views.defaults.bad_request (). If you are using a custom view, make sure it accepts different requests and arguments and returns HttpResponseBadRequest.

2. 403:

An expensive string, or a string representing a full Python import line in the view to be called if the user does not have the necessary permissions to access the app.

By default, this is Django.views.defaults.permission_denied (). If you are using a custom view, make sure it accepts the application with different arguments and returns HttpResponseForbidden.

3. 404:

A dial, or a string representing a full Python import line in the view that should be called if there are no matching URL patterns.

By default, this is Django.views.defaults.page_not_found (). If you are using a custom view, and if it has errors that it will return HttpResponseNotFound.

4. 500:

A drive, or cable representing a full Python input line in the view should be called in case of server errors. Server errors occur when you have time-lapse errors in the view code.

By default, this is Django.views.defaults.server_error (). If you are using a custom view, make sure it accepts the request dispute and retrieves HttpResponseServerError.

Django – Template System

The Django template system is used to separate data, the way it is presented and viewed by the user. The template layer is the same as the MVC view layer. There are already template formats besides HTML, if you want to generate XML documents or JSON files, etc.

DRY is one of the main building codes of Django and is a design pattern that stands for “Do Not Repeat Yourself”. It is all about keeping the code simple and non repeating. For example, the template should be divided into useful items such as a sidebar, main navigation bar, page title, page footer and so on. This reduces duplication and is designed to write code that is efficient. 

Django makes it possible to distinguish between python and HTML, python goes to view and HTML enters templates. Linking the two, Django relies on dedicated performance and the language of the Django template.

Django Template (DTL) Language:

Django template engine provides a small language to define the user-facing layer of the program.

Flexible Display:

The variation looks like this: {{variable}}. The template replaces the dynamic variable sent by the view to the third parameter of the rendering function. Let’s change our hello.html to show today –

1

2

3

4

5

6

7

hello.html

<html>

   <body>

      Hello World !!! <p> Today is {{today}} </p>

   </body>

</html>

After that our view will change to –

1

2

3

def hello (request):

   today = datetime.datetime.now(). date ()

   roll back (request, "hello.html", {"today": today})

We will now get the next result after getting the URL / myapp / hello –

Hello World!!!

Today is September 11, 2015

As you may have noticed, if the variable is not a thread, Django will use the __str__ method to indicate it; and with the same goal, you can achieve the quality of an object just as you do in Python. 

For example: if we wanted to show the date year, my variable would be: {{today.year}}.

Filters:

They help you adjust the dynamics during the display. The filter structure looks like the following: {{var | filters}}.

Other examples –

    {{string | truncatewords: 80}} – This filter will shorten the thread, so you’ll only see the first 80 words.

    {{string | lower}} – Converts a unit of characters into lowercase letters.

    {{string | escape | line 

breaks}} – The content of the line runs, then converts the line split into tags.

Tags:

Tags allow you to perform the following tasks: if conditions, loop, template asset and many more.

As like Python you can use if, else and elif in your template –

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

<html>

   <body>

    

      Hello World !!! <p> Today is {{now}} </p>

      Singa

      {% if now.day == 1%}

       

      the first day of the month.

      {% elif now.day == 30%}

       

      last day of the month.

      {% more %}

       

      I do not know.

      {% endf %}  

   </body>

</html>

In this new template, depending on the date, the template will give you a certain value.

Mark the tag for

Like ‘if’, we have the ‘for’ tag, which works in the same way as Python. Let’s change our mindset so we can move the list to our template –

def hello (request):

   now = datetime.datetime.now (). date ()

week_days = [‘Sun’,’Mon’, ‘Tue’, ‘Wed’, ‘Thu’, ‘Fri’, ‘Sat’]

   return (request, “hello.html”, {“now”: now, “days_of_week”: week_days})

Block and Expand Tags:

The template program cannot be completed without a template asset. Which means that when designing your own templates, you should have a large template with empty space for a child template to fill in according to their need, such as a page that may require a special css of the selected tab.

Syntax: {% block <block_name>%}{% endblock %}

Code: 

1

2

3

4

5

6

7

8

9

10

11

12

13

”””

{% extends 'base.html' %} {% block content %}

<div

class="bg-image d-flex justify-content-center align-items-center"

style="

background-image: url('https://www.hdwallpapersfreedownload.com/uploads/large/fruits/fruits-background.jpg');

height: 100vh;

"

>

<h1 class="text-white">Fresh Fruits Shop</h1>

</div>

{% endblock %}

”””

Django – Models

Django model uses a powerful ORM layer that makes it easy to deal with databases and data which also speeds up the development process.

With the exception of Object-Relational-Mapping, developers need to create their own tables and define queries or procedures that sometimes translate into large SQL values that tend to be complex and difficult to track.

The ORM layer allows you to write all table descriptions with a simple python code, and takes care of translating that into appropriate query language of choice, and also helps with CRUD functionality.

In fact, the developer does not need to know the most complex SQL or what it translates, however, it is important to note that understanding SQL will allow you to write better and faster questions and make your website more secure.

Unlike other frameworks, the models are placed in a single file, usually, models.py, which can make it sound cramped for large projects.

Django supports multiple data systems. SQLite is ready for testing and development as it can be used out of the box without installing any other software. For production, you can go to MYSQL or PostgreSQL, and if you want a NoSQL database, you can use MongoDB in our Django projects.

Code:

1

2

3

4

5

6

7

8

9

10

11

12

from django.db import models

class Product(models.Model):

name = models.CharField(max_length=255)

price = models.FloatField()

stock = models.IntegerField()

image_url = models.CharField(max_length=2083)

class Offer(models.Model):

code = models.CharField(max_length=10)

description = models.CharField(max_length=255)

discount = models.FloatField()

Django – Page Redirection

In a web application, page redirection is required for a variety of reasons. You may wish to redirect a user to another page when a specified action is performed, or simply in the event of an error. When a user joins in to your website, he is frequently forwarded to either the main home page or his own dashboard. The ‘redirect’ method is used in Django to perform redirection.

The ‘redirect’ method takes two arguments: the URL to which you wish to be redirected as a string, and the name of the view.

1

2

3

4

5

6

7

8

9

10

11

12

13

def hello(request):

   today = datetime.datetime.now().date()

   daysOfWeek = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']

   return render(request, "hello.html", {"today" : today, "days_of_week" : daysOfWeek})

     

def viewBlog(request, blogId):

""" A view that displays a specific article depending on its ID."""

   text = "Displaying Number of Blog : %s" %blogId

   return HttpResponse(text)

     

def viewBlogs(request, year, month):

   text = "Displaying Blogs of : %s/%s"%(year, month)

   return HttpResponse(text)

Let’s alter our hello view to redirect to djangoprojectsamples.com and our viewBlog to redirect to our internal ‘/myapp/blogs’. To accomplish this, myapp/view.py will be renamed to

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

from django.shortcuts import render, redirect

from django.http import HttpResponse

import datetime

  

# Create your views here.

def hello(request):

   today = datetime.datetime.now().date()

   daysOfWeek = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']

   return redirect("https://www.djangoprojectsamples.com")

     

def viewBlog(request, blogId):

   """ A view that display an article based on his ID"""

   text = "Displaying Number of Blog: %s" %blogId

   return redirect(viewBlogs, year = "2021", month = "08")

     

def viewBlogs(request, year, month):

   text = "Displaying blogs of: %s/%s"%(year, month)

   return HttpResponse(text

In the preceding example, we imported redirect from django.shortcuts, and for redirection to the Django official website, we simply pass the full URL as a string to the ‘redirect’ method, whereas for the second example (the viewBlog view), the ‘redirect’ method takes the view name and its parameters as arguments. When you go to /myapp/hello, you will see the following screen.

And going to /myapp/blog/40 will bring you to the following screen.

By adding the permanent = True argument, you may also indicate whether the ‘redirect’ is temporary or permanent. The user will see no difference, yet these are the factors that search engines use when ranking your website.

Django – Sending E-mails

For sending e-mail, Django has a ready-to-use light engine. You only need to import smtplib, just like Python. Simply import django.core.mail into Django. Edit your project settings.py file and specify the following options to start sending e-mail. –

EMAIL_HOSTsmtp server
EMAIL_HOST_USERsmtp server login credential
EMAIL_HOST_PASSWORDsmtp server password credential
EMAIL_PORTserver port of smtp 
EMAIL_USE_TLS or _SSLif secure connection then it’s TRUE

Sending a Simple E – Mail

Let’s create a “sendSimpleEmail” view to send a simple e-mail for the second example (the viewBlog view), the ‘redirect’ method takes the view name and its parameters as arguments.

1

2

3

4

5

6

from django.core.mail import send_mail

from django.http import HttpResponse

  

def sendSimpleEmail(request,emailto):

   res = send_mail("hello ramesh", "How are you?", "ramesh@gmail.com", [emailto])

   return HttpResponse('%s'%res)

List of parameter details to send an e mail:

subjectSubject of the email
message Body of the email 
from_emailFrom email 
recipient_listEmail receivers list 
fail_silently If false, send mail will throw an exception if there is a problem.
auth_userUser login 
auth_password User Password 
connectionBackend of the email
html_messageEmail will be multipart or alternative

1

2

3

4

5

from django.conf.urls import patterns, url

  

urlpatterns = paterns('myapps.views',url(r'^sampleemail/(?P<emailto>

   [\w.%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4})/',

   'sendSampleEmail',name = 'sendSampleEmail'),

So, if you go to /myapps/sampleemail/ramesh@gmail.com, you’ll see something like this:

Using send mass mail to send many emails

The method returns the number of messages sent successfully. This is similar to send mail but adds a datatuple parameter, thus our sendMassEmail view will be datatuple.

1

2

3

4

5

6

7

8

from django.core.mail import send_mass_mail

from django.http import HttpResponse

  

def sendMassEmail(request,emailto):

   msg1 = ('subject 1', 'message 1', 'ramesh@gmail.com', [emailto1])

   msg2 = ('subject 2', 'message 2', 'suresh@gmail.com', [emailto2])

   res = send_mass_mail((msg1, msg2), fail_silently = False)

   return HttpResponse('%s'%res)

Let’s create the URL to access the view:

1

2

3

4

5

from django.conf.urls import patterns, url

  

urlpatterns = paterns('myapps.views', url(r'^massEmail/(?P<emailto1>

   [\w.%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4})/(?P<emailto2>

   [\w.%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4})', 'sendMassEmail' , name = 'sendMassEmail'),)

When accessing /myapps/massemail/ramesh@gmail.com/suresh@gmail.com/, we get –

Send_Mass_Mail parameter details:

datatuplesEach element of the tuple is (subject, message, from email, recipient list).
fail_silentlyIf false, send mail will throw an exception if there is a problem.
auth_userUser Login
auth_passwordUser Password 
connectionBackend of e- mail

Two messages were successfully sent, as shown in the image above.

$python -m smtpd -n -c DebuggingServer localhost:1025

This implies that all of your sent e-mails will be printed to stdout, and the dummy server will be accessible at localhost:1025.

Sending HTML E-Mail

It’s as simple as sending an HTML message in Django >= 1.7.

1

2

3

4

5

from django.core.mail import send_mail

  

from django.http import HttpResponse

   res = send_mail("hello ramesh", "How are you ?", "ramesh@gmail.com",

         ["ramesh@gmail.com"], html_message=")

This will result in a multipart/alternative e-mail being sent.

However, with Django 1.7, HTML messages are sent via the django.core.mail module. The EmailMessage class then calls the object’s’send’ method.

Let’s generate a “sendHTMLEmail” view to send an HTML e-mail.

1

2

3

4

5

6

7

8

9

from django.core.mail import EmailMessage

from django.http import HttpResponse

  

def sendHTMLEmail(request , emailto):

   html_content = "<strong>Comment tu vas?</strong>"

   email = EmailMessage("my subject", html_content, "ramesh@gmail.com", [emailto])

   email.content_subtype = "html

  res = email.send()

   return HttpResponse('%s'%res)

Information for the EmailMessage class construction parameters:

Subject E- mail subject
Message Body in HTML 
from_emailE- mail from whom
to Receiver’s list 
bcce- mail address for list of bcc receivers 
connectionBackend email connection

Let’s make a URL to get to our view:

1

2

3

4

5

6

from django.conf.urls import patterns, url

  

urlpatterns = paterns('myapps.views', url(r'^htmlemail/(?P<emailto>

   [\w.%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4})/',

   'sendHTMLEmail' , name = 'sendHTMLEmail'),)

return HttpResponse('%s'%res)

viewBlog view), the ‘redirect’ method takes the view name and its parameters as arguments.

Django – Generic Views

As we’ve seen, writing views can be somewhat difficult in some circumstances. Assume you require a static or listing page. Generic views are a convenient method to put up those simple views in Django.

Generic views, unlike classic views, are classes rather than functions. In django.views.generic, Django provides a set of generic view classes, and every generic view is either one of those classes or a class that derives from one of them.

There are more than ten generic classes.

1

2

3

4

>>> import django.views.generic

>>> dir(django.views.generic)

  

['ArchiveIndexView', 'CreateView', 'DateDetailView', 'DayArchiveView', 'DeleteView', 'DetailView', 'FormView', 'GenericViewError', 'ListView', 'MonthArchiveView', 'RedirectView', 'TemplateView', 'TodayArchiveView', 'UpdateView', 'View', 'WeekArchiveView', 'YearArchiveView', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__', 'base', 'dates','detail', 'edit', 'list']

This is the view that you can use for your generic view. Let’s have a look at an illustration to see how it works.

Static Page of HTML: (samplestatic.html)

1

2

3

4

5

<html>

   <body>

      This will be Static HTML Page!!

   </body>

</html>

If we implemented it the way we learnt before, we’d have to rename as myapp/sviews.py

1

2

3

4

5

from django.shortcuts import render

  

def static(request):

   return render(request, 'samplestatic.html', {})

 return HttpResponse('%s'%res

1

2

3

from django.conf.urls import patterns, url

urlpatterns = patterns("myapps.views", url(r'^static/', 'static',

name = 'samplestatic'),

The good way is to use generic views. For that, our myapps/views.py will become –

1

2

3

4

from django.views.generic import TemplateView

  

class StaticView(TemplateView):

   template_name = "samplestatic.html"

our myapp/samplestatic

1

2

3

4

from myapp.views import StaticView

from django.conf.urls import patterns

  

urlpatterns = patterns("myapps.views", (r'^static/$', StaticView.as_view()),)

We can also do the following to achieve the same result:

There has been no change in the view.py

Change the name of the url.py file

1

2

3

4

5

6

from django.views.generic import TemplateView

from django.conf.urls import patterns, url

  

urlpatterns = patterns("myapps.views",

   url(r'^static/',TemplateView.as_view(template_name = 'samplestatic.html')),)

 return HttpResponse('%s'%res)

viewBlog view), the ‘redirect’ method takes the view name and its parameters as arguments.

Change the name of the url.py file

1

2

3

4

5

from django.views.generic import TemplateView

from django.conf.urls import patterns, url

  

urlpatterns = patterns("myapps.views",

   url(r'^static/',TemplateView.as_view(template_name = 'samplestatic.html')),)

In our Dreamreal model, we’ll make a list of all entries. Using the ListView generic view class makes this simple. Update the url.py file as follows:

1

2

3

4

5

6

7

from django.views.generic import ListView

from django.conf.urls import patterns, url

  

urlpatterns = patterns(

   "myapps.views", url(r'^dreamlist/', ListView.as_view(model = Dreamreal,

      template_name = "dream_list.html")),

)

It’s worth noting at this point that the generic view passes object list to the template as a variable. You’ll need to add a context object name argument to the as view method if you wish to name it yourself. The sampleurl.py file will then be renamed

1

2

3

4

5

6

from django.views.generic import ListView

from django.conf.urls import patterns, url

  

urlpatterns = patterns(

   "myapps.views", url(r'^dreamlist/', ListView.as_view(model = Dreamreal,

      template_name = "dream_list.html")),

It’s worth noting at this point that the generic view passes object list to the template as a variable. You’ll need to add a context object name argument to the as view method if you wish to name it yourself. The sampleurl.py file will then be renamed

1

2

3

4

5

6

7

from django.views.generic import ListView

from django.conf.urls import patterns, url

  

urlpatterns = patterns("myapp.views",

   url(r'^dreamreals/', ListView.as_view(

      template_name = "dream_list.html")),

      model = Dreamreal, context_object_name = ”dreamreals_objects” ,)

the template will be

viewBlog view), the ‘redirect’ method takes the view name and its parameters as arguments

1

2

3

4

5

6

7

{% extends "mainsample_template.html" %}

{% block content %}

Dreamreals:<p>

{% for dr in object_list %}

{{dr.name}}</p>

{% endfor %}

{% endblock %}

Django – Form Processing

In Django, generating forms is quite similar to establishing a model. Again, all we have to do is inherit from the Django class, and the form fields will be the class attributes. To store our app forms, create a forms.py file in the myapp subdirectory. We’ll make a login page.

myapps/sampleforms.py

1

2

3

4

5

6

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

from django import forms

  

class LoginForm(forms.Form):

   user = forms.CharField(max_length = 150)

   password = forms.CharField(widget = forms.PasswordInput())

The field type can take the “widget” parameter for html rendering, as seen above; in our case, we want the password concealed rather than displayed. Django also includes a number of other widgets, such as DateInput for dates, CheckboxInput for checkboxes, and so on.

Using Form in View:

GET and POST are the two types of HTTP queries. The type of the request is set in the “method” attribute of the request object supplied as a parameter to your view in Django, and all data passed

Loin view myapps/view.py

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

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

from myapps.forms import LoginForm

  

def login(request):

   username = "not logged in"

    

   if request.method == "POST":

      #Get the posted form

      MyLoginForm = LoginForm(request.POST)  #login form

       

      if MyLoginForm.is_valid():

         username = MyLoginForm.cleaned_data['username'] #validation

   else:

      MyLoginForm = Loginform()

         

   return render(request, 'loggedinsample.html', {"username" : username})

The outcome of the login form submitted via loggedinsample.html will be displayed in the view. We’ll need the login form template first to test it. We’ll call it loginsample.html for now.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

<html>

   <body>

       

      <form name = "form" action = "{% url "myapps.views.samplelogin" %}"

         method = "POST" >{% csrf_token %}

          

         <div style = "max-width:470px;">

            <center>

               <input type = "text" style = "margin-left:20%;"

                  placeholder = "Identifiant" name = "username" />

            </center>

         </div>

             

         <br>

          

         <div style = "max-width:470px;">

            <center>

               <input type = "password" style = "margin-left:20%;"

                  placeholder = "password" name = "password" />

            </center>

         </div>

             

         <br>

          

         <div style = "max-width:470px;">

            <center>

             

               <button style = "border:0px; background-color:#4285F4; margin-top:8%;

                  height:35px; width:80%;margin-left:19%;" type = "submit"

                  value = "Login" >

                  <strong>Login</strong>

               </button>

                

            </center>

         </div>

          

      </form>

       

   </body>

</html>

The template will show a login form and then post the results to the login view we saw earlier. You’ve probably noticed the tag in the template, which is just there to protect your site from a Cross-site Request Forgery (CSRF) attack.

After we’ve created the login template, we’ll need to create the loggedinsample.html template, which will be rendered after the form has been processed.

1

2

3

4

5

6

7

<html>

    

   <body>

      The user who has logged in is : <strong>{{username}}</strong> 

   </body>

    

</html>

To get started, we just need a pair of URLs: myapps/urls.py

1

2

3

4

5

6

from django.conf.urls import patterns, url

from django.views.generic import TemplateView

  

urlpatterns = patterns('myapps.views',

   url(r'^connection/',TemplateView.as_view(template_name = 'loginsample.html')),

   url(r'^login/', 'login', name = 'login'))

The form is valid when it is submitted. Make careful to fill out both fields in our situation, and you’ll obtain

If your username is ramesh and you’ve forgotten your password, this is the place to go. The following notice will appear on your screen:

Django – File Uploading

Make sure you have the Python Image Library (PIL) installed before you start playing with images. Let’s make a profile form in myapps/formsample.py to demonstrate how to upload an image.

1

2

3

4

5

from django import forms

  

class ProfileForms(forms.Form):

   name = forms.CharField(max_length = 150)

   picture = forms.ImageFields()

The only change here, as you can see, is just the forms. ImageField. ImageField will verify that the file you’ve submitted is an image. The form validation will fail if this is not done.

Now we’ll make a “Profile” model to save our profile that we just submitted. In myapps/samplemodels.py, this is done. –

1

2

3

4

5

6

7

rom django.db import models

  

class Profile(models.Model):

   name = models.CharField(max_length = 70)

   picture = models.ImageField(upload_to = 'pictures')

   class Meta:

      db_table = "profile"

The ImageField takes a mandatory argument: upload to, as you can see for the model. This is the location where your images will be saved on your hard drive. Note that the parameter will be added to your settings.py file’s MEDIA ROOT option.

myapps/views.py

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

from myapp.forms import ProfileForm

from myapp.models import Profile

def SaveProfile(request):

   saved = False

  

  

   if request.method == "POST":

      #Get the posted form

      MyProfileForm = ProfileForm(request.POST, request.FILES)

       

      if MyProfileForm.is_valid():

         profile = Profile()

         profile.name = MyProfileForm.cleaned_data["name"]

         profile.picture = MyProfileForm.cleaned_data["picture"]

         profile.save()

         saved = True

   else:

      MyProfileForm = Profileform()

         

   return render(request, 'savedsample.html', locals())

It’s important to note that when building a ProfileForm, we’ve included a new parameter: request.FILES. If the form validation fails, a message stating that the photo is empty will be displayed.

We only need the savedsample.html and profilesample.html templates now for the form and redirection page, respectively.

myapps/templates/savedsample.html

1

2

3

4

5

6

7

8

9

10

11

12

13

<html>

   <body>

    

      {% if saved %}

         <strong>Your profile was saved in the file</strong>

      {% endif %}

       

      {% if not saved %}

         <strong>Your profile was not saved in the file</strong>

      {% endif %}

       

   </body>

</html>

myapp/templates/profilesample.html

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

<html>

   <body>

    

      <form name = "form" enctype = "multipart/form-data"

         action = "{% url "myapps.views.SaveProfile" %}" method = "POST" >{% csrf_token %}

          

         <div style = "max-width:470px;">

            <center> 

               <input type = "text" style = "margin-left:20%;"

               placeholder = "Name" name = "name" />

            </center>

         </div>

             

         <br>

          

         <div style = "max-width:470px;">

            <center>

               <input type = "file" style = "margin-left:20%;"

                  placeholder = "Picture" name = "picture" />

            </center>

         </div>

             

         <br>

          

         <div style = "max-width:470px;">

            <center>

             

               <button style = "border:0px;background-color:#4285F4; margin-top:8%;

                  height:35px; width:80%; margin-left:19%;" type = "submit" value = "Login" >

                  <strong>Login</strong>

               </button>

                

            </center>

         </div>

          

      </form>

       

   </body>

</html>

To get started, we’ll need our pair of URLs: myapps/urls.py

1

2

3

4

5

6

7

from django.conf.urls import patterns, url

from django.views.generic import TemplateView

  

urlpatterns = patterns(

   'myapp.views', url(r'^profile/',TemplateView.as_view(

      template_name = 'profilesample.html')), url(r'^saved/', 'SaveProfile', name = 'saved')

)

When accessing “/myapp/profilesample”, we will get the following profilesample.html template rendered −

And the saved template will be rendered when the form is submitted.

If you want to submit a different type of file than an image, simply replace the ImageField in both the Model and the Form with FileField.

Django – Apache Setup

The Django dev web server was utilised. However, this server is only for testing purposes and is not suitable for use in a production environment. You’ll need a real server like Apache, Nginx, or something similar once you’re in production. Let’s talk about Apache Setup.

Mod wsgi is used to serve Django apps via Apache. The first step is to ensure that Apache and mod wsgi are both installed. Remember how, when we were creating our project and looking at the structure, it looked like this

1

2

3

4

5

6

7

myprojectsample/

   manage.py

   myprojectsample/

      __init__.py

      settings.py

      urls.py

      wsgi.py

The wsgi.py file is the one taking care of the link between Django and Apache.

Let’s imagine we wish to share our project with Apache (myprojectsample). All we have to do now is tell Apache to access our folder. Assume we’ve placed our myprojectsample folder in the standard “/var/www/html” location. At this time, the project can be accessed at 127.0.0.1/myprojectsample. As you can see in the next screenshot, Apache will just list the folder.

As can be observed, Apache is unable of dealing with Django-related issues. We’ll need to configure Apache in httpd.conf to take care of this. As a result, enter httpd.conf and add the following line

1

2

3

4

5

6

7

8

9

WSGIScriptAlias / /var/www/html/myprojectsample/myprojectsample/wsgi.py

WSGIPythonPath /var/www/html/myprojectsample/

  

<Directory /var/www/html/myprojectsample/>

   <Files wsgi.py>

      Order deny,allow

      Allow from all

   </Files>

</Directory>

Django – Cookies Handling

As part of your web application’s requirements, you may need to keep some data on a per-site-visitor basis. Always remember that cookies are saved on the client side, and that depending on the security level of your client browser, setting cookies may or may not function.

Let’s develop a system that uses the login system we created before to demonstrate cookie handling in Django. The system will keep you logged in for X minutes after which you will be kicked out of the app.

You’ll need to set up two cookies for this: last connection and username.

Let’s start by changing our login view such that our username and last connection cookies are saved.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

from django.template import RequestContext

  

def login(request):

   username = "not logged in"

    

   if request.method == "POST":

      #Get the posted form

      MyLoginForm = LoginForm(request.POST)

    

   if MyLoginForm.is_valid():

      username = MyLoginForm.cleaned_data['username']

   else:

      MyLoginForm = LoginForm()

    

   response = render_to_response(request, 'loggedinsample.html', {"username" : username},

      context_instance = RequestContext(request))

    

   response.set_cookie('last_connection', datetime.datetime.now())

   response.set_cookie('username', datetime.datetime.now())

     

   return response

As can be seen in the example above, the set cookie method is called on the response rather than the request, and all cookie values are returned as strings.

Now let’s make a form View for the login form, where we won’t show the form until a cookie is set and it’s less than 10 seconds old.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

def formView(request):

   if 'username' in request.COOKIES and 'last_connection' in request.COOKIES:

      username = request.COOKIES['username']

       

      last_connection = request.COOKIES['last_connection']

      last_connection_time = datetime.datetime.strptime(last_connection[:-7],

         "%Y-%m-%d %H:%M:%S")

       

      if (datetime.datetime.now() - last_connection_time).seconds < 10:

         return render(request, 'loggedinsample.html', {"username" : username})

      else:

         return render(request, 'loginsample.html', {})

             

   else:

      return render(request, 'loginsample.html', {})

The COOKIES attribute (dict) of the request is used to access the cookie you set, as shown in the formView above.

1

2

3

4

5

6

from django.conf.urls import patterns, url

from django.views.generic import TemplateView

  

urlpatterns = patterns('myapps.views',

   url(r'^connection/','formView', name = 'loginform'),

   url(r'^login/', 'login', name = 'login'))

When accessing /myapps/connection, you will get the following page –

After login you will be redirected to the page displayed below

If you try to access /myapps/connection again during the next 10 seconds, you will be taken straight to the second screen. If you go outside of this range and access /myapps/connection again, you’ll get the login form (screen 1).

Django – Sessions

 As previously mentioned, client-side cookies can be used to store a lot of useful data for the web app. We’ve already seen how client-side cookies can be used to store various data for our web app. Depending on the relevance of the data you want to save, this can lead to a slew of security flaws.

Django offers a session framework for handling cookies for security reasons. Data is saved on the server side (as in a database), while the client-side cookie only provides a session ID for identification. Sessions can also help you avoid situations where the user’s browser is set to reject cookies.

How to setup sessions lets learn

Enabling sessions in Django is done in the project settings.py Add some lines to the MIDDLEWARE_CLASSES and INSTALLED APPS settings.py This should be done when creating the project, but it’s always good to be prepared, thus MIDDLEWARE_CLASSES should have MIDDLEWARE_CLASSES.

‘django.contrib.sessions.middleware.SessionMiddleware’

The app installed must contain

.contrib.sessions’

‘django

Django saves session data in the database by default (django session table or collection), but you can configure the engine to save data in other places, such as a file or a cache.

When session is enabled, a session (dict) attribute is added to every request (first argument of any Django view).

To demonstrate how to create and store sessions, let’s design a simple example. We’ve already constructed a simple login mechanism (see Django form processing chapter and Django Cookies Handling chapter). Allow us to save your username in a cookie so that you won’t see the login form if you aren’t logged out when you visit our login page. Basically, let’s make our Django Cookies handling login mechanism more safe by keeping cookies on the server.

Let’s start by changing our login view to save our username cookie on the server side.

1

2

3

4

5

6

7

8

9

10

11

12

13

def login(request):

   username = 'not logged in'

    

   if request.method == 'POST':

      MyLoginForm = LoginForm(request.POST)

       

      if MyLoginForm.is_valid():

         username = MyLoginForm.cleaned_data['username']

         request.session['username'] = username

      else:

         MyLoginForm = LoginForm()

             

   return render(request, 'loggedinsample.html', {"username" : username}

Then we’ll make a form View view for the login form, which will hide the form if a cookie is set.

1

2

3

4

5

6

def formView(request):

   if request.session.has_key('username'):

      username = request.session['susername']

      return render(request, 'loggedinsample.html', {"username" : username})

   else:

      return render(request, 'loginsample.html', {})

Now let’s edit the url.py file to match our new view’s url.

1

2

3

4

5

6

from django.conf.urls import patterns, url

from django.views.generic import TemplateView

  

urlpatterns = patterns('myapp.views',

   url(r'^connection/','formView', name = 'loginform'),

   url(r'^login/', 'login', name = 'login'))

You’ll see the following page when you go to /myapps/connection.

You’ll be forwarded to the following page as a result.

If you try to enter /myapps/connection again, you’ll be taken straight to the second screen.

Let’s make a straightforward logout view that clears our cookie.

1

2

3

4

5

6

def logout(request):

   try:

      del request.session['username']

   except:

      pass

   return HttpResponse("<strong>You have logged out now.</strong>")

And pair it with a logout URL in myapps/url.py

url(r’^logout/’, ‘logout’, name = ‘logout’),

Now, if you access /myapps/logout, you will get the following page –

You’ll see the login form if you go to /myapps/connection again (screen 1).

Additional Actions That Can Be Taken Using Sessions

We’ve seen how to store and access a session, but it’s also worth noting that the request’s session attribute has various additional helpful actions, such as

set_expiry (value) : Sets the session’s expiration time.

get_expiry_age ( ) : The number of seconds till this session expires is returned.

get_expiry_date ( ) : The expiration date for this session is returned.

clear_expired ( ) : Expired sessions are removed from the session repository.

get_expire_at_browser_close() : If the user’s session cookies have expired when the user’s web browser is closed, this method returns True or False.

Django – Caching 

Caching anything means saving the outcome of a time-consuming calculation so you don’t have to do it again the next time you need it. The pseudocode that follows demonstrates how caching works.

1

2

3

4

5

6

7

8

If you're given a URL, try looking it up in the cache.

  

if the page has been cached:

return the previously cached page

else:

create a webpage

the created page is saved in the cache (for next time)

return the page that was created

Django has its own caching system that allows you to keep your dynamic pages so that you don’t have to calculate them again when you need them. The advantage of the Django Cache framework is that it allows you to cache data.

  • The result of a particular vision.
  • It’s a piece of a template.
  • Your full web page.

The first step in using cache in Django is to determine where the cache will be stored. Caching can be saved in a database, on a file system, or directly in memory, according to the cache framework. The settings are made in your project’s settings.py file.

Caching a View

You can cache a specific view instead of the full site if you don’t want to cache the complete site. The cache page decorator that comes with Django is used to accomplish this. Let’s imagine we wish to save the view’s outcome in a cache. View the articles

1

2

3

4

5

6

7

from django.views.decorators.cache import cache_page

  

@cache_page(60 * 15)

  

def viewArticles(request, year, month):

   text = "Displaying blogs of : %s/%s"%(year, month)

   return HttpResponse(text)

As you can see, the number of seconds you want the view result to be cached is passed as a parameter to cache page. The result will be cached for 15 minutes in our case.

As previously stated, the aforementioned view was mapped to

1

2

urlpatterns = patterns('myapps.views',

   url(r'^blogs/(?P<month>\d{2})/(?P<year>\d{4})/', 'viewBlogs', name = 'blogs'),)

Because the URL accepts arguments, each call will be stored separately. Requests to /myapps/articles/02/2007, for example, will be cached independently from requests to /myapps/articles/03/2008.

A view can also be cached directly in the url.py file. The following gives the same result as the previous. Simply replace the related mapped URL (above) in your myapps/url.py 

1

2

3

urlpatterns = patterns('myapps.views',

   url(r'^blogs/(?P<month>\d{2})/(?P<year>\d{4})/',

   cache_page(60 * 15)('viewBlogs'), name = 'blogs'),)

Creating a Template Fragment

You can also use the cache tag to cache specific parts of a template. Take a look at our hello.html template.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

{% extends "main_templatesample.html" %}

{% block title %}My Hello PageSample{% endblock %}

{% block content %}

  

Hello Everyone!!!<p>Today is {{today}}</p>

We are

{% if today.day == 1 %}

  

the first day of month.

{% elif today == 30 %}

  

the last day of month.

{% else %}

  

Don’t kmow

{%endif%}

  

<p>

   {% for day in days_of_week %}

   {{day}}

</p>

  

{% endfor %}

{% endblock %}

Caching the content blog 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

{% load cache %}

{% extends "main_template.html" %}

{% block title %}My Hello PageSample{% endblock %}

{% cache 500 content %}

{% block content %}

  

Hello Everyone!!!<p>Today is {{today}}</p>

We are

{% if today.day == 1 %}

  

the first day of month.

{% elif today == 30 %}

  

the last day of month.

{% else %}

  

Don’t know.

{%endif%}

  

<p>

   {% for day in days_of_week %}

   {{day}}

</p>

  

{% endfor %}

{% endblock %}

{% endcache %}

The cache tag, as you can see above, has two parameters: the time you want the block to be cached (in seconds) and the name you want to give the cache fragment.

Entire Site Caching

Caching the entire site is the simplest approach to use cache in Django. This is done in the project settings.py by modifying the MIDDLEWARE CLASSES variable. To the choice, the following must be added:

1

2

3

4

5

MIDDLEWARE_CLASSES += (

   'django.middleware.cache.UpdateCacheMiddleware',

   'django.middleware.common.CommonMiddleware',

   'django.middleware.cache.FetchFromCacheMiddleware',

)

It’s worth noting that the sequence matters here: Update should come before the Fetch middleware.

Then you must set a value for in the same file.

CACHE MIDDLEWARE ALIAS – The storage cache alias to use.

CACHE MIDDLEWARE SECONDS – The time each page should be cached in seconds.

Django – Comments

Before you begin, keep in mind that the Django Comments framework has been deprecated since version 1.5. You may now do so using an external feature, but if you still want to utilize it, it’s still available in versions 1.6 and 1.7. It is no longer present in version 1.8, however the source is still available on a different GitHub account.

Any model in your project can have comments attached to it thanks to the comments framework.

To get started with the Django comments framework, follow these steps.

Add ‘django.contrib.sites’ and ‘django.contrib.comments’ to the INSTALLED APPS option in the project settings.py file.

1INSTALLED_APPS += ('django.contrib.sites', 'django.contrib.comments',)

Obtain site ID

1

2

3

4

>>> from django.contrib.sites.models import Site

>>> Site().save()

>>> Site.objects.all()[0].id

u'56194498e13823167dd43c64'

Set the ID obtained in the settings.py file 

SITE_ID = u’56194498e13823167dd43c64′

DB Sync 

python manage.py syncdb

Add the URLs from the comment app to your project’s urls.py file.

1

2

from django.conf.urls import include

url(r'^comments/', include('django.contrib.comments.urls')),

Let’s update our greeting templates to track comments on our Dreamreal model now that we’ve installed the framework. We’ll list and save comments for a single Dreamreal entry, the name of which will be provided as a parameter to the /myapp/hello URL.

Django RSS

Django has a framework for creating syndication feeds. By subclassing the django.contrib.syndication.views.Feed class, you can build RSS or Atom feeds.

Let’s make a feed for the most recent app comments (Also see Django – Comments Framework chapter). Let’s start by creating a myapp/feeds.py file and defining our feed (You can put your feeds classes anywhere you want in your code structure).

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

from django.contrib.syndication.views import Feed

from django.contrib.comments import Comment

from django.core.urlresolvers import reverse

  

class DreamrealCommentsFeed(Feed):

   title = "DreamSample's comments"

   link = "/drcomments/"

   description = "Modifies new comments to DreamSample."

  

   def items(self):

      return Comment.objects.all().order_by("-submit_date")[:5]

         

   def item_title(self, item):

      return item.user_name

         

   def item_description(self, item):

      return item.comment

         

   def item_link(self, item):

      return reverse('comment', kwargs = {'object_pk':item.pk})

  • The title, link, and description attributes of our feed class correspond to the standard RSS title, link, and description elements.
  • The elements that should be in the feed as item elements are returned by the items method. The last five remarks in our situation.
  • The item title method returns the title that will be used for our feed item. The user name will be the title in our case.
  • The item description method returns the text that will be used as the feed item’s description. The comment itself in our case.
  • The item link method creates a link to the entire item. It will take you to the comment in our situation.

Django – AJAX

Ajax is a collection of technologies that work together to decrease the number of times a website loads. Ajax is commonly used to improve the end-user experience. Ajax can be used directly in Django by using an Ajax library such as JQuery or others. Let’s imagine you want to use JQuery. You’ll need to download the library and serve it on your server using Apache or another server. Then incorporate it into your template, just like you would in any Ajax-based application.

The Django Ajax framework is another approach to use Ajax with Django. The most popular is django-dajax, which is a strong tool for developing asynchronous display logic in web applications using Python and very little JavaScript source code. Prototype, jQuery, Dojo, and MooTools are four of the most popular Ajax frameworks supported.

The first step is to install django-dajax. Easy install or pip can be used to accomplish this.

$ pip install django_dajax

$ easy_install django_dajax

This will install django-dajaxice, which is required by django-dajax. After that, both dajax and dajaxice must be configured.

In your project settings, add dajax and dajaxice. py in the INSTALLED APPS setting

1

2

3

4

INSTALLED_APPS += (

   'dajaxice',

   'dajax'

)

settings.py should have the following content

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

TEMPLATE_LOADERS = (

   'django.template.loaders.filesystem.Loader',

   'django.template.loaders.app_directories.Loader',

   'django.template.loaders.eggs.Loader',

)

  

TEMPLATE_CONTEXT_PROCESSORS = (

   'django.contrib.auth.context_processors.auth',

   'django.core.context_processors.debug',

   'django.core.context_processors.i18n',

   'django.core.context_processors.media',

   'django.core.context_processors.static',

   'django.core.context_processors.request',

   'django.contrib.messages.context_processors.messages'

)

  

STATICFILES_FINDERS = (

   'django.contrib.staticfiles.finders.FileSystemFinder',

   'django.contrib.staticfiles.finders.AppDirectoriesFinder',

   'dajaxice.finders.DajaxiceFinder',

)

  

DAJAXICE_MEDIA_PREFIX = 'dajaxice'

By end of this read you would have completed the following concepts under the Django tutorial – Basics of Django, Django Environment, Django tutorial – Models, How to create a project using Django and python, Django App life cycle, Django – URL mapping using Django. If you wish to learn more such concepts, head over to Great Learning Academy and enroll yourself on any of our free Django courses


 

What Is Django? | How to Create A Project using Django

How to Set Up Spectrum WiFi Router- Wireless Extender Setup

In this guide, we are going to discuss easy steps for spectrum wifi setup. If you looking guide for the setup then read the guide.

 

Post image

Select Turn on a content blocker to enable parental controls. The first step will be to connect to your router. Connect one end of the coax wire to the cable wall outlet and the other end to the modem. Sign in to view and pay your bill, manage your account, and watch TV from anywhere.

As a result, you should double-check the above and seek assistance from your ISP. detailed instructions for installing and configuring a Then sele

ct Manage Network from the drop-down menu under Services > Internet. Connect the power cord to the wifi router and the other end to an electrical outlet.

Connect the router's power cord next. Connect one end to the ethernet port on your modem and the other to the internet port on your router. Switch to Spectrum Internet ® right away. Log in to your Spectrum account to check and pay your bill, watch TV, manage your account, and do other things. Your spectrum service should be activated quickly. Then, go to the antivirus tab and select preferences.

However, keep in mind that the IP address of a router may differ in some cases. You can continue to use your 2.4 GHz only devices if you have a router with a single network that automatically selects between 2.5 GHz and 5 GHz. Finally, after entering a new password and network name, click Save. It will take you directly to the spectrum activation page.

Install the Spectrum App on Android or iPhone and Follow the Steps Below-

If you have an Android phone, you can connect to spectrum wifi hotspots right away. Wait for the modem to connect to the network (about 2 to 5 minutes) before proceeding to the next stage of spectrum internet and wifi setup.

Wait for the wifi light on the front panel of the wifi router to illuminate.

Start using your Spectrum internet service. Change to a broadband internet connection.

Connect the modem's power cord to an electrical outlet on the other end.

This Address, as well as the Login Credentials, will be Printed on the Router-

Creating a profile is simple and quick. You can do this by launching a browser and entering your router's IP address, which is typically 192.168.0.1 or 192.168.1.1.

It is necessary to upgrade your browser. Unfortunately, this browser is no longer available.

Connect the coax wire to the voice, internet, and wifi frequencies on the spectrum.

Connect one end of the coax wire to the cable wall outlet and the other end to the modem.

How to Connect to the Internet Using WiFi-

Launch the My Spectrum app on your smartphone. First, connect the coax cable. Sign up now for a fantastic deal on fast-spectrum internet with a consistent connection all year.

Then, in the address box, enter spectrum.net. After connecting the router, simply connect to your new wifi network and launch a web browser. It's the same software you've been using to manage your Spectrum internet subscription and pay your Spectrum internet bill.

The cable wire should be connected to the Spectrum voice, internet, and wifi setup. Connect one end of the coax wire to the cable wall outlet and the other end to the modem. Connect one end of the coax wire to the cable wall outlet and the other end to the modem. If the address isn't printed there, then visit our website wirelessextendersetup.org our expert will guide you.

#internet #ip #login #setup #Spectrumwifisetup #wifi 

Rupert  Beatty

Rupert Beatty

1667625360

TransitionButton: UIButton Sublass for Loading & Transition animation

TransitionButton

Concept

Source: Dribbble

Preview

  • Expand animation:

  • Shake animation:

Example

To run the example project, clone the repo, then open the workspace TransitionButton.xcworkspace run using iOS Example scheme.

Installation

CocoaPods

CocoaPods is a dependency manager for Cocoa projects. You can install it with the following command:

$ gem install cocoapods

To integrate TransitionButton into your Xcode project using CocoaPods, specify it in your Podfile:

use_frameworks!

pod 'TransitionButton'

Then, run the following command:

$ pod install

Carthage

Carthage is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks.

You can install Carthage with Homebrew using the following command:

$ brew update
$ brew install carthage

To integrate TransitionButton into your Xcode project using Carthage, specify it in your Cartfile:

github "aladinway/TransitionButton"

Run carthage update to build the framework and on your application targets’ “General” settings tab, in the “Embedded Binaries” section, drag and drop the built TransitionButton.framework from the Carthage/Build folder on disk.

Usage

TransitionButton is a subclass of UIButton. In addition to all what UIButton provides. TransitionButton has two main methods :

startAnimation() : start animating the button with a loading spinner, it should be called just before starting a task, exemple: before a network call to check the login information.

stopAnimation(animationStyle: StopAnimationStyle, revertAfterDelay delay: TimeInterval, completion: (() -> Void)?) : stop animating the button.

  • animationStyle: the style of the stop animation.
  • revertAfterDelay: revert the button to the original state after a delay to give opportunity to custom transition.
  • completion: a completion block to be called once the animation finished, it may be useful to transit to another view controller, example transit to the home screen from the login screen.

For the stop Animation paramteter StopAnimationStyle there is three styles :

  • StopAnimationStyle.normal: just revert the button to the original state.
  • StopAnimationStyle.expand: expand the button and cover all the screen, useful to do transit animation.
  • StopAnimationStyle.shake: revert the button to original state and make a shaoe animation, useful to reflect that something went wrong

Example

import TransitionButton  // 1: First import the TransitionButton library
import UIKit

class FirstViewController: UIViewController {
    
    let button = TransitionButton(frame: CGRect(x: 100, y: 100, width: 100, height: 40)) // please use Autolayout in real project
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.addSubview(button)
        
        button.backgroundColor = .red
        button.setTitle("button", for: .normal)
        button.cornerRadius = 20
        button.spinnerColor = .white
        button.addTarget(self, action: #selector(buttonAction(_:)), for: .touchUpInside)
    }
    
    @IBAction func buttonAction(_ button: TransitionButton) {
        button.startAnimation() // 2: Then start the animation when the user tap the button
        let qualityOfServiceClass = DispatchQoS.QoSClass.background
        let backgroundQueue = DispatchQueue.global(qos: qualityOfServiceClass)
        backgroundQueue.async(execute: {
            
            sleep(3) // 3: Do your networking task or background work here.
            
            DispatchQueue.main.async(execute: { () -> Void in
                // 4: Stop the animation, here you have three options for the `animationStyle` property:
                // .expand: useful when the task has been compeletd successfully and you want to expand the button and transit to another view controller in the completion callback
                // .shake: when you want to reflect to the user that the task did not complete successfly
                // .normal
                button.stopAnimation(animationStyle: .expand, completion: {
                    let secondVC = UIViewController()
                    self.present(secondVC, animated: true, completion: nil)
                })
            })
        })
    }
}

When using the expand animation it's important that you use a custom fade animation to move from the frist view controller to the second view controller to override the native slide animation. You can use the call CustomTransitionViewController it's a subclass of UIViewController which provides a built-in fade transition animation, here is how your second view contoller should looks like :

import TransitionButton

class SecondViewController: CustomTransitionViewController {

}

And you are done.

Download Details:

Author: AladinWay
Source Code: https://github.com/AladinWay/TransitionButton 
License: MIT license

#swift #ios #login #animation 

TransitionButton: UIButton Sublass for Loading & Transition animation
Rupert  Beatty

Rupert Beatty

1666089074

Advanced Usage Of UIAlertController & Pickers Based on It: Telegram

Alerts & Pickers

Advanced usage of native UIAlertController with TextField, TextView, DatePicker, PickerView, TableView, CollectionView and MapView.

Features

  •  Custom pickers based on UITextField, UITextView, UIDatePicker, UIPickerView, UITableView, UICollectionView and MKMapView.
  •  Example using a Storyboard.
  •  Easy contentViewController placement.
  •  Attributed title label and message label.
  •  Button customization: image and title color.
  •  Understandable action button placement.
  •  Easy presentation.
  • Pure Swift 4.

actionSheet-.gif 

Usage

actionSheet-simple.gif alert-simple.gif

  • New Alert
let alert = UIAlertController(style: .alert, title: "Title", message: "Message")
// or
let alert = UIAlertController(style: .alert)
  • Set and styling title
alert.set(title: "Title", font: .systemFont(ofSize: 20), color: .black)
// or
alert.setTitle(font: .systemFont(ofSize: 20), color: .black)
  • Set and styling message
alert.set(message: "Message", font: .systemFont(ofSize: 16), color: .black)
// or
alert.setMessage(font: .systemFont(ofSize: 16), color: .black)
  • Add button with image
alert.addAction(image: image, title: "Title", color: .black, style: .default) { action in
    // completion handler
}
  • Show Alert
// show alert
alert.show()

// or show alert with options
alert.show(animated: true, vibrate: true) {
    // completion handler
}

actionSheet-simple-image.gif alert-simple-image.gif

Set Content ViewController

When setting your own custom UIViewController into UIAlertController keep in mind to set prefferedContentSize.height of the controller otherwise it will no effect. You can not set prefferedContentSize.width.

let alert = UIAlertController(style: .alert, title: "Title")
let vc = CustomViewController()
vc.preferredContentSize.height = height
alert.setValue(vc, forKey: "contentViewController")
alert.show()

// or
let alert = UIAlertController(style: .alert, title: "Title")
let vc = CustomViewController()
alert.set(vc: vc, height: height)
alert.show()

Pickers

For UX better to use .actionSheet style in UIAlertController when set picker into contentViewController. If you like you can use .alert style as well, buy .actionSheet style is wider and User can see more as well as action button is placing at bottom that also more convenience for User to touch it.

UITextField In native UIAlertController you can only add UITextField to .alert style with default style and you can not change such properties as .borderColor, .borderWidth, .frame.size and so on. But if you make your own UIViewController with UITextField, it will solve all these problems.

One TextField Picker

You can use both styles .alert and .actionSheet of UIAlertController.

 alert-textField-1.gif

let alert = UIAlertController(style: self.alertStyle, title: "TextField")                  
let config: TextField.Config = { textField in
    textField.becomeFirstResponder()
    textField.textColor = .black
    textField.placeholder = "Type something"
    textField.left(image: image, color: .black)
    textField.leftViewPadding = 12
    textField.borderWidth = 1
    textField.cornerRadius = 8
    textField.borderColor = UIColor.lightGray.withAlphaComponent(0.5)
    textField.backgroundColor = nil
    textField.keyboardAppearance = .default
    textField.keyboardType = .default
    textField.isSecureTextEntry = true
    textField.returnKeyType = .done
    textField.action { textField in
        // validation and so on
    }
}              
alert.addOneTextField(configuration: config)
alert.addAction(title: "OK", style: .cancel)
alert.show()

Two TextFields Picker

You can use both styles .alert and .actionSheet of UIAlertController.

actionSheet-textField-2.gif

let alert = UIAlertController(style: .alert, title: "Login")

let configOne: TextField.Config = { textField in
    textField.left(image: user), color: .black)
    textField.leftViewPadding = 16
    textField.leftTextPadding = 12
    textField.becomeFirstResponder()
    textField.backgroundColor = nil
    textField.textColor = .black
    textField.placeholder = "Name"
    textField.clearButtonMode = .whileEditing
    textField.keyboardAppearance = .default
    textField.keyboardType = .default
    textField.returnKeyType = .done
    textField.action { textField in
        // action with input
    }
}

let configTwo: TextField.Config = { textField in
    textField.textColor = .black
    textField.placeholder = "Password"
    textField.left(image: lock, color: .black)
    textField.leftViewPadding = 16
    textField.leftTextPadding = 12
    textField.borderWidth = 1
    textField.borderColor = UIColor.lightGray.withAlphaComponent(0.5)
    textField.backgroundColor = nil
    textField.clearsOnBeginEditing = true
    textField.keyboardAppearance = .default
    textField.keyboardType = .default
    textField.isSecureTextEntry = true
    textField.returnKeyType = .done
    textField.action { textField in
        // action with input
    }
}
// vInset - is top and bottom margin of two textFields   
alert.addTwoTextFields(vInset: 12, textFieldOne: configOne, textFieldTwo: configTwo)
alert.addAction(title: "OK", style: .cancel)
alert.show()

DatePicker

UIDatePicker does not look very much in .alert style.

 

let alert = UIAlertController(style: .actionSheet, title: "Select date") alert.addDatePicker(mode: .dateAndTime, date: date, minimumDate: minDate, maximumDate: maxDate) { date in    // action with selected date } alert.addAction(title: "OK", style: .cancel) alert.show()

PickerView

Example how to use UIPickerView as contentViewController and change height of the UIAlertController.

 

let alert = UIAlertController(style: .actionSheet, title: "Picker View", message: "Preferred Content Height") let frameSizes: [CGFloat] = (150...400).map { CGFloat($0) } let pickerViewValues: [[String]] = [frameSizes.map { Int($0).description }] let pickerViewSelectedValue: PickerViewViewController.Index = (column: 0, row: frameSizes.index(of: 216) ?? 0) alert.addPickerView(values: pickerViewValues, initialSelection: pickerViewSelectedValue) { vc, picker, index, values in    DispatchQueue.main.async {        UIView.animate(withDuration: 1) {            vc.preferredContentSize.height = frameSizes[index.row]        }    } } alert.addAction(title: "Done", style: .cancel) alert.show()

Locale Pickers

Country Picker

 

let alert = UIAlertController(style: .actionSheet, message: "Select Country") alert.addLocalePicker(type: .country) { info in    // action with selected object } alert.addAction(title: "OK", style: .cancel) alert.show()

Phone Code Picker

 

let alert = UIAlertController(style: .actionSheet, title: "Phone Codes") alert.addLocalePicker(type: .phoneCode) { info in    // action with selected object } alert.addAction(title: "OK", style: .cancel) alert.show()

Currency Picker

 

let alert = UIAlertController(style: .actionSheet, title: "Currencies") alert.addLocalePicker(type: .currency) { info in    alert.title = info?.currencyCode    alert.message = "is selected"    // action with selected object } alert.addAction(title: "OK", style: .cancel) alert.show()

Image Picker

 

  • Horizontal Image Picker with paging and single selection:

let alert = UIAlertController(style: .actionSheet) let photos: [UIImage] = images alert.addImagePicker(    flow: .horizontal,    paging: true,    images: photos,    selection: .single(action: { [unowned self] image in        // action with selected image    })) alert.addAction(title: "OK", style: .cancel) alert.show()

  • Vertical Image Picker w/o paging and with multiple selection:

let alert = UIAlertController(style: .actionSheet) let photos: [UIImage] = images alert.addImagePicker(    flow: .vertical,    paging: false,    height: UIScreen.main.bounds.height,    images: photos,    selection: .multiple(action: { [unowned self] images in        // action with selected images    })) alert.addAction(title: "OK", style: .cancel) alert.show()

PhotoLibrary Picker

 

let alert = UIAlertController(style: .actionSheet) alert.addPhotoLibraryPicker(    flow: .horizontal,    paging: true,    selection: .single(action: { image in        // action with selected image    })) alert.addAction(title: "Cancel", style: .cancel) alert.show()

ColorPicker

Example how to use UIViewController instantiated from Storyboard with Autolayout as contentViewController in the UIAlertController.

 

let alert = UIAlertController(style: .actionSheet) alert.addColorPicker(color: color) { color in    // action with selected color } alert.addAction(title: "Done", style: .cancel) alert.show()

Contacts Picker

 

let alert = UIAlertController(style: .actionSheet) alert.addContactsPicker { contact in    // action with contact } alert.addAction(title: "Cancel", style: .cancel) alert.show()

Location Picker

 

let alert = UIAlertController(style: .actionSheet) alert.addLocationPicker { location in    // action with location } alert.addAction(title: "Cancel", style: .cancel) alert.show()

Telegram Picker

 

let alert = UIAlertController(style: .actionSheet) alert.addTelegramPicker { result in    switch result {      case .photo(let assets):        // action with assets      case .contact(let contact):        // action with contact      case .location(let location):        // action with location    } } alert.addAction(title: "Cancel", style: .cancel) alert.show()

TextViewer

 

let alert = UIAlertController(style: .actionSheet) alert.addTextViewer(text: .attributedText(text)) alert.addAction(title: "OK", style: .cancel) alert.show()

Alerts vs. Action Sheets

There are some things to keep in mind when using .actionSheet and .alert styles:

  • Pickers better to use in .actionSheet style.
  • UITextField can be used in both styles.

Installing

Manually

Download and drop /Source folder in your project.

Requirements

  • Swift 4
  • iOS 11 or higher

Communication

  • If you found a bug, open an issue.
  • If you have a feature request, open an issue.
  • If you want to contribute, submit a pull request.

Download Details:

Author: Dillidon
Source Code: https://github.com/dillidon/alerts-and-pickers 
License: MIT license

#swift #map #telegram #login #contact 

Advanced Usage Of UIAlertController & Pickers Based on It: Telegram
Rupert  Beatty

Rupert Beatty

1666072980

An Animated Avatar That Responds to Text Field interactions

Login Critter

An animated avatar that responds to text fields interactions 🐻

Demo gif

Inspired by the amazing work done by other designers and developers, specifically Darin Senneff's amazing work. 🎩🌟 I wanted to try and create a similar animated "Login avatar" in Swift.

The Login Critter uses several UIPropertyAnimator. The head rotation is controlled by updating the fractionComplete property for an animator. As the user types, the animator's fraction complete is calculated by text width / text field width.

Avatar Assets

The Login Critter assets are broken down in to "Parts": body, head, eyes, ears, nose, muzzle, etc. Each "Part" can be individually animated. They are just vector PDFs because I wanted to focus on the animations and not worry about creating shapes programmatically.

I used Affinity Designer for creating the mock up and assets. (I'm falling in love with this program. 😍) I've included the raw asset in this repo.

Avatar States

The Login Critter has a neutral, active, ecstatic, and shy state.

For simplicity, the neutral state is just the identity transform for all the Part layers. The neutral state can be triggered by tapping the background.

The active state has two phases a start and end. The start and end active phases corresponds to the avatar turning from left to right. The active state can be triggered by tapping the email text field.

The ecstatic state is unique because it can be used in combination with all other states, i.e. the avatar can be both ecstatic and neutral. The ecstatic state can be triggered by typing @ in the email text field.

The shy state is only used in combination with the neutral state and can be triggered by tapping the password text field.

The peek state is only used in combination with the shy state and can be toggled On or Off using the "show password" button in the password text field.

There is also a "saved" state. The "saved" state is the current active transformation that is stored when returning to the neutral state. For example, if the active state is 50% complete, the avatar is looking straight down, and transitions to the neutral state, then when returning to the active state the avatar will animate to 50% complete instead of 0% complete.

NeutralActiveEcstaticShyPeek
Neutral pngActive pngEcstatic pngShy pngPeek png

The "Parts" transformations for each state begin with it's identity, the neutral state, then scale, rotate and/or translate is applied.

Debug Mode

There is a debug mode flag that when set to true it will show a debug UI. But, be wary, strange behavior might occur if you use both the text field and the debug UI. It's best to use either the text field or debug UI when testing.

Meta

It's rare that I get a chance to do animations and thought this might be a fun little project. Thanks for checking it out! 🙇‍

Chris Goldsby – @goldsbychris

Distributed under the MIT license. See LICENSE for more information.

Questions? Comments? I would love to hear your feedback. :heart:

Download Details:

Author: cgoldsby
Source Code: https://github.com/cgoldsby/LoginCritter 
License: MIT license

#swift #login #animation 

An Animated Avatar That Responds to Text Field interactions

Formulario de inicio de sesión usando Python Tkinter con ejemplo

En este programa, vamos a discutir cómo podemos implementar la página de inicio de sesión en python usando el paquete Tkinter. 

Tkinter es un marco de GUI multiplataforma que viene integrado en la biblioteca estándar de Python. Dado que es un marco multiplataforma, el mismo código se puede usar en cualquier sistema operativo, como Linux, macOS y Windows. Tkinter proporciona una interfaz orientada a objetos para el kit de herramientas Tk GUI.

Para entender cómo crear un formulario de inicio de sesión usando Python Tkinter vamos al siguiente ejemplo.

Ejemplo: formulario de inicio de sesión usando Python Tkinter

En este ejemplo, escribimos un programa que abre una ventana con campos: nombre de usuario y contraseña y un botón para enviar estos valores.

from tkinter import *
from functools import partial

def validateLogin(username, password):
	print("username entered :", username.get())
	print("password entered :", password.get())
	return

#window
tkWindow = Tk()  
tkWindow.geometry('400x150')  
tkWindow.title('Tkinter Login Form - pythonexamples.org')

#username label and text entry box
usernameLabel = Label(tkWindow, text="User Name").grid(row=0, column=0)
username = StringVar()
usernameEntry = Entry(tkWindow, textvariable=username).grid(row=0, column=1)  

#password label and password entry box
passwordLabel = Label(tkWindow,text="Password").grid(row=1, column=0)  
password = StringVar()
passwordEntry = Entry(tkWindow, textvariable=password, show='*').grid(row=1, column=1)  

validateLogin = partial(validateLogin, username, password)

#login button
loginButton = Button(tkWindow, text="Login", command=validateLogin).grid(row=4, column=0)  

tkWindow.mainloop()

Producción:

En este tutorial de ejemplos de Python, aprendimos a crear un formulario de inicio de sesión en la aplicación GUI de Python usando tkinter.

Formulaire de connexion utilisant Python Tkinter avec exemple

Dans ce programme, nous allons discuter de la manière dont nous pouvons implémenter la page de connexion en python à l'aide du package Tkinter. 

Tkinter est un framework d'interface graphique multiplateforme intégré à la bibliothèque standard Python. Comme il s'agit d'un framework multiplateforme, le même code peut être utilisé sur n'importe quel système d'exploitation, tel que Linux, macOS et Windows. Tkinter fournit une interface orientée objet à la boîte à outils Tk GUI.

Pour comprendre comment créer un formulaire de connexion à l'aide de Python Tkinter, nous allons et l'exemple suivant.

Exemple : Formulaire de connexion avec Python Tkinter

Dans cet exemple, nous écrivons un programme qui ouvre une fenêtre avec des champs : nom d' utilisateur et mot de passe et un bouton pour soumettre ces valeurs.

from tkinter import *
from functools import partial

def validateLogin(username, password):
	print("username entered :", username.get())
	print("password entered :", password.get())
	return

#window
tkWindow = Tk()  
tkWindow.geometry('400x150')  
tkWindow.title('Tkinter Login Form - pythonexamples.org')

#username label and text entry box
usernameLabel = Label(tkWindow, text="User Name").grid(row=0, column=0)
username = StringVar()
usernameEntry = Entry(tkWindow, textvariable=username).grid(row=0, column=1)  

#password label and password entry box
passwordLabel = Label(tkWindow,text="Password").grid(row=1, column=0)  
password = StringVar()
passwordEntry = Entry(tkWindow, textvariable=password, show='*').grid(row=1, column=1)  

validateLogin = partial(validateLogin, username, password)

#login button
loginButton = Button(tkWindow, text="Login", command=validateLogin).grid(row=4, column=0)  

tkWindow.mainloop()

Production:

Dans ce didacticiel d'exemples Python, nous avons appris à créer un formulaire de connexion dans une application graphique Python à l'aide de tkinter.

中條 美冬

1664270963

例で Python Tkinter を使用したログイン フォーム

このプログラムでは、Tkinter パッケージを使用して Python でログイン ページを実装する方法について説明します。 

Tkinterは、Python 標準ライブラリに組み込まれているクロスプラットフォームの GUI フレームワークです。クロスプラットフォームのフレームワークであるため、Linux、macOS、Windows など、どのオペレーティング システムでも同じコードを使用できます。Tkinter は、Tk GUI ツールキットへのオブジェクト指向インターフェースを提供します。

Python Tkinter を使用してログイン フォームを作成する方法を理解するために、次の例に進みます。

例: Python Tkinter を使用したログインフォーム

この例では、ユーザー名パスワード、およびこれらの値を送信するためのボタンを含むウィンドウを開くプログラムを作成します。

from tkinter import *
from functools import partial

def validateLogin(username, password):
	print("username entered :", username.get())
	print("password entered :", password.get())
	return

#window
tkWindow = Tk()  
tkWindow.geometry('400x150')  
tkWindow.title('Tkinter Login Form - pythonexamples.org')

#username label and text entry box
usernameLabel = Label(tkWindow, text="User Name").grid(row=0, column=0)
username = StringVar()
usernameEntry = Entry(tkWindow, textvariable=username).grid(row=0, column=1)  

#password label and password entry box
passwordLabel = Label(tkWindow,text="Password").grid(row=1, column=0)  
password = StringVar()
passwordEntry = Entry(tkWindow, textvariable=password, show='*').grid(row=1, column=1)  

validateLogin = partial(validateLogin, username, password)

#login button
loginButton = Button(tkWindow, text="Login", command=validateLogin).grid(row=4, column=0)  

tkWindow.mainloop()

出力:

この Python の例のチュートリアルでは、tkinter を使用して Python GUI アプリケーションでログイン フォームを作成する方法を学びました。

Форма входа с использованием Python Tkinter с примером

В этой программе мы собираемся обсудить, как мы можем реализовать страницу входа в систему на python с помощью пакета Tkinter. 

Tkinter — это кросс-платформенный фреймворк с графическим интерфейсом, встроенный в стандартную библиотеку Python. Поскольку это кроссплатформенная среда, один и тот же код можно использовать в любой операционной системе, например Linux, macOS и Windows. Tkinter предоставляет объектно-ориентированный интерфейс для набора инструментов Tk GUI.

Чтобы понять, как создать форму входа с помощью Python Tkinter, рассмотрим следующий пример.

Пример: форма входа в систему с использованием Python Tkinter

В этом примере мы пишем программу, которая открывает окно с полями: имя пользователя и пароль и кнопку для отправки этих значений.

from tkinter import *
from functools import partial

def validateLogin(username, password):
	print("username entered :", username.get())
	print("password entered :", password.get())
	return

#window
tkWindow = Tk()  
tkWindow.geometry('400x150')  
tkWindow.title('Tkinter Login Form - pythonexamples.org')

#username label and text entry box
usernameLabel = Label(tkWindow, text="User Name").grid(row=0, column=0)
username = StringVar()
usernameEntry = Entry(tkWindow, textvariable=username).grid(row=0, column=1)  

#password label and password entry box
passwordLabel = Label(tkWindow,text="Password").grid(row=1, column=0)  
password = StringVar()
passwordEntry = Entry(tkWindow, textvariable=password, show='*').grid(row=1, column=1)  

validateLogin = partial(validateLogin, username, password)

#login button
loginButton = Button(tkWindow, text="Login", command=validateLogin).grid(row=4, column=0)  

tkWindow.mainloop()

Выход:

В этом руководстве по примерам Python мы научились создавать форму входа в приложение с графическим интерфейсом Python с помощью tkinter.

Duck Hwan

1664263687

예제와 함께 Python Tkinter를 사용한 로그인 양식

이 프로그램에서는 Tkinter 패키지를 사용하여 파이썬에서 로그인 페이지를 구현하는 방법에 대해 논의할 것입니다. 

Tkinter 는 Python 표준 라이브러리에 내장된 크로스 플랫폼 GUI 프레임워크입니다. 크로스 플랫폼 프레임워크이기 때문에 Linux, macOS, Windows 등 모든 운영 체제에서 동일한 코드를 사용할 수 있습니다. Tkinter는 Tk GUI 툴킷에 대한 객체 지향 인터페이스를 제공합니다.

Python Tkinter를 사용하여 로그인 양식을 만드는 방법을 이해하기 위해 다음 예제로 이동합니다.

예 : Python Tkinter를 사용한 로그인 양식

이 예에서는 사용자 이름암호 와 이러한 값을 제출하는 버튼 이 있는 창을 여는 프로그램을 작성합니다.

from tkinter import *
from functools import partial

def validateLogin(username, password):
	print("username entered :", username.get())
	print("password entered :", password.get())
	return

#window
tkWindow = Tk()  
tkWindow.geometry('400x150')  
tkWindow.title('Tkinter Login Form - pythonexamples.org')

#username label and text entry box
usernameLabel = Label(tkWindow, text="User Name").grid(row=0, column=0)
username = StringVar()
usernameEntry = Entry(tkWindow, textvariable=username).grid(row=0, column=1)  

#password label and password entry box
passwordLabel = Label(tkWindow,text="Password").grid(row=1, column=0)  
password = StringVar()
passwordEntry = Entry(tkWindow, textvariable=password, show='*').grid(row=1, column=1)  

validateLogin = partial(validateLogin, username, password)

#login button
loginButton = Button(tkWindow, text="Login", command=validateLogin).grid(row=4, column=0)  

tkWindow.mainloop()

산출:

이 Python 예제 자습서에서는 tkinter를 사용하여 Python GUI 응용 프로그램에서 로그인 양식을 만드는 방법을 배웠습니다.

Anmeldeformular mit Python Tkinter mit Beispiel

In diesem Programm werden wir besprechen, wie wir die Anmeldeseite in Python mit dem Tkinter-Paket implementieren können. 

Tkinter ist ein plattformübergreifendes GUI-Framework, das in die Python-Standardbibliothek integriert ist. Da es sich um ein plattformübergreifendes Framework handelt, kann derselbe Code auf jedem Betriebssystem wie Linux, macOS und Windows verwendet werden. Tkinter bietet eine objektorientierte Schnittstelle zum Tk-GUI-Toolkit.

Um zu verstehen, wie man ein Anmeldeformular mit Python Tkinter erstellt, sehen wir uns das folgende Beispiel an.

Beispiel: Anmeldeformular mit Python Tkinter

In diesem Beispiel schreiben wir ein Programm, das ein Fenster mit Feldern öffnet: Benutzername und Passwort und eine Schaltfläche zum Senden dieser Werte.

from tkinter import *
from functools import partial

def validateLogin(username, password):
	print("username entered :", username.get())
	print("password entered :", password.get())
	return

#window
tkWindow = Tk()  
tkWindow.geometry('400x150')  
tkWindow.title('Tkinter Login Form - pythonexamples.org')

#username label and text entry box
usernameLabel = Label(tkWindow, text="User Name").grid(row=0, column=0)
username = StringVar()
usernameEntry = Entry(tkWindow, textvariable=username).grid(row=0, column=1)  

#password label and password entry box
passwordLabel = Label(tkWindow,text="Password").grid(row=1, column=0)  
password = StringVar()
passwordEntry = Entry(tkWindow, textvariable=password, show='*').grid(row=1, column=1)  

validateLogin = partial(validateLogin, username, password)

#login button
loginButton = Button(tkWindow, text="Login", command=validateLogin).grid(row=4, column=0)  

tkWindow.mainloop()

Ausgabe:

In diesem Tutorial mit Python-Beispielen haben wir gelernt, ein Anmeldeformular in einer Python-GUI-Anwendung mit tkinter zu erstellen.