1675257841
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.
1674999008
facebook_and_google_signin
A new Flutter project.
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.
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.
Now in your Dart code, you can use:
import 'package:facebook_and_google_signin/facebook_and_google_signin.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
1670507104
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.
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 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 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.
There are many authentication methods applications employ to verify a user’s identity:
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.
Now we are going to review some of the best practices to store passwords in a database.
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).
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.
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.
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:
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:
Hashed Password = HASH(INDIVIDUAL SALT + PASSWORD + COMMON PEPPER)
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.
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:
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.
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.
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.
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 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.
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.
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/
1670088780
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.
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
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=
Run the following command –
composer require laravel/ui
Run the following command –
php artisan ui bootstrap --auth
resources/auth/
folder.Controllers/Auth/
folder.Run the following command –
npm install && npm run dev
You have to keep it running.
Open another terminal or command line window and run the following command –
php artisan migrate
This will create tables in the database.
php artisan serve
It gives the URL to run the project – http://127.0.0.1:8000
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/
1669167411
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.
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:
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.
Syntax: python
Code:
1 2 3 4 |
|
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 |
|
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/
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.
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/.
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.
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 |
|
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.
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.
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 |
|
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 |
|
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 |
|
MIDDLEWARE_CLASSES –
1 2 3 4 5 6 7 8 |
|
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 |
|
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 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 |
|
After Changes DIRS:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
Now we can write in our view like –
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
Views can also receive parameters –
1 2 3 4 5 6 |
|
Views can also return objects in form of dictionary-
1 2 3 4 5 6 |
|
When linked to a URL, the page will display the forwarded number as a parameter. Note that the parameters will be passed by URL.
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 |
|
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 |
|
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-
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 |
|
Thereafter CellShop / urls.py will switch to the following –
1 2 3 4 5 6 7 8 |
|
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 |
|
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 |
|
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.
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 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 |
|
After that our view will change to –
1 2 3 |
|
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 |
|
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 |
|
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 |
|
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 |
|
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 |
|
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.
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_HOST | smtp server |
EMAIL_HOST_USER | smtp server login credential |
EMAIL_HOST_PASSWORD | smtp server password credential |
EMAIL_PORT | server port of smtp |
EMAIL_USE_TLS or _SSL | if secure connection then it’s TRUE |
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 |
|
subject | Subject of the email |
message | Body of the email |
from_email | From email |
recipient_list | Email receivers list |
fail_silently | If false, send mail will throw an exception if there is a problem. |
auth_user | User login |
auth_password | User Password |
connection | Backend of the email |
html_message | Email will be multipart or alternative |
1 2 3 4 5 |
|
So, if you go to /myapps/sampleemail/ramesh@gmail.com, you’ll see something like this:
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 |
|
1 2 3 4 5 |
|
When accessing /myapps/massemail/ramesh@gmail.com/suresh@gmail.com/, we get –
datatuples | Each element of the tuple is (subject, message, from email, recipient list). |
fail_silently | If false, send mail will throw an exception if there is a problem. |
auth_user | User Login |
auth_password | User Password |
connection | Backend 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.
It’s as simple as sending an HTML message in Django >= 1.7.
1 2 3 4 5 |
|
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 |
|
Information for the EmailMessage class construction parameters:
Subject | E- mail subject |
Message | Body in HTML |
from_email | E- mail from whom |
to | Receiver’s list |
bcc | e- mail address for list of bcc receivers |
connection | Backend email connection |
Let’s make a URL to get to our view:
1 2 3 4 5 6 |
|
viewBlog view), the ‘redirect’ method takes the view name and its parameters as arguments.
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 |
|
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 |
|
If we implemented it the way we learnt before, we’d have to rename as myapp/sviews.py
1 2 3 4 5 |
|
1 2 3 |
|
The good way is to use generic views. For that, our myapps/views.py will become –
1 2 3 4 |
|
our myapp/samplestatic
1 2 3 4 |
|
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 |
|
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 |
|
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 |
|
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 |
|
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 |
|
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 |
|
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 |
|
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.
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 |
|
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 |
|
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 |
|
To get started, we just need a pair of URLs: myapps/urls.py
1 2 3 4 5 6 |
|
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:
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 |
|
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 |
|
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 |
|
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 |
|
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 |
|
To get started, we’ll need our pair of URLs: myapps/urls.py
1 2 3 4 5 6 7 |
|
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.
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 |
|
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 |
|
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 |
|
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 |
|
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 |
|
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).
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.
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 |
|
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 |
|
Now let’s edit the url.py file to match our new view’s url.
1 2 3 4 5 6 |
|
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 |
|
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.
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 |
|
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 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 |
|
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 |
|
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 |
|
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 |
|
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 |
|
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.
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 |
|
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.
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.
1 | INSTALLED_APPS += ('django.contrib.sites', 'django.contrib.comments',) |
Obtain site ID
1 2 3 4 |
|
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 |
|
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 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 |
|
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 |
|
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 |
|
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.
1668150677
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.
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
1667625360
TransitionButton
Source: Dribbble
To run the example project, clone the repo, then open the workspace TransitionButton.xcworkspace
run using iOS Example
scheme.
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 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.
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 wrongimport 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.
Author: AladinWay
Source Code: https://github.com/AladinWay/TransitionButton
License: MIT license
1666089074
Advanced usage of native UIAlertController with TextField, TextView, DatePicker, PickerView, TableView, CollectionView and MapView.
let alert = UIAlertController(style: .alert, title: "Title", message: "Message")
// or
let alert = UIAlertController(style: .alert)
alert.set(title: "Title", font: .systemFont(ofSize: 20), color: .black)
// or
alert.setTitle(font: .systemFont(ofSize: 20), color: .black)
alert.set(message: "Message", font: .systemFont(ofSize: 16), color: .black)
// or
alert.setMessage(font: .systemFont(ofSize: 16), color: .black)
alert.addAction(image: image, title: "Title", color: .black, style: .default) { action in
// completion handler
}
// show alert
alert.show()
// or show alert with options
alert.show(animated: true, vibrate: true) {
// completion handler
}
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()
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.
You can use both styles .alert
and .actionSheet
of UIAlertController
.
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()
You can use both styles .alert
and .actionSheet
of UIAlertController
.
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()
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()
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()
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()
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()
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()
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()
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()
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()
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()
let alert = UIAlertController(style: .actionSheet) alert.addContactsPicker { contact in // action with contact } alert.addAction(title: "Cancel", style: .cancel) alert.show()
let alert = UIAlertController(style: .actionSheet) alert.addLocationPicker { location in // action with location } alert.addAction(title: "Cancel", style: .cancel) alert.show()
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()
let alert = UIAlertController(style: .actionSheet) alert.addTextViewer(text: .attributedText(text)) alert.addAction(title: "OK", style: .cancel) alert.show()
There are some things to keep in mind when using .actionSheet
and .alert
styles:
.actionSheet
style.UITextField
can be used in both styles.Download and drop /Source
folder in your project.
Author: Dillidon
Source Code: https://github.com/dillidon/alerts-and-pickers
License: MIT license
1666072980
An animated avatar that responds to text fields interactions 🐻
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
.
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.
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.
Neutral | Active | Ecstatic | Shy | Peek |
---|---|---|---|---|
![]() | ![]() | ![]() | ![]() | ![]() |
The "Parts" transformations for each state begin with it's identity
, the neutral state, then scale, rotate and/or translate is applied.
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.
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:
Author: cgoldsby
Source Code: https://github.com/cgoldsby/LoginCritter
License: MIT license
1664278260
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.
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.
1664274609
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.
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
このプログラムでは、Tkinter パッケージを使用して Python でログイン ページを実装する方法について説明します。
Tkinterは、Python 標準ライブラリに組み込まれているクロスプラットフォームの GUI フレームワークです。クロスプラットフォームのフレームワークであるため、Linux、macOS、Windows など、どのオペレーティング システムでも同じコードを使用できます。Tkinter は、Tk GUI ツールキットへのオブジェクト指向インターフェースを提供します。
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 アプリケーションでログイン フォームを作成する方法を学びました。
1664267340
В этой программе мы собираемся обсудить, как мы можем реализовать страницу входа в систему на python с помощью пакета Tkinter.
Tkinter — это кросс-платформенный фреймворк с графическим интерфейсом, встроенный в стандартную библиотеку Python. Поскольку это кроссплатформенная среда, один и тот же код можно использовать в любой операционной системе, например Linux, macOS и Windows. Tkinter предоставляет объектно-ориентированный интерфейс для набора инструментов Tk GUI.
Чтобы понять, как создать форму входа с помощью 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.
1664263687
이 프로그램에서는 Tkinter 패키지를 사용하여 파이썬에서 로그인 페이지를 구현하는 방법에 대해 논의할 것입니다.
Tkinter 는 Python 표준 라이브러리에 내장된 크로스 플랫폼 GUI 프레임워크입니다. 크로스 플랫폼 프레임워크이기 때문에 Linux, macOS, Windows 등 모든 운영 체제에서 동일한 코드를 사용할 수 있습니다. Tkinter는 Tk GUI 툴킷에 대한 객체 지향 인터페이스를 제공합니다.
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 응용 프로그램에서 로그인 양식을 만드는 방법을 배웠습니다.
1664260046
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.
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.