tag:blogger.com,1999:blog-44344798340264777762024-03-14T02:06:24.129+05:30Django Easy TutorialAn easy tutorial to learn & practice an effective web development with pythonAnjaneyulu Battahttp://www.blogger.com/profile/04466094850374273896noreply@blogger.comBlogger36125tag:blogger.com,1999:blog-4434479834026477776.post-14140500420482636912017-07-02T15:03:00.001+05:302017-07-02T15:03:42.603+05:30aggregation usage in django queries<div dir="ltr" style="text-align: left;" trbidi="on">
<div dir="ltr" style="text-align: left;" trbidi="on">
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiyWiTOkgflDzmrT3nmfgWaOdYmlS8_oE7HfiZ8dlW9dgdWVx95oLYMd322iWLT9dwwRXtKgQXKssFfySMctT68EMlzZj401eRyOueNXHFKoUjCxUx-JqRfpSmkdnZWCwo734nrCDVkXt8H/s1600/using-aggregation-django.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img alt="aggregation usage in django queries" border="0" data-original-height="206" data-original-width="453" height="145" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiyWiTOkgflDzmrT3nmfgWaOdYmlS8_oE7HfiZ8dlW9dgdWVx95oLYMd322iWLT9dwwRXtKgQXKssFfySMctT68EMlzZj401eRyOueNXHFKoUjCxUx-JqRfpSmkdnZWCwo734nrCDVkXt8H/s320/using-aggregation-django.png" title="aggregation usage in django queries" width="320" /></a></div>
<br />It is an easy tutorial to make complex queries in django. I personally believe that every word has a specific meaning to it in the world of technology.<br />
<h2 style="text-align: left;">
<b>Aggregation:</b></h2>
<blockquote class="tr_bq">
The meaning of <i>aggregation</i> is "the collection of related items of content so that they can be displayed or linked to".</blockquote>
<h2 style="text-align: left;">
Cases when Aggregation is used:</h2>
<ol style="text-align: left;">
<li><div style="text-align: left;">
To find "maximum", "minimum" value of column(field in django) in database table in django terms a model.</div>
</li>
<li>To find "count" of records in database table based on a column/field value.</li>
<li>To find "average" value of a group of similar objects </li>
<li>To find "sum" of values of a column of a table/model in database.</li>
<li>In most of the cases we use aggregation on columns of data type "integer", "float", "date", "datetime" etc.</li>
</ol>
Consider below django model to learn queries that use aggregation<br />
<br />
<blockquote class="tr_bq">
<pre>class Book(models.Model):
name = models.CharField(max_length=300)
pages = models.IntegerField()
price = models.DecimalField(max_digits=10, decimal_places=2)
rating = models.FloatField()
</pre>
</blockquote>
<h2 style="text-align: left;">
Usage of "Avg" in django queryset </h2>
<div style="text-align: left;">
</div>
<ul style="text-align: left;">
<li>Find average price across all books?<pre>from django.db.models import Avg
out = Book.objects.aggregate(Avg('price'))
# value of out is something like {'price__avg': 34.35}
</pre>
</li>
<li>Find average price across all books which contains "django" in name?
<pre>from django.db.models import Avg
queryset = Book.objects.filter(name__icontains='django')
out = queryset.aggregate(Avg('price'))
# value of out is something like {'price__avg': 54.25}
</pre>
</li>
<li>Find average price across all books which has minimum price of 14?<pre>from django.db.models import Avg
queryset = Book.objects.filter(price__gte=14)
out = queryset.aggregate(Avg('price'))
# value of out is something like {'price__avg': 25.65}
</pre>
</li>
</ul>
<h2 style="text-align: left;">
Usage of "Max" in django queryset</h2>
<ul style="text-align: left;">
<li>Find maximum price across all books?
<pre>from django.db.models import Max
out = Book.objects.aggregate(Max('price'))
# value of out is something like {'price__max': 81.20}
</pre>
</li>
<li>Find maximum price across all books which contains "django" in name?
<pre>from django.db.models import Max
queryset = Book.objects.filter(name__icontains='django')
out = queryset.aggregate(Max('price'))
# value of out is something like {'price__max': 54.25}
</pre>
</li>
</ul>
</div>
<h2 style="text-align: left;">
Usage of "Min" in django queryset</h2>
<ul style="text-align: left;">
<li>Find minimum price across all books?
<pre>from django.db.models import Min
out = Book.objects.aggregate(Min('price'))
# value of out is something like {'price__min': 81.20}
</pre>
</li>
<li>Find minimum price across all books which contains "django" in name?
<pre>from django.db.models import Min
queryset = Book.objects.filter(name__icontains='django')
out = queryset.aggregate(Min('price'))
# value of out is something like {'price__min': 54.25}
</pre>
</li>
</ul>
<h2 style="text-align: left;">
Usage of "SUM" in django queryset</h2>
<ul style="text-align: left;">
<li><div style="text-align: left;">
Find sum of prices all books?</div>
<pre>from django.db.models import Sum
out = Book.objects.aggregate(Sum('price'))
# value of out is something like {'price__sum': 81.20} </pre>
</li>
<li>find sum of all prices of books which contains "django" in name<br /><pre>from django.db.models import Min
queryset = Book.objects.filter(name__icontains='django')
out = queryset.aggregate(Sum('price'))
# value of out is something like {'price__sum': 54.25}
</pre>
</li>
</ul>
<h2 style="text-align: left;">
Usage of "COUNT" in django queryset </h2>
<ul style="text-align: left;">
<li><div style="text-align: left;">
Find count of all books?</div>
<pre>from django.db.models import Count
out = Book.objects.aggregate(Count('rating'))
# value of out is something like {'rating__count': 8} </pre>
</li>
<li>find count of all prices of books which contains "django" in name<br /><pre>from django.db.models import Count
queryset = Book.objects.filter(name__icontains='django')
out = queryset.aggregate(Sum('price'))
# value of out is something like {'rating__count': 5}
</pre>
</li>
</ul>
<h2 style="text-align: left;">
Multiple aggregations in a single query</h2>
<blockquote class="tr_bq">
<pre>from django.db.models import Avg, Max, Min
Book.objects.aggregate(Avg('price'), Max('price'), Min('price'))
# value of out is something like
# { 'price__avg': 34.35, 'price__max': 81.20, 'price__min': 12.99}
</pre>
</blockquote>
These are the very basic queries that used aggregation. we can also use aggregation on <b>"foreign key"</b> fields, "<b>many-to-many</b>" fields and we can also use it with joins("__" notation in django).</div>
Anjaneyulu Battahttp://www.blogger.com/profile/04466094850374273896noreply@blogger.com0tag:blogger.com,1999:blog-4434479834026477776.post-188744845011548942017-06-25T22:17:00.003+05:302017-06-25T22:17:43.255+05:30install android studio on ubuntu with command line<div dir="ltr" style="text-align: left;" trbidi="on">
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgh9D2gPZj6hcCD6_FinJClk3NkvTbPNWz2JTsscdKq4nOaeGV18v8HlLVEZVOfLBb5sxqfTYL8GhAeLmdhXCB3MiaQf64je8oji72HrdthOiRCYFANeA5aVDlrtgWYyUoJIomnt9BIoFHv/s1600/android_studio_on_ubuntu.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img alt="install android studio on ubuntu" border="0" data-original-height="235" data-original-width="477" height="196" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgh9D2gPZj6hcCD6_FinJClk3NkvTbPNWz2JTsscdKq4nOaeGV18v8HlLVEZVOfLBb5sxqfTYL8GhAeLmdhXCB3MiaQf64je8oji72HrdthOiRCYFANeA5aVDlrtgWYyUoJIomnt9BIoFHv/s400/android_studio_on_ubuntu.png" title="install android studio on ubuntu" width="400" /></a></div>
<ul style="text-align: left;">
<li>Android is an mobile operating system developed by Google.</li>
<li>First version of Android released on 23rd September 2008.</li>
<li>Android is an open source operating system.</li>
<li>Nowadays everyone is using android mobiles & android is providing cool and fantastic applications.</li>
<li>There are millions of android applications are out there on Google playstore.</li>
<li>There is a huge demand for android developers.</li>
<li>So don't waste time. Let's start developing cool android applications with extremely powerful and best operating system Ubuntu.</li>
</ul>
To install the <i><b>android studio</b></i> on <i><b>Ubuntu </b></i>follow below steps:<br />
<ol style="text-align: left;">
<li>Android Studio depends on Java, and Oracle. So, install it too.
<pre>sudo add-apt-repository -y ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java7-installer oracle-java7-set-default
</pre>
</li>
<li>Now, Add the Android Studio PPA & Install Android Studio
<pre>sudo add-apt-repository ppa:paolorotolo/android-studio
sudo apt-get update
sudo apt-get install android-studio
</pre>
</li>
<li> You have successful installed Android Studio. Start android studio setup with below command.
<pre>chmod +x /opt/android-studio/bin/studio.sh
/opt/android-studio/bin/studio.sh
</pre>
</li>
<li>After executing above commands it will open wizard & while it is installing it will download required files from Google. Do not change installation path.</li>
<li>To setup android virtual device(AVD) open studio and goto <i><b>Tools >> Android >> AVD Manager.</b></i> It will show you list of virtual devices if available. If not create a virtual device by clicking create virtual device button. Now choose the device and create it.</li>
<li> Now, you can see directory named<b> "Android" </b>in you home directory.</li>
<li>To setup Android path create a text file in home directory named <i><b>".bash_profile"</b></i> and add below lines to it.
<pre>export ANDROID_HOME=$HOME/Android/Sdk
export PATH=$PATH:$ANDROID_HOME/tools
export PATH=$PATH:$ANDROID_HOME/platform-tools
</pre>
</li>
</ol>
To open complete android studio run below command<br />
<blockquote class="tr_bq">
<pre>/opt/android-studio/bin/studio.sh </pre>
</blockquote>
To use virtual devices only then follow below steps<br />
<ol style="text-align: left;">
<li>Change direcoty <pre>cd ~/Android/Sdk/tools/</pre>
</li>
<li>Find list of available virtual devices<br /><pre>emulator -list-avds
# Nexus_5X_API_23 (name of avd)</pre>
</li>
<li>Now, run below command to open virtual devise<br /><pre>emulator -avd <AVD Name> # in my case avd names is Nexus_5X_API_23</pre>
</li>
</ol>
It will open android emulator without opening android studio. <br />
<ol style="text-align: left;">
</ol>
</div>
Anjaneyulu Battahttp://www.blogger.com/profile/04466094850374273896noreply@blogger.com0tag:blogger.com,1999:blog-4434479834026477776.post-27264940089749108212017-06-18T09:02:00.000+05:302017-06-18T09:20:55.363+05:30Basic understanding of package.json in npm<div dir="ltr" style="text-align: left;" trbidi="on">
<div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj-E79Xcn-rSDuGFJ2c70qh5z9Rp9Ea-N_nqCx9clHNPDPpYRru35C8ZaXJLAP7f4B558viEeS4ZFe8FAKXz956w3eSvSpRTIEeRq8y89XC-9PPoIUFhV_8D_ZlgffyW3dSolScNn8F9H3T/s1600/basics-of-package.json.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img alt="Basics understangind of package.json" border="0" data-original-height="228" data-original-width="428" height="170" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj-E79Xcn-rSDuGFJ2c70qh5z9Rp9Ea-N_nqCx9clHNPDPpYRru35C8ZaXJLAP7f4B558viEeS4ZFe8FAKXz956w3eSvSpRTIEeRq8y89XC-9PPoIUFhV_8D_ZlgffyW3dSolScNn8F9H3T/s320/basics-of-package.json.png" title="Basics understangind of package.json" width="320" /></a></div>
#package.json
<br />
<pre>{
"name": "module-name",
"version": "1.0.0",
"description": "An example module to illustrate the usage of a package.json",
"author": "Your Name <you.name@example.org>",
"contributors": [{
"name": "Foo Bar",
"email": "foo.bar@example.com"
}],
"scripts": {
"test": "vows --spec --isolate",
"start": "node index.js",
"predeploy": "echo im about to deploy",
"postdeploy": "echo ive deployed",
"prepublish": "coffee --bare --compile --output lib/foo src/foo/*.coffee"
},
"main": "lib/foo.js",
"repository": {
"type": "git",
"url": "https://github.com/nodejitsu/browsenpm.org"
},
"bugs": {
"url": "https://github.com/nodejitsu/browsenpm.org/issues"
},
"keywords": [
"nodejitsu",
"example",
"browsenpm"
],
"dependencies": {
"primus": "*",
"async": "~0.8.0",
"express": "4.2.x",
"winston": "git://github.com/flatiron/winston#master",
"bigpipe": "bigpipe/pagelet",
"plates": "https://github.com/flatiron/plates/tarball/master"
},
"devDependencies": {
"vows": "^0.7.0",
"assume": "<1.0.0 || >=2.3.1 <2.4.5 || >=2.5.2 <3.0.0",
"pre-commit": "*"
},
"license": "MIT"
}
</pre>
"package.json" file contains complete information of the package. Let's see the Basic details of json object.<br />
<ul style="text-align: left;">
<li><b>name</b>:<b> </b>It represents name of the current package</li>
<li><b>version</b>: It represents version number of the current package.</li>
<li><b>description</b>: It contains the information of package like what it can do, how do we use it, etc.</li>
<li><b>author</b>: It takes name of the author and email</li>
<li><b>contributors</b>: It takes list of objects, each object contains the information of contributor(i.e name and email)</li>
<li><b>scripts</b>: It contains the aliases of commands. Instead of typing long commands we can simply give an alias and use it. If you look at above package.json file you can observe that "scripts" contains the alias command "prepublish" to the long command "coffee --bare --compile --output lib/foo src/foo/*.coffee". Istead of typing the long command we can simply use <i><b>"npm prepublish"</b></i></li>
<li><b>main</b>: It contains the path of the js file. NPM uses it as an initial point.</li>
<li><b>repository:</b>It contains the git url or url of the code control system.</li>
<li><b>bugs: </b>It contains the url where we can raise the issues/bugs of the package.</li>
<li><b>keywords: </b>It contains the search keywords for the package.</li>
<li><b>dependencies: </b>It contains the dependency packages and respective versions used for production.</li>
<li><b>devDependencies: </b><br />It contains the dependency packages and respective versions used for development.</li>
</ul>
</div>
</div>
Anjaneyulu Battahttp://www.blogger.com/profile/04466094850374273896noreply@blogger.com0tag:blogger.com,1999:blog-4434479834026477776.post-49543145807358302322017-06-17T16:35:00.000+05:302017-08-26T23:05:23.643+05:30Basic usage of npm command line<div dir="ltr" style="text-align: left;" trbidi="on">
<div style="text-align: left;">
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi8WZyU1t2h63xlvodi0u2QR_ADhPvG0YJfVJLIkR1jgewfwlk-y4y0Uwd_5fl-8-FCxtFsTOSqtN4mxcRtobo0uAJSCIZPBpTHEHLD8vpwUDNdB-3BqdEQAJjvfIzTLbryg6hZ1O8GD3HP/s1600/command-line-npm.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="121" data-original-width="261" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi8WZyU1t2h63xlvodi0u2QR_ADhPvG0YJfVJLIkR1jgewfwlk-y4y0Uwd_5fl-8-FCxtFsTOSqtN4mxcRtobo0uAJSCIZPBpTHEHLD8vpwUDNdB-3BqdEQAJjvfIzTLbryg6hZ1O8GD3HP/s1600/command-line-npm.png" /></a></div>
<br />
I'm assuming that you have already installed the nodejs and npm. If not install <a href="https://django-easy-tutorial.blogspot.in/2017/06/install-nodejs-and-npm-in-ubuntu-windows.html" target="_blank">nodejs and npm</a> it. </div>
<h2 style="text-align: left;">
Create a package with npm</h2>
<ul style="text-align: left;">
<li><pre>npm init</pre>
</li>
</ul>
<ul style="text-align: left;">
<li>When we run above command It will ask us a couple of questions about the package that we are going to create. After executing the command it will create a "package.json" file.</li>
<li>We use "init" command only if we want to create a new package.</li>
</ul>
<h2 style="text-align: left;">
Installing global packages with npm</h2>
<ul style="text-align: left;">
<li><pre>npm install -g <package name>
</pre>
</li>
</ul>
<ul style="text-align: left;">
<li>we install a package globally only if we want to use it as a command line</li>
</ul>
<ul style="text-align: left;">
<li>For example I you want to create a react native app we install react-native-cli globally. It provides "react-native" command we use it to create a react native package.</li>
<li>If you are using ubuntu use the command "sudo npm install -g <package name>" Because it requires superuser permissions. </li>
</ul>
<h2 style="text-align: left;">
Installing local packages with npm</h2>
<h2 style="text-align: left;">
</h2>
<ul style="text-align: left;">
<li><pre>npm install <package name></pre>
</li>
</ul>
<ul style="text-align: left;">
<li>We use this command very frequently.</li>
<li>It will install the specified package locally.</li>
<li>After running the above command you can see package inside <b>"node_modules"</b> directory.</li>
<li>If you want to install the package as a dependent package then try the below command. It will save the package name in "package.json" file under dependencies.</li>
<li><pre>npm install <package name> --save</pre>
</li>
<li>If you want to install it as development dependent package then try the below command. It will save the package name in "package.json" file under devDependencies.</li>
<li><pre>npm install <package name> --save-dev</pre>
</li>
<li>we don't require the development dependent packages in production.</li>
</ul>
<h2 style="text-align: left;">
Uninstall a local package</h2>
<ul style="text-align: left;">
<li><pre>npm remove <package name> --save </pre>
</li>
</ul>
<h2 style="text-align: left;">
Uninstall a global package</h2>
<ul style="text-align: left;">
<li><pre>npm remove -g <package name> </pre>
</li>
</ul>
<h2 style="text-align: left;">
Search for a package</h2>
<ul style="text-align: left;">
<li><pre>npm search <package terms></pre>
</li>
</ul>
<h2 style="text-align: left;">
List all globally installed packages</h2>
<ul style="text-align: left;">
<li><pre>npm -g list</pre>
</li>
</ul>
<h2 style="text-align: left;">
List all locally installed packages</h2>
<ul style="text-align: left;">
<li><pre>npm list</pre>
</li>
</ul>
<h2 style="text-align: left;">
Setup for already existed package </h2>
<ul style="text-align: left;">
<li><pre>npm install</pre>
</li>
<li>when you run above command it will install all packages(development packages and production) from "package.json" file.</li>
</ul>
</div>
Anjaneyulu Battahttp://www.blogger.com/profile/04466094850374273896noreply@blogger.com0tag:blogger.com,1999:blog-4434479834026477776.post-84173264589390663562017-06-11T11:17:00.001+05:302017-06-11T11:28:28.251+05:30how to install nodejs and npm in ubuntu and windows<div dir="ltr" style="text-align: left;" trbidi="on">
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh9Qe2M8hkzvk_tC1IyhSTWpBhkGYyE-wk74JEkh66JO-g0Lny0PG9D7LXZBS1uGQbCIAdWhK6WI5dcLPeJJQqncE1kkvzrOrhRFjx6ojL9rk7E4m5nhxtPFmDk4BUwPE5plZsmE7iK-UrU/s1600/nodejs_npm.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img alt="installation of nodejs and npm" border="0" data-original-height="192" data-original-width="256" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh9Qe2M8hkzvk_tC1IyhSTWpBhkGYyE-wk74JEkh66JO-g0Lny0PG9D7LXZBS1uGQbCIAdWhK6WI5dcLPeJJQqncE1kkvzrOrhRFjx6ojL9rk7E4m5nhxtPFmDk4BUwPE5plZsmE7iK-UrU/s1600/nodejs_npm.png" title="installation of nodejs and npm" /></a></div>
<h2 style="text-align: left;">
Installation procedure of NodeJs in Ubuntu</h2>
<ol style="text-align: left;">
<li><h4>
Add NodeJS PPA to Ubuntu
with below command. It required curl package for ubuntu</h4>
<h3>
</h3>
<pre># install curl with below command<code>
sudo apt-get install curl</code>
sudo apt-get install python-software-properties
curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash -
</pre>
</li>
<li><h4>
Install NodeJs and NPM with below command</h4>
<pre>sudo apt-get install nodejs</pre>
</li>
<li><h4>
Check whether NodeJs and NPM installed or Not</h4>
<pre>node -v
npm -v</pre>
</li>
</ol>
<h2 style="text-align: left;">
Installation procedure of NodeJs in Windows</h2>
<ol style="text-align: left;">
<li><h4>
Visit NodeJs official web page <a href="https://nodejs.org/en/download/">https://nodejs.org/en/download/</a> and click on <a href="https://nodejs.org/dist/v6.11.0/node-v6.11.0-x86.msi" rel="nofollow" target="_blank">windows installer icon</a> and download it.</h4>
</li>
<li><h4>
After downloading the file(.msi) run it. It will ask for acceptance of license and terms of service, just accept it.</h4>
</li>
<li><h4>
To check the installation, Just open the command line and type the below commands</h4>
<pre>node -v
npm -v </pre>
</li>
<li><h4>
you can see the version of node and npm If <u>NodeJs & NPM</u> installed successfully. </h4>
</li>
</ol>
Please comment below If you get any errors.</div>
Anjaneyulu Battahttp://www.blogger.com/profile/04466094850374273896noreply@blogger.com0tag:blogger.com,1999:blog-4434479834026477776.post-88442311441835501872017-05-31T08:03:00.002+05:302017-05-31T08:03:41.173+05:30custom inclusion_tag vs built-in include tag django<div dir="ltr" style="text-align: left;" trbidi="on">
<div dir="ltr" style="text-align: left;" trbidi="on">
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhdQt0qSi6s04zGnRRuiFPB8ilsnxrMWYKt1ZJHOsQQpWHVlCHilBMzPCihM7iP5tn3QygcwYooQZJhpMZmnvn8LI2bkCcHduP7Fh_SsBud-s8P_KYgnwsuaz2MuPhOjqLz5kXhuTxJOeez/s1600/django-include-vs-inclusion_tag.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img alt="custom inclusion_tag vs built-in include tag django" border="0" data-original-height="285" data-original-width="508" height="179" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhdQt0qSi6s04zGnRRuiFPB8ilsnxrMWYKt1ZJHOsQQpWHVlCHilBMzPCihM7iP5tn3QygcwYooQZJhpMZmnvn8LI2bkCcHduP7Fh_SsBud-s8P_KYgnwsuaz2MuPhOjqLz5kXhuTxJOeez/s320/django-include-vs-inclusion_tag.png" title="custom inclusion_tag vs built-in include tag django" width="320" /></a></div>
<h2 style="text-align: left;">
Advantages using inclusion tags:</h2>
<ul style="text-align: left;">
<li>If we observe the templates of website we can see the repetitive code or components.</li>
<li>We can take repetitive code/component in a partial template and include it in other templates wherever the code is required.</li>
<li>We use inclusion tags (<b>include tag, custom inclusion_tag</b>) for cases like navigation menu, search forms, headers, footers, etc.</li>
<li>In future we may want to change our website / webapp structure (navigation menu or header, footer) then we don't need to change it in every template but have to change it in partial template that is included in other pages.</li>
<li>This will improve the <u>maintainability</u> of templates.</li>
</ul>
<h2 style="text-align: left;">
built-in include tag:</h2>
<ul style="text-align: left;">
<li>It is the django's built-in template tag.</li>
<li><b><i>Include tag</i> </b>it simply takes the partial template name as a string(<b>"partial/nav_menu.html"</b>) and uses the context passed from the view to render and include the partial template in the main template.</li>
<li>We can also pass the extra context to <b><i>Include tag </i></b>using<b><i> </i></b>keyword arguments.<b><i><br /></i></b></li>
<li>Use <b><i>Include tag </i></b>only when we don't need to process the context data.</li>
<li>It is simple and most used template tag in django.</li>
</ul>
<h2 style="text-align: left;">
custom inclusion_tag:</h2>
<ul style="text-align: left;">
<li><i><b>custom inclusion_tag </b></i>works same as <i><b>include tag</b></i>.</li>
<li>The only difference between <u><i><b>custom inclusion tag</b></i></u> and <i><b>include tag </b></i>is we can process the context data and render the template with processed context data.</li>
</ul>
<h2 style="text-align: left;">
It's coding time</h2>
<script src="https://gist.github.com/AnjaneyuluBatta505/65e324debe2ab60fafd2c614d6fba882.js"></script>
<ul style="text-align: left;">
<li> In above code I have passed dummy data for "pk" and "name" as extra context data in built-in include tag. In general we get it from template tags.</li>
<li>If you don't want to use the context in custom inclusion tag you can set <i>"takes_context=False</i>" (default value is False if we don't provide)</li>
</ul>
</div>
<span class="pl-c1"></span>
</div>
Anjaneyulu Battahttp://www.blogger.com/profile/04466094850374273896noreply@blogger.com0tag:blogger.com,1999:blog-4434479834026477776.post-18996695075190379792017-05-18T08:51:00.001+05:302017-05-18T08:51:13.387+05:30Implementing sitemaps in django application<div dir="ltr" style="text-align: left;" trbidi="on">
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjXFIfdaYPsEeJ59arVNPScNrO2-6_YV3Gm5nBkd5UjTWpggF14qfsfE6l_dCSgnSgP5gftQyVc10zXjp6IABlO17K-QR0egE_YQZpF8HMWby6cCzEkcSZMk7YpQf1sJvZaq9yCzQdv1PJi/s1600/sitemap-django.jpeg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="247" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjXFIfdaYPsEeJ59arVNPScNrO2-6_YV3Gm5nBkd5UjTWpggF14qfsfE6l_dCSgnSgP5gftQyVc10zXjp6IABlO17K-QR0egE_YQZpF8HMWby6cCzEkcSZMk7YpQf1sJvZaq9yCzQdv1PJi/s320/sitemap-django.jpeg" width="320" /></a></div>
<h2 style="text-align: left;">
Sitemap:</h2>
<ul style="text-align: left;">
<li>Sitemap is a collection of web pages of website that are placed in single page that is available for both search engines as well as users.</li>
<li>Xml is used to generate sitemap for a website.</li>
<li>Sitemap tells a search engine that how
frequently your contents in a page changes and follow the priority while indexing the web pages.</li>
</ul>
<h2 style="text-align: left;">
Rules of a sitemap:</h2>
<ul style="text-align: left;">
<li>A sitemap can have at most 50,000 URL's.</li>
<li>A sitemap file size should not greater than 10 MB.</li>
<li>If you have more than 50,000 URL's then you can categorize the URLS and and create sub sitemaps for it. </li>
<li>Use sitemap index to hold all the sub sitemaps of a website.</li>
<li>Submit the sitemap index to the search engine bots. It will automatically crawls the all web pages from a given website.</li>
</ul>
<h2 style="text-align: left;">
Sitemaps framework in django</h2>
<ul style="text-align: left;">
<li><div style="text-align: left;">
It automates the creation of sitemap xml</div>
</li>
<li>We can classify the urls of a website as static and dynamic </li>
</ul>
<h2 style="text-align: left;">
Configurations of sitemaps framework</h2>
<ul style="text-align: left;">
<li>We have to add <i><b>'django.contrib.sitemaps'</b></i> in <i><b>INSTALLED_APPS</b></i> setting. </li>
<li>You must add<i><b> 'APP_DIRS': True</b></i> in <i><b>TEMPLATES</b></i> setting.</li>
</ul>
Sitemaps framework provides two classes <b><span class="pl-en">Sitemap </span></b><span class="pl-en">and </span><b><span class="pl-en">GenericSitemap.</span></b><br />
<h3 style="text-align: left;">
<b><span class="pl-en">Sitemap Class:</span></b></h3>
<ul style="text-align: left;">
<li>It has the following attributes or methods that will help in creating the sitemap.</li>
<li><h3>
<b>items:</b>
</h3>
<ul>
<li>It is a method and It returns <u>list of objects</u>.</li>
<li>Every object that is returned from this method will be passed to location(), lastmod(), changefreq() and priority() methods. </li>
</ul>
</li>
</ul>
<ul style="text-align: left;">
<li><h3>
<b>location:</b>
</h3>
<ul style="text-align: left;">
<li>It is either an attribute or a method </li>
<li>If it is a method, It takes an <u>item/object</u> as a argument.</li>
<li>It's responsible for returning the <u>absolute path.</u></li>
<li>Absolute path should not contains <i>protocol(http, https), domain name.</i></li>
<li>Example: "/contact-us/", "/country/india/"</li>
<li>If you do not override it will call <b>"obj.get_absolute_url()" </b>by default.</li>
<li>If the object doesn't have <i>get_absolute_url</i> it will raises an error.</li>
</ul>
</li>
</ul>
<ul style="text-align: left;">
<li><h3>
<b>lastmod:</b><b> </b></h3>
<ul>
<li>It is either an attribute or a method. </li>
<li>It is responsible for returning a date or datetime object. </li>
<li>It returns none by default.</li>
<li>It is used to tell a search engine that when the page is last modified.</li>
</ul>
<br />
<ul>
</ul>
</li>
</ul>
<div>
<ul style="text-align: left;">
<li><h3>
changefreq:</h3>
<ul style="text-align: left;">
<li>It is either an attribute or a method.</li>
<li>If it is a method, It takes an <u>item/object</u> as a argument.</li>
<li>It tells search engines that how frequently a web page changes.</li>
<li>Possible values are <i>"always", "hourly", "daily", "weekly", "monthly", "yearly", "never" </i></li>
</ul>
</li>
<li><h3>
priority:</h3>
<ul style="text-align: left;">
<li>The priority of this URL relative to other URLs on your site.</li>
<li>It's valid values range
from 0.0 to 1.0.</li>
<li>It only lets the search engines know which pages you deem most
important for the crawlers. </li>
<li>
The default priority of a page is 0.5.<br />
</li>
</ul>
</li>
<li><h3>
protocol:</h3>
<ul style="text-align: left;">
<li>It is an attribute. It specifies which version of protocol to use while generating full url.</li>
<li>Possible values are "http", "https"</li>
<li>Default values is "http"</li>
</ul>
</li>
<li><h3>
i18n:</h3>
<ul style="text-align: left;">
<li>It is a boolean attribute.</li>
<li>If it is true then it will add a language prefix for all urls.</li>
<li>By default it is set to <u>"False"</u></li>
</ul>
</li>
</ul>
<h3 style="text-align: left;">
<span class="pl-en">GenericSitemap:</span></h3>
<ul style="text-align: left;">
<li><div style="text-align: left;">
It simply inherits the <u>Sitemap</u> class. So, It gets all the above mentioned properties.</div>
</li>
</ul>
<ul style="text-align: left;">
<li>It takes arguments <i>"info_dict", "priority", "changefreq", "protocol".</i></li>
<li><i>info_dict</i> contains two keys<i> 1. "queryset", 2. "date_field"</i></li>
<li> We don't need to write extra classes for Sitemaps instead we can use it</li>
</ul>
Now, It's coding time.<br />
<script src="https://gist.github.com/AnjaneyuluBatta505/4133d3f30bad825e68f0c70a064e5f1d.js"></script> If we use sitemap view for urls below 50,000 and sitemap index for above 5,000.</div>
</div>
Anjaneyulu Battahttp://www.blogger.com/profile/04466094850374273896noreply@blogger.com0tag:blogger.com,1999:blog-4434479834026477776.post-32957151180071634392017-05-12T09:26:00.000+05:302017-05-12T09:26:09.955+05:30django base template structure for template inheritance<div dir="ltr" style="text-align: left;" trbidi="on">
<div dir="ltr" style="text-align: left;" trbidi="on">
<div class="separator" style="clear: both; text-align: center;">
</div>
<table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"><tbody>
<tr><td style="text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj-QtufUdkWaWlOPiF3L_qIPSII_cKqtRosyhhz3zmR2lQrDsJfGG0SSfxOa0fnj4809hU_hNwwYJJKc5hgBUt3XdZJtYKTM4SL9dnSmH_qy8nmCAr0kJLt3ryHa_NRsoXkYPzMIbCSql5A/s1600/django-template-inheritance.png" imageanchor="1" style="margin-left: auto; margin-right: auto;"><img alt="django template inheritance" border="0" height="442" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj-QtufUdkWaWlOPiF3L_qIPSII_cKqtRosyhhz3zmR2lQrDsJfGG0SSfxOa0fnj4809hU_hNwwYJJKc5hgBUt3XdZJtYKTM4SL9dnSmH_qy8nmCAr0kJLt3ryHa_NRsoXkYPzMIbCSql5A/s640/django-template-inheritance.png" title="django template inheritance" width="640" /></a></td></tr>
<tr><td class="tr-caption" style="text-align: center;">django template inheritance</td></tr>
</tbody></table>
<ul>
<li>Generally we develop websites to show our products or services to customers all over the web.</li>
<li>Our customers only can find our services or products through search engines like Google, Yahoo, Bing, etc.</li>
<li>We/Owner of website register his/her website at search engines to crawl and index our products in the search engine's database.</li>
<li>The indexed products appears in the customers search when they search in search engines.</li>
<li>Based on the meta data, web page content and speed of the web page(load time) search engine will give rank to our web page.</li>
<li>In order to get good rankings in search engines we need to develop our django templates by considering above factors.</li>
<li>To reduce the code and to increase the maintainability we use <b>template inheritance</b> in <i>django templates</i>.</li>
</ul>
Every web page must contain two types HTML tags head and body.<br />
<h3 style="text-align: left;">
head Tag:</h3>
<ul style="text-align: left;">
<li>
Inside head tag we provide information like web page title, search key words, web page description.
</li>
<li>Above information is useful for search engines. When search engines crawl our web page they look for information inside head tag.</li>
<li>It will help us to index our products or services in search engines.</li>
<li>It works fine but It would be better if we have a good speed in page loading. This would certainly help us to get better rankings in search engines.</li>
<li>web page loads and applies the styles from style sheet resources.</li>
<li>In order to get style sheets browser will send a request to the resource server. If server takes more time if the resource size is more. </li>
<li>To reduce the size of style sheets/resources we use compressor tools like <a href="https://django-compressor.readthedocs.io/en/latest/" rel="nofollow" target="_blank">"django compressor"</a>.</li>
<li>It will reduce stylesheet(css) size so that server can serve it quickly.</li>
<li>It's a best approach not to load the javascript resources inside the head tag.</li>
</ul>
<h3 style="text-align: left;">
Body Tag: </h3>
<ul style="text-align: left;">
<li>Inside the body tag we display our information like our services and products to the customer.</li>
<li>It's a best approach to load the javascript resources just before the end of body tag.</li>
<li> This will improve the page displaying time and It's better to compress the javascript also by using the <a href="https://django-compressor.readthedocs.io/en/latest/" rel="nofollow" target="_blank">"django compressor"</a> tool.</li>
</ul>
<h3 style="text-align: left;">
Let's design the base template structure: </h3>
<pre class="brush: py">{% load compress %}
<!DOCTYPE html>
<html>
<head>
<title> {% block title %} Learn Html {% endblock %}</title>
{% block metadata %}
<meta charset="utf-8">
<meta name="description" content="easy way to learn HTML">
<!-- other html tags here -->
{% endblock %}
{% block cdn_css %}
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
{% endblock %}
{% compress css %}
{% block local_css %}
<link rel="stylesheet" href="{% static 'css/main.css' %}">
{% endblock %}
{% block internal_css %}
<style>
body{
color: black;
}
</style>
{% endblock %}
{% endcompress %}
</head>
<body>
{% block content %}
Main content
{% endblock %}
{% block cdn_js %}
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!-- other cdn javascript links -->
{% endblock %}
{% compress js %}
{% block local_js %}
<script src="{% static 'js/main.js' %}"></script>
<!-- other cdn javascript links -->
{% endblock %}
{% block internal_js %}
<script type="text/javascript">
console.log(" I'm working...")
<!-- extra script -->
</script>
{% endblock %}
{% endcompress %}
</body>
</html> </pre>
</div>
<br />
<h3 style="text-align: left;">
title Block:</h3>
<div style="text-align: left;">
Title will change from page to page. After extending or inheriting the <b>base.html </b>we can override the title block to define our page title. </div>
<h3 style="text-align: left;">
metadata Block:</h3>
<div style="text-align: left;">
Metadata also changes page to page we can also override/overload it by defining the block in inherited page.</div>
<h3 style="text-align: left;">
cdn_css Block:</h3>
<div style="text-align: left;">
This block is used to link the cdn css files from could that will be used to style the page. Do not include the all css files in <b>base.html</b> file. </div>
<h3 style="text-align: left;">
local_css Block:</h3>
<div style="text-align: left;">
This block is used to link our local external css files. This should be defined below the cdn_css block because we may override/overload styles of cdn css files.</div>
<h3 style="text-align: left;">
internal_css Block:</h3>
<div style="text-align: left;">
Some times we also need internal styles for every page. In this kind of scenarios we can override/overload the <b>internal_css</b> block. </div>
<h3 style="text-align: left;">
content Block:</h3>
<div style="text-align: left;">
This block is used to render our main HTML content.</div>
<h3 style="text-align: left;">
cdn_js Block:</h3>
<div style="text-align: left;">
Some times we use external javascript plugins in some of the pages. If it it the case then override/overload <b>cdn_js</b> block.</div>
<h3 style="text-align: left;">
local_js Block:</h3>
<div style="text-align: left;">
We use this block to link our local javascript libraries to the page. This will improves the page structure.</div>
<h3 style="text-align: left;">
internal_js Block:</h3>
<div style="text-align: left;">
In many cases we write internal javascript. For this type of cases we can override/overload <b>"internal_js" </b>block.</div>
<h3 style="text-align: left;">
what is the use of writing css blocks inside "compress" tag ?</h3>
<div style="text-align: left;">
If we write javascript block inside the compress tag then django
compressor will gather all the css data and minimizes it.<br />
Note: do not include cloud css links inside "compress" tag block. </div>
<h3 style="text-align: left;">
what is the use of writing javascript blocks inside "compress" tag ?</h3>
<div style="text-align: left;">
If we write javascript block inside the compress tag then django compressor will gather all the javascript data and minimizes it.<br />
<br /><b>Notes:</b><br />
<ul style="text-align: left;">
<li>Do not include cloud javascript or css links inside "compress" tag block.<br /> </li>
<li>Use <b>"{{ block.super }}"</b> to inherit the content from the block in <b>base.html</b>.</li>
</ul>
<br /></div>
</div>
Anjaneyulu Battahttp://www.blogger.com/profile/04466094850374273896noreply@blogger.com0tag:blogger.com,1999:blog-4434479834026477776.post-79209001922761080042017-05-04T22:28:00.003+05:302017-05-04T22:49:52.871+05:30django debug toolbar - improve application performance<div dir="ltr" style="text-align: left;" trbidi="on">
<table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"><tbody>
<tr><td style="text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhVXtD2h1fg21V0z7ZvbhbZCSB4OnHOrV5x1uGqPwYAU-44duroKf8w8PjpBH1He-GL6LZ7MBHMIwfOtJkY_2muEhQEMN075nicb0WVOdunNF9t0Yi1rGRPQdHWIIqjUIgFH4lQl6RGake0/s1600/django-debug-toolbar.png" imageanchor="1" style="margin-left: auto; margin-right: auto;"><img alt="django debug toolbar" border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhVXtD2h1fg21V0z7ZvbhbZCSB4OnHOrV5x1uGqPwYAU-44duroKf8w8PjpBH1He-GL6LZ7MBHMIwfOtJkY_2muEhQEMN075nicb0WVOdunNF9t0Yi1rGRPQdHWIIqjUIgFH4lQl6RGake0/s1600/django-debug-toolbar.png" title="django debug toolbar" /></a></td></tr>
<tr><td class="tr-caption" style="text-align: center;">django debug toolbar</td></tr>
</tbody></table>
<h2 style="text-align: left;">
debugging:</h2>
<ul style="text-align: left;">
<li>It is the process of locating and correcting the errors in a computer program or code.</li>
<li>debugging is an integral part of software testing.</li>
<li>debugging improves code quality and eases the maintainability of a software.</li>
</ul>
<h2 style="text-align: left;">
debugging tool:</h2>
<ul style="text-align: left;">
<li>A debugging tool is comprised of one or more computer programs that are used to locate the errors in other programs.</li>
</ul>
<h2 style="text-align: left;">
django debug toolbar: </h2>
<ul style="text-align: left;">
<li>It is one of the best debugging tools for the django applications.</li>
<li>debug toolbar makes developer life simple. Developer need not to worry about common lookups like settings, request data, etc.</li>
<li>By using this tool we can quickly find out the error location. It helps developers to keep headache away.</li>
</ul>
<h2 style="text-align: left;">
tools provided by debug toolbar: </h2>
<ul style="text-align: left;">
<li><h3 style="text-align: left;">
versions:</h3>
<ul>
<li>It provides the information of packages that are used in our django application.</li>
<li>It lists out package, package name and package version.</li>
<li>In some cases we need to have a specific version of a package but we may use advanced version of the package. We may get errors by using toolbar we can quickly have a look on it. </li>
<li>example: wee need djcelery==2.9.1 but we used djcelery==3.2.1</li>
</ul>
</li>
<li><h3>
time:</h3>
<ul>
<li>It helps to use our system resources(CPU) effectively.</li>
<li>It lists out the time used by each resource(user CPU time, System CPU time, etc) in milli seconds.</li>
<li>It also provides the timing browser when our web page is loaded.</li>
<li>It provides the time information like domain lookup, connect, request, response, DOM loading, DOM ContentLoadedEvent, load event.</li>
</ul>
</li>
<li><h3>
Settings:</h3>
<ul>
<li>It quickly lists out our django project settings in a tabular format.</li>
<li>We need not go to the ide/editor to see project settings. </li>
</ul>
</li>
<li><h3>
Headers: </h3>
<ul>
<li>It summaries the information of HTTP request.</li>
<li>It provides information of headers sent in the HTTP request as well as headers received in the HTTP response.</li>
<li>In some cases we need to send authentication information like tokens in HTTP request headers.</li>
<li>It helps us to check whether we sent authentication token in headers or not.</li>
</ul>
</li>
<li><h3>
Request:</h3>
<ul>
<li>
It contains the information of view, session data, cookies, GET data, POST data</li>
<li> By using this we can quickly navigate to the respective view</li>
<li>And also can be able to see data handled by the request</li>
</ul>
</li>
<li><h3>
SQL:</h3>
<ul>
<li>It shows the number of queries executed on a page and time taken each query in milliseconds.</li>
<li>It also shows the django equivalent of raw SQL.</li>
<li>Reduce the number of queries to improve the application performance. </li>
</ul>
</li>
<li><h3>
Static files:</h3>
<ul>
<li>It lists the static files and paths of static files for quick navigation. </li>
</ul>
</li>
<li><h3>
Templates: </h3>
<ul>
<li>It shows template directory paths</li>
<li>It also lists out the templates used in creating the response.</li>
<li>It helps us for quick navigation to a template.</li>
</ul>
</li>
<li><h3>
Cache: </h3>
<ul>
<li>It summaries the cache of our django application</li>
</ul>
</li>
<li><h3>
Signals: </h3>
<ul>
<li>It lists out the signals and receivers used in the page rendering.</li>
<li>It helps if we write custom signals or receivers.<br /> </li>
</ul>
</li>
<li><h3>
Logging: </h3>
<ul>
<li>It shows logging messages information<br />
</li>
</ul>
</li>
</ul>
<h2 style="text-align: left;">
How to use django debug toolbar ?</h2>
<div style="text-align: left;">
add the below code at the end of the settings file.</div>
<div style="text-align: left;">
<u><b>settings.py</b></u></div>
<pre class="brush: py">if DEBUG:
MIDDLEWARE_CLASSES = MIDDLEWARE_CLASSES + [
'debug_toolbar.middleware.DebugToolbarMiddleware',
]
INSTALLED_APPS = INSTALLED_APPS + [
'debug_toolbar',
]
INTERNAL_IPS = ('127.0.0.1', )
DEBUG_TOOLBAR_CONFIG = {
'INTERCEPT_REDIRECTS': False,
}
</pre>
<div style="text-align: left;">
add the below code at the end of the project urls file. </div>
<div style="text-align: left;">
<u><b>urls.py</b></u>
<br />
<pre class="brush: py">if settings.DEBUG:
import debug_toolbar
urlpatterns += [
url(r'^__debug__/', include(debug_toolbar.urls)),
]
</pre>
</div>
</div>
Anjaneyulu Battahttp://www.blogger.com/profile/04466094850374273896noreply@blogger.com0tag:blogger.com,1999:blog-4434479834026477776.post-52340193845143979712017-04-30T11:29:00.000+05:302017-04-30T11:29:50.778+05:30django send one time use account activation email<div dir="ltr" style="text-align: left;" trbidi="on">
<table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"><tbody>
<tr><td style="text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjWUWyEJ4jgYhWbsiowYBd-V7CU-nGZXY_91DGQqSwnfEydcRXRxs_7f_G54QpEziHLNb6wxjse-dRgBuMWujk_YP7f1GboAT3AdFPf5FmJTQshgCorZQ2il0_f_EE4gAIdJalr6CG5PZqk/s1600/one_time_activation_link_django.png" imageanchor="1" style="margin-left: auto; margin-right: auto;"><img border="0" height="433" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjWUWyEJ4jgYhWbsiowYBd-V7CU-nGZXY_91DGQqSwnfEydcRXRxs_7f_G54QpEziHLNb6wxjse-dRgBuMWujk_YP7f1GboAT3AdFPf5FmJTQshgCorZQ2il0_f_EE4gAIdJalr6CG5PZqk/s640/one_time_activation_link_django.png" width="640" /></a></td></tr>
<tr><td class="tr-caption" style="text-align: center;">django one time activation link email</td></tr>
</tbody></table>
<ul style="text-align: left;">
<li>After success registration of the user, we will send activation link email to the users email account. </li>
<li>After clicking the activation link we have to activate users account & make user login. </li>
<li>This process will avoid the fake accounts in our application.</li>
</ul>
<b>app/urls.py</b><br />
<pre class="brush: py">from django.conf.urls import url
from app import views
urlpatterns = [
# ......
url(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/account/$',
views.activate_user_account, name='activate_user_account'),
# ......
]
</token></uidb64></pre>
<b>app/views.py</b><br />
<pre class="brush: py">from django.core.urlresolver import reverse
from django.contrib.auth import login
from django.conf import settings
from django.utils.encoding import force_bytes
from django.utils.encoding import force_text
from django.utils.http import urlsafe_base64_encode
from django.core.mail import EmailMultiAlternatives
from django.contrib.auth.tokens import default_token_generator
from django.core.urlresolvers import reverse
from django.template.loader import render_to_string
from django.http import HttpResponse
from app.models import User
def send_account_activation_email(request, user):
text_content = 'Account Activation Email'
subject = 'Email Activation'
template_name = "emails/account/activation.html"
from_email = settings.DEFAULT_FROM_EMAIL
recipients = [user.email]
kwargs = {
"uidb64": urlsafe_base64_encode(force_bytes(user.pk)).decode(),
"token": default_token_generator.make_token(user)
}
activation_url = reverse("app:activate_user_account", kwargs=kwargs)
activate_url = "{0}://{1}{2}".format(request.scheme, request.get_host(), activation_url)
context = {
'user': user,
'activate_url': activate_url
}
html_content = render_to_string(template_name, context)
email = EmailMultiAlternatives(subject, text_content, from_email, recipients)
email.attach_alternative(html_content, "text/html")
email.send()
def activate_user_account(request, uidb64=None, token=None):
try:
uid = force_text(urlsafe_base64_decode(uidb64))
user = User.objects.get(pk=uid)
except User.DoesNotExist:
user = None
if user and default_token_generator.check_token(user, token):
user.is_email_verified = True
user.is_active = True
user.save()
login(request, user)
return redirect('hr:user_profile')
else:
return HttpResponse("Activation link has expired")
</pre>
<b>emails/account/activation.html</b><br />
<pre class="brush:py"><html>
<title> Email Activation </title>
<body>
<p> Dear {{ user }}</p>
<p>Your account has successfully created. Please click below link to activate your account.</p>
<p><a href="{{ activate_url }}"> Activate your account </a></p>
</body>
</html>
</pre>
In the last blog post <a href="https://django-easy-tutorial.blogspot.in/2017/04/django-form-usage-and-validations.html" target="_blank">"User Registration"</a> we have seen how to register a user.<br />
<br />
Let's start our discussion,<br />
<ul style="text-align: left;">
<li><b>"urlsafe_base64_encode" </b>takes user id and generates the base64 code(uidb64)</li>
<li><b>"default_token_generator.make_token" </b>takes the user object and generates the onetime usable token for the user(token)</li>
<li>we create activation email using uidb64 and token and send it to user's email.</li>
<li>after clicking the activation url it will dispatched to the <b>"activate_user_account"</b> view</li>
<li>Here we receive <b>"uidb64", "token". </b>By using the <b>"urlsafe_base64_decode"</b> we decode the base64 encoded <b>"uidb64"</b> user id. We query the database with user id to get user.</li>
<li>We check the token validation using <b>"default_token_generator.check_token</b>" and <b>"user object"</b></li>
</ul>
Reference: <a href="https://github.com/django/django/blob/master/django/contrib/auth/tokens.py#L80">https://github.com/django/django/blob/master/django/contrib/auth/tokens.py#L80</a><br />
Please comment if you have any questions.<br />
<b> </b></div>
Anjaneyulu Battahttp://www.blogger.com/profile/04466094850374273896noreply@blogger.com0tag:blogger.com,1999:blog-4434479834026477776.post-50894013294187278222017-04-29T23:56:00.000+05:302017-04-30T10:01:38.802+05:30django form usage and validations<div dir="ltr" style="text-align: left;" trbidi="on">
<div dir="ltr" style="text-align: left;">
<div>
<div>
<div>
<div style="text-align: left;">
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEicQSt8ac9Zjoztxwl3G2TTyucwJhg9FtacoNMoldrI66au82b3KjIkQd875E_uUF_9a75oVV4wTO1eJXvwa9EGEpNncX8AkN0IZ9YIAeYS70GHFb35BXDYs0IyRx_B11D-Ow6SjcgF1_Vy/s1600/django-contact-forms.jpg"><img alt="django form usage and validations" border="0" height="350" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEicQSt8ac9Zjoztxwl3G2TTyucwJhg9FtacoNMoldrI66au82b3KjIkQd875E_uUF_9a75oVV4wTO1eJXvwa9EGEpNncX8AkN0IZ9YIAeYS70GHFb35BXDYs0IyRx_B11D-Ow6SjcgF1_Vy/s400/django-contact-forms.jpg" title="django form usage and validations" width="400" /></a></div>
Let's start with an example, If you are applying for a college admission you will fill up the college admission form with your details and submit it to the college.<br />
It's general process for college admission. No web interactivity.<br />
<br />
If we are applying for a college in web. We go to college website and we fill the details in a web form(HTML Form) and submit it.<br />
<br />
In backend web application will store the data submitted by the student/user.<br />
To avoid the data redundancy or invalid data we have to validated the form and show the errors to the user to take relevant information from the user.<br />
<br />
Developer part:<br />
To perform the above process developer has to write the html forms with hands. It consumes the time of developer. we can avoid writing of html forms with django forms.<br />
<br />
<h3 style="text-align: left;">
Advantages of using the django forms</h3>
<br />
1. Automated HTML creation<br />
2. Basic validation of data<br />
3. Custom validations for fields<br />
4. Automatic saving of data for model forms<br />
<br />
Let's start using Django Forms<br />
<br />
<b>Use Case: User Registration for web application</b><br />
<br />
<b>app/forms.py</b><br />
<pre class="brush: py">from django import forms
from app.models import User
class RegistrationForm(forms.Form):
first_name = forms.CharField()
last_name = forms.CharField()
email = forms.EmailField()
password = forms.CharField(widget=forms.HiddenInput())
profile_pic = forms.ImageField()
address = forms.CharField(widget=forms.Textarea())
def clean_email(self):
email = self.cleaned_data.get('email')
# check and raise error if other user already exists with given email
is_exists = User.objects.filter(email=email).exists()
if is_exists:
raise forms.ValidationError("User already exists with this email")
return email
def clean(self):
data = self.cleaned_data
# use your logic for non field errors
return data
</pre>
<br />
<h3 style="text-align: left;">
Django forms consists of three components.</h3>
<br />
1. Fields<br />
2. Widgets<br />
3. Custom Validators<br />
<br />
<b>1.Fields:</b> <br />
<ul style="text-align: left;">
<li>It is responsible for basic validation of data</li>
<li>Every field has default validation logic and a default widget.</li>
<li>It generates the HTML form elements with the help of widgets.</li>
<li>HTML form elements "input", "textarea", "select", "checkbox", "radio", etc.</li>
<li>Django Form Fields:</li>
</ul>
</div>
<div style="text-align: left;">
<b>2.Widgets:</b></div>
<div style="text-align: left;">
<ul style="text-align: left;">
<li>It is responsible for generation of HTML form elements.</li>
<li>we can write and use custom widgets</li>
</ul>
</div>
</div>
<b>3. Custom Validators</b><br />
<ul style="text-align: left;">
<li><b> </b>The Custom Validator allows us to create a validation control with customized validation logic.</li>
</ul>
<h3 style="text-align: left;">
Levels of validations in django forms</h3>
<br />
1. Basic Field Validation<br />
2. Custom Field Validation<br />
3. Non Fields Validation / Common Fields Validation <b> </b><br />
<br />
<b>1. Basic Field Validation</b><br />
<ul style="text-align: left;">
<li>It is the first method to validate the data (<b>"to_python"</b>)</li>
<li>Every field has a basic validation logic based on the type </li>
<li>Example: <b>"EmailField"</b> has the logic to validate whether the given data is valid email or not.</li>
</ul>
</div>
<b>2. Custom Field Validation</b><br />
<ul style="text-align: left;">
<li>It is called after basic validation method <b>"to_python"</b>.</li>
<li>It has method signature as <b>"clean_<field name>"</b></li>
<li>Validation logic goes inside the method</li>
</ul>
<b>3. Non Fields Validation / Common Fields Validation</b><br />
<ul style="text-align: left;">
<li>It is called after the custom field validation method.</li>
<li>method signature is <b>"clean"</b></li>
<li>we override it only if we need to validate multiple fields at the same time.</li>
</ul>
</div>
<h3 style="text-align: left;">
<b> Handling django forms</b></h3>
<div style="text-align: left;">
<pre class="brush: py">form = RegistrationForm(data={}, files={}, initial={})
</pre>
django form class takes the three initial arguments "data", "files", "initial" if we provide it otherwise it takes it as empty.<br />
<b>data: form data</b><br />
<b>files: form files</b><br />
<b>initial: initial data to be rendered with widgets to show to the user.</b><br />
<br />
<h3 style="text-align: left;">
Form usage in views</h3>
<pre class="brush: py">def register(request):
"""
create user & send one time activation email to user
"""
print(request.POST, request.FILES)
# make sure to keep enctype="multipart/form-data" in html form
if request.POST:
form = RegistrationForm(request.POST, request.FILES)
if form.is_valid():
print(form.cleaned_data)
first_name = form.cleaned_data.get("first_name")
last_name = form.cleaned_data.get("last_name")
email = form.cleaned_data.get("email")
profile_pic = form.cleaned_data.get("profile_pic")
password = form.cleaned_data.get("password")
user = User.objects.create(
first_name=first_name,
last_name=last_name,
email=email,
profile_pic=profile_pic,
is_active=False
)
user.set_password(password)
user.save()
print(user)
# send one time activation email
# send_account_activation_email(request, user)
return redirect('books_list')
else:
form = RegistrationForm()
return render(request, 'registration.html', {'form': form})
</pre>
<div style="text-align: left;">
form.cleaned_data => returns a dictionary with validated data</div>
<div style="text-align: left;">
form.is_valid() => returns a boolean True if form data is valid otherwise False</div>
<h3 style="text-align: left;">
Form usage in template</h3>
<pre class="brush: py">{% extends 'base.html' %}
{% block content %}
<div class="wrapper" style="color: blue; padding: 100px;">
<form action="" enctype="multipart/form-data" method="POST">
<legend> Registration </legend>
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="submit" />
</form>
</div>
{% endblock %}
</pre>
<br />In the next blog post we will see sending one time use activation link email.<br />
References:<br />
<a href="https://docs.djangoproject.com/en/1.11/topics/forms/">https://docs.djangoproject.com/en/1.11/topics/forms/</a><br />
<a href="https://github.com/django/django/blob/master/django/forms/forms.py">https://github.com/django/django/blob/master/django/forms/forms.py</a></div>
<div>
</div>
</div>
</div>
Anjaneyulu Battahttp://www.blogger.com/profile/04466094850374273896noreply@blogger.com0tag:blogger.com,1999:blog-4434479834026477776.post-72512935344336204892017-04-01T20:27:00.000+05:302017-04-01T20:34:38.953+05:30usage of css, javascript, images in django<div dir="ltr" style="text-align: left;" trbidi="on">
<div dir="ltr" style="text-align: left;" trbidi="on">
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiUz58tmRpvHOIvggAwkfvV0KoRwrrEiQ1q6GvqKEZrEj8_DfZ9u2hitm5eS-XrR0x8S41gCETxjeHGhKBTMKIsexImuO5oacXuwONUpzpoYfhq4_mxoIGpNXiboz-Nb69Ddzy-Uhf6Zikh/s1600/django-static-files-archtechture.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiUz58tmRpvHOIvggAwkfvV0KoRwrrEiQ1q6GvqKEZrEj8_DfZ9u2hitm5eS-XrR0x8S41gCETxjeHGhKBTMKIsexImuO5oacXuwONUpzpoYfhq4_mxoIGpNXiboz-Nb69Ddzy-Uhf6Zikh/s1600/django-static-files-archtechture.png" /></a></div>
In the last post we have seen <a href="http://django usage of template and view " target="_blank">how to use html template in django view</a>. In this tutorial we will learn about usage of static files in django.<br />
<br />
Before we are going to use CSS and JavaScript, we have to know why we use them. Let's start with HTML<br />
<br />
<h3 style="text-align: left;">
HTML - Hyper Text Markup Language</h3>
HTML is the basic language of the web. It describes the how a web page should look. When a browser loads the web page it reads the HTML instructions line by line and follows it to present the web page.<br />
Once the HTML instructions in the are completed then the browser stops working, because the HTML program is over.<br />
<br />
<h3 style="text-align: left;">
CSS - Cascading Style Sheets</h3>
<div id="GingerWidget-originalHtmlText" style="display: block;">
<span class="mistake">You</span> may arise a question that we have HTML why we need CSS.</div>
<div id="GingerWidget-originalHtmlText" style="display: block;">
<span class="mistake"></span>
</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjGLYRWjmButZ1sKdL9thl_4spiZE-Y6Im7W-hlA8Kca1AFQ1rPFQCLkPYBSAEU7nJavocUIE0ffRStrPHoX9CaO_i5Gf85KabngqMsmPO4GrJscAXnihyzGUyA1e9MvzRdy7Q8J19607oN/s1600/HTML_VS_CSS.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="200" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjGLYRWjmButZ1sKdL9thl_4spiZE-Y6Im7W-hlA8Kca1AFQ1rPFQCLkPYBSAEU7nJavocUIE0ffRStrPHoX9CaO_i5Gf85KabngqMsmPO4GrJscAXnihyzGUyA1e9MvzRdy7Q8J19607oN/s400/HTML_VS_CSS.jpg" width="400" /> </a></div>
<div class="separator" style="clear: both; text-align: center;">
<br /></div>
In above picture we are comparing the HTML and HTML + CSS.<br />
HTML just provides us basic structure of a web page, If we apply styles(CSS) to it we can make awesome web pages. <br />
<h3 style="text-align: left;">
JavaScript </h3>
By using HTML + CSS can only provide then best presentation, but user can't able to interact with the web page. Here comes our superman JavaScript.<br />
<br />
JavaScript allows a user to interact with the web page.<br />
For example, </div>
<div onmouseout="mOut(this)" onmouseover="mOver(this)" style="background-color: #d94a38; height: 20px; margin-left: 25%; padding: 40px; width: 200px;">
mouse over me</div>
<script>
function mOver(obj) {
obj.innerHTML = "Thank You"
}
function mOut(obj) {
obj.innerHTML = "mouse over"
}
</script> If you mouse over the above box, it will say thanks.<br />
By using JavaScript we can make web page more lively.<br />
We can make animations, games, etc. by using HTML + CSS + JavaScript<br />
Best Websites using JavaScript<br />
<a href="http://www.filippobello.com/portfolio" rel="nofollow" target="_blank">http://www.filippobello.com/portfolio</a><br />
<a href="http://www.legworkstudio.com/" rel="nofollow" target="_blank">http://www.legworkstudio.com/</a><br />
<br />
Now, It's time to use the static files in our django application.<br />
If you don't setup static settings yet, setup <a href="https://django-easy-tutorial.blogspot.in/2017/03/django-project-layout-and-settings.html" target="_blank">static settings</a> in settings.py<br />
<br />
<b>static/img/books_back.jpg</b><br />
It is the background image used in the template.<b> </b><br />
<b>static/css/main.css</b><br />
<pre>html, body {
height: 100%;
margin: 0;
}
.wrapper {
min-height: 85%;
/* Equal to height of footer */
/* But also accounting for potential margin-bottom of last child */
margin-bottom: -50px;
background: #ece4e4;
background-image: url("/static/img/books_back.jpg");
background-repeat: no-repeat;
}
.footer,
.push {
height: 50px;
}
.header{
height: 50px;
background: #d4d0d0;
line-height: 2.5;
text-align: center;
font-size: 17pt;
color: green;
font-weight: 600;
}
.footer{
line-height: 3.5;
background: #d4d0d0;
text-align: center;
vertical-align: text-bottom;
}
</pre>
<br />
<b>static/js/main.js</b><br />
<pre>alert("Javascript Test");
console.log("Javascript is working");
</pre>
<br />
<b>templates/home.html</b><br />
<br />
<pre>{% load static %}
<!DOCTYPE html>
<html>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="{% static 'css/main.css' %}">
<head>
<title> Library Management </title>
</head>
<body>
<div class="header">Library Management</div>
<div class="wrapper">
<div class="container">
<h2><a href="#" class="btn btn-primary">Login</a></h2>
<h2><a href="#" class="btn btn-primary">Register</a></h2>
</div>
</div>
</div>
<div class="push"></div>
</div>
<footer class="footer">copyrights &copy; 2017</footer>
</body>
<script type="text/javascript" src="{% static 'js/main.js' %}"></script>
</html>
</pre>
<br />
<br />
<ul style="text-align: left;">
<li>{% load static %} will load the built-in template tags from the static library.</li>
<li><b>static </b>is a built-in template tag that will return the static path.</li>
<li><b>{% static 'css/main.css' %}</b> is equivalent to <b>static/css/main.css</b></li>
<li>If it works fine you will get an alert message.<b> </b></li>
</ul>
</div>
Anjaneyulu Battahttp://www.blogger.com/profile/04466094850374273896noreply@blogger.com0tag:blogger.com,1999:blog-4434479834026477776.post-4269010490005642502017-03-31T21:47:00.000+05:302017-03-31T21:47:19.951+05:30django usage of template and view<div dir="ltr" style="text-align: left;" trbidi="on">
<div dir="ltr" style="text-align: left;" trbidi="on">
<div>
<table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"><tbody>
<tr><td style="text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg0ZSAYFnlsIhmaJoDgwEQhWqaGBIfya-schVp4wFU4l7sGgDKp0wt-QVfjvd560Jqgj0Hi3_atwib4biZ5Gr5NpsKy1qHkRzLWj4iJLIJ0IDsnbEQbA6_I73Bj88sD0037IkbuK6jjo4eA/s1600/django-usuage-of-template-and-view.png" imageanchor="1" style="margin-left: auto; margin-right: auto;"><img alt="django usage of template and view" border="0" height="467" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg0ZSAYFnlsIhmaJoDgwEQhWqaGBIfya-schVp4wFU4l7sGgDKp0wt-QVfjvd560Jqgj0Hi3_atwib4biZ5Gr5NpsKy1qHkRzLWj4iJLIJ0IDsnbEQbA6_I73Bj88sD0037IkbuK6jjo4eA/s640/django-usuage-of-template-and-view.png" title="django usage of template and view" width="640" /></a></td></tr>
<tr><td class="tr-caption" style="text-align: center;">django templates & views</td></tr>
</tbody></table>
<br />In the last blog post we have seen <a href="http://django-easy-tutorial.blogspot.in/2017/03/django-models-and-database-schema-design.html" target="_blank">how to write models for project</a>. In this blog post we are going learn about usage of <i>templates</i> in django views.<br />
<br />
Before start writing the <b>view </b>read the <a href="http://django-easy-tutorial.blogspot.in/2017/03/django-request-lifecycle.html" target="_blank">django request life cycle</a> for better understanding.<br />
<br />
Url dispatcher passes the request to the view. View is responsible for the processing of the request. As we know django follows the MVT architecture.<br />
<br />
M - model<br />
V - view<br />
T - template<br />
<br />
<ol style="text-align: left;">
<li><b>Model'</b>s allow us to connect with the databases for information.</li>
<li><b>View</b> takes the advantage of django models to get the information from the database[using queries] and processes it. We write business logic in views.<br />We process the data in views and passes it to the template for showing processed data to the user.</li>
<li><b>Template </b>takes the processed data from the view and represent the data in a required formats like html, xml, json, etc.</li>
</ol>
<br />
We have discussed the theory part. Let's start the coding.<br />
<ul style="text-align: left;">
</ul>
<b>library_management/urls.py</b><br />
<ul style="text-align: left;">
</ul>
</div>
<pre class="brush: py">from django.conf.urls import url, include
urlpatterns = [
....
url(r'^', include('library.urls')),
....
]
</pre>
This is the root urls file of our application. <b>'include' </b>will add the app(library) urls. Based on the regular expression pattern users request will be served.<br />
<br />
<b>library/urls.py</b><br />
<pre class="brush: py">from django.conf.urls import url
from library import views
urlpatterns = [
url(r'^$', views.home, name="home"),
]
</pre>
<b>library/views.py</b><br />
<pre class="brush: py">from django.shortcuts import render
def home(request):
return render(request, 'home.html', {'say_hello': 'Hello World'})
</pre>
<b>templates/home.html</b><br />
<pre><!DOCTYPE html>
<html> <head>
<title> Library Management </title> </head>
<body>
<h1> {{ say_hello }}</h1>
</body>
</html>
</pre>
We have imported 'views' module from the library app and mapped it to url. Whenever we request the url <span style="color: purple;"><span style="background-color: white;">http://localhost:8000</span></span> in the browser it will the passed to the function <span style="color: purple;"><span style="background-color: white;">home</span></span>.<br />
If we observe <span style="background-color: #999999;"><span style="background-color: white;"><span style="color: purple;">library/views.py</span> </span></span>we have imported the <span style="background-color: #999999;"><span style="background-color: white;"><span style="color: purple;">render</span> from the django shortcuts module. <span style="color: purple;">render</span> takes request, template name(path from template directories) and context data(the dictionary) and renders the template with context data and returns the <span style="color: purple;">http response. <span style="color: black;">Browser receives the response and displays it to the user.</span></span></span></span><br />
<span style="background-color: #999999;"><span style="background-color: white;"><span style="color: purple;"><span style="color: black;"><span style="color: purple;">{{ say_hello }} </span> replaces with <span style="color: purple;">Hello World. <span style="color: black;">Context is a dictionary with keys and values. <span style="color: purple;">say_hello</span> is a key in the context so it will replaced by it's value.<br />It's just like string formatting in python.</span></span></span></span></span></span>
</div>
</div>
Anjaneyulu Battahttp://www.blogger.com/profile/04466094850374273896noreply@blogger.com0tag:blogger.com,1999:blog-4434479834026477776.post-27298266540911018952017-03-26T17:46:00.001+05:302017-03-26T17:46:36.542+05:30django models and database schema design<div dir="ltr" style="text-align: left;" trbidi="on">
<div>
<div>
Before we start the design our <i>database schema</i>, we have to <a href="http://django-easy-tutorial.blogspot.in/2017/03/django-first-application.html" target="_blank">create our django project</a>. Our project is "Library Management"(For quicker understanding).<br />
<br />
Before we start development of any software project, we should know about basics of software development life cycle.<br />
We have six steps in every software development life cycle.<br />
<div class="_yXc">
<ul class="_kYe">
<li class="_AXc">Requirement gathering and analysis.</li>
<li class="_AXc">Design(users flow, data flow & database schema design, etc).</li>
<li class="_AXc">Implementation or coding.</li>
<li class="_AXc">Testing.</li>
<li class="_AXc">Deployment.</li>
<li class="_AXc">Maintenance.</li>
</ul>
</div>
We are not going deep into the above steps. But, We will discuss about the requirements for our project "Library Management".<br />
<span style="color: #6fa8dc;"><br /></span>
<span style="color: #6fa8dc;">Library Management allows user to register & login into the system. User can search for book with details (name, author, etc.) and can see details of book(availability, author, etc). User can request the Admin(Library staff) for book. Admin will see the request of user and will approve/reject the book and dispatch it to the users address. After approving the book user will receive it and later he will return it within the due date. After receiving the book from the user Admin will mark it as received.</span><br />
<br />
Based on the above requirement we can derive the user flow & admin flow like below diagrams. <br />
<br />
<b>User's flow:</b><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEipPqLjpj8Zb9SxRTW_NsiNz6yi1AbpAehTiG_Cb-dRffOxTSKrrpnfklCAVbNn9Cwra7Gz-Je0c-4OlIJlHW3H6otYXu0S8xlFD1KXRfHoMH1y7f3jhh4vf-RtZ52BwfSjp1-FSl1bbBB9/s1600/library-user-flow-diagram.png" imageanchor="1"><img alt="library management user flow diagram" border="0" height="297" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEipPqLjpj8Zb9SxRTW_NsiNz6yi1AbpAehTiG_Cb-dRffOxTSKrrpnfklCAVbNn9Cwra7Gz-Je0c-4OlIJlHW3H6otYXu0S8xlFD1KXRfHoMH1y7f3jhh4vf-RtZ52BwfSjp1-FSl1bbBB9/s400/library-user-flow-diagram.png" title="library management user flow diagram" width="400" /></a></div>
<b>Admin/staff Flow:</b><br />
<b><br /></b>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiW6JUjfDhUP2k5Xhh4HEsvLEIKp8sID2SYLpkBbNYgGU7v68NqpvKMHBQR0JPjW2oI0jd13g3nFo89FSnIAj5-6qtZ9gkdZ4uxQYJ60KoJoiYXSOwHz-oZRpWJsF0CfAWl532MSS2WfXVO/s1600/library-admin-flow.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img alt="library management admin flow diagram" border="0" height="290" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiW6JUjfDhUP2k5Xhh4HEsvLEIKp8sID2SYLpkBbNYgGU7v68NqpvKMHBQR0JPjW2oI0jd13g3nFo89FSnIAj5-6qtZ9gkdZ4uxQYJ60KoJoiYXSOwHz-oZRpWJsF0CfAWl532MSS2WfXVO/s400/library-admin-flow.png" title="library management admin flow diagram" width="400" /></a></div>
<div class="separator" style="clear: both; text-align: center;">
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
From the above user-flow diagrams we can observe that we have to store the following details<br />
1. User profile<br />
2. Books Information<br />
3. Book register(who has taken book, when returned, due date etc.)<br />
<br />
Question yourself what to store and why so that you will understand the usage of fields in models & use appropriate names for models.<br />
<b>1. User Profile:</b><br />
<ul style="text-align: left;">
<li>first name, last name, email, is staff(to distinguish users admin, user), profile picture, address</li>
</ul>
<b>2. Book Information:</b><br />
<ul style="text-align: left;">
<li>title, author, description, image, available books(number)</li>
</ul>
</div>
<b>3. Book register:</b><br />
<ul style="text-align: left;">
<li>user(who taken book), book(which book), took on(date), returned on (date), due date</li>
</ul>
Following diagram shows the entity relationship model for our project. we have chose the data type based on the data.</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjO2mq2hiJOg3k3d8xGw2hBDW0EcCRponXf_zDK5-fI-Hv_uLcO1FogIIIruXCfwY_KeFh31H0VbktgSPIDvDjEauGO6roOBLDV-mjKboAg4eSlwJ7VsmlRQNFSpE_F1Hri5zn1d8OxAwPd/s1600/library-management-schema.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img alt="database schema for library management django" border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjO2mq2hiJOg3k3d8xGw2hBDW0EcCRponXf_zDK5-fI-Hv_uLcO1FogIIIruXCfwY_KeFh31H0VbktgSPIDvDjEauGO6roOBLDV-mjKboAg4eSlwJ7VsmlRQNFSpE_F1Hri5zn1d8OxAwPd/s1600/library-management-schema.png" title="database schema for library management django" /></a></div>
<div>
we have designed our <i><b>database model</b></i>. Our next step is to implement it in our django project. Django is providing us <b>"<a href="https://github.com/django/django/blob/master/django/contrib/auth/models.py#L292" rel="nofollow" target="_blank">User</a>"</b> model with basic fields (first_name, last_name, email, is_staff, is_active, username, is_superuser). But we need to add extra fields like address and profile picture.</div>
<div>
So, we have to customize the user model. In order to do that we have to configure the <b>settings.py</b><br />
<pre class="brush: py">AUTH_USER_MODEL = "library.User"</pre>
Now we are ready to write models, open the file <b>"library/models.py"</b> and write models init.<br />
<br /></div>
<pre class="brush: py">from django.db import models
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
profile_pic = models.ImageField(null=True)
address = models.TextField(null=True)
def __str__(self):
return self.email
def get_upload_file_name(book_object, file_name):
return "%s/%s/%s" % ("Book", book_object.id, file_name)
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=100)
description = models.TextField()
image = models.ImageField(upload_to=get_upload_file_name)
available = models.IntegerField(default=0)
ISBN = models.CharField(max_length=50)
def __str__(self):
return self.title
class BookRecord(models.Model):
user = models.ForeignKey(User)
book = models.ForeignKey(Book)
took_on = models.DateTimeField(auto_now_add=True)
returned_on = models.DateTimeField(null=True)
due_date = models.DateField()
def __str__(self):
return str(self.user)
</pre>
Now, follow the below steps to create database<br />
<pre class="brush: py">python manage.py makemigrations</pre>
This command will create the migration files in the <b>"library/migrations" </b>directory.<br />
<pre class="brush: py">python manage.py migrate</pre>
This command will run the migrations on <i>django orm</i> and creates the database.<br />
Now, our database is successfully created and ready to use it.<br /><br />Django provides defiirent kinds of model fields like "CharField", "IntegerField", "Foreign Key", "ManytoMany", "Decimal Field", etc.<br />
Based on the type of data that we are storing in the attribute we have to choose the fields.<br />In User model, for attribute profile pic I have chosen the "ImageField" because user will upload the image.<br />In BookRecord model, I have used "ForeignKey" field for attribute user because I'm making the relation between User table to BookRecord table.<br />
Like this we have many other fields we have to choose the fields for models attributes based on the storage data. Read the <a href="https://docs.djangoproject.com/en/1.10/ref/models/fields/" rel="nofollow" target="_blank">django official documentation on model fields.</a> Still if you don't understand please comment below, so that I can clarify your doubts.</div>
Anjaneyulu Battahttp://www.blogger.com/profile/04466094850374273896noreply@blogger.com0tag:blogger.com,1999:blog-4434479834026477776.post-34877642771421746922017-03-23T21:02:00.000+05:302017-03-23T23:51:23.688+05:30django templates and static files<div dir="ltr" style="text-align: left;" trbidi="on">
<br />
<table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"><tbody>
<tr><td style="text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjURAZOnH9I-hPveP5E8QlEQrsqu5p0jD56_xI1hID80Isv9B9ZQvPKxaYO4HcONAf8bDdU3L1pJIokXQpr4ncJGK4w7-C-TPfvCblv21K-Pkb8ExvDofT0Bg31dg_lmTyeIRkb4lH-SqYr/s1600/django-templates-and-static-files.png" imageanchor="1" style="margin-left: auto; margin-right: auto;"><img alt="django templates and static files settings" border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjURAZOnH9I-hPveP5E8QlEQrsqu5p0jD56_xI1hID80Isv9B9ZQvPKxaYO4HcONAf8bDdU3L1pJIokXQpr4ncJGK4w7-C-TPfvCblv21K-Pkb8ExvDofT0Bg31dg_lmTyeIRkb4lH-SqYr/s1600/django-templates-and-static-files.png" title="django templates and static files settings" /></a></td></tr>
<tr><td class="tr-caption" style="text-align: center;">Django template configurations</td></tr>
</tbody></table>
<h2 style="text-align: left;">
Django templates:</h2>
<div style="text-align: left;">
Django templates are just HTML files. Django creates <u><b>HttpResponse</b></u> for a request by rendering the given template(HTML file) with given context data. </div>
<div style="text-align: left;">
<br /></div>
<div style="text-align: left;">
Django supports different types of template engines like <u><b>JINJA, GENSHI, MAKO</b></u> etc., Django also have it's own template engines. Template engines are configured with "<u><b>TEMPLATES</b></u>" setting. It contains a list of template engines. Each template engine settings are defined in dictionary like below.<br />
<pre class="brush: py">TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ["templates"],
'APP_DIRS': True,
'OPTIONS': {
# ... some options here ...
},
},
]
</pre>
We can observe in above configuration is that it contains a template engine(dictionary of settings) inside a list.<br />
<div style="text-align: left;">
<b>BACKEND:</b></div>
<div style="text-align: left;">
It is a python path to a template engine class. It is used for rendering the templates.</div>
<div style="text-align: left;">
Django has two built-in template engines.</div>
<ol style="text-align: left;">
<li><b>django.template.backends.django.DjangoTemplates </b></li>
<b>
</b>
<li><b>django.template.backends.jinja2.Jinja2</b></li>
</ol>
<div style="text-align: left;">
Both backends works fine, but they differ in template language syntax. </div>
<div style="text-align: left;">
<b>DIRS:</b></div>
<div style="text-align: left;">
We provide "template path<b>" </b>to template engine. It will search for template with given path in directories (APP_DIRS, DIRS). It considers the apps from <b>"INSTALLED_APPS"</b> configuration.</div>
<div style="text-align: left;">
<b>APP_DIRS:</b></div>
<div style="text-align: left;">
By default it is set to <b>"True".</b> This allow template engine to look for template in applications template directories.</div>
<div style="text-align: left;">
<b>
OPTIONS: </b></div>
<div style="text-align: left;">
It allows us to define options like <b><a href="https://docs.djangoproject.com/en/1.10/ref/templates/upgrading/" rel="nofollow" target="_blank">template context processors, template loaders</a>.</b></div>
<div style="text-align: left;">
<b><br /></b></div>
<h2 style="text-align: left;">
<b>Django static files:</b></h2>
<div style="text-align: left;">
Static files, the term <b>"static" </b>itself tells that they do not change with time.</div>
<div style="text-align: left;">
Usually static files includes <b>javascript, css, images, </b>etc.<br />
Configuration for static files</div>
<ol>
<li>
Make sure that <b><code class="docutils literal"><span class="pre">django.contrib.staticfiles</span></code></b> is included in your <a class="reference internal" href="https://docs.djangoproject.com/en/1.10/ref/settings/#std:setting-INSTALLED_APPS" rel="nofollow" target="_blank"><code class="xref std std-setting docutils literal">INSTALLED_APPS</code></a></li>
<li><code class="xref std std-setting docutils literal"></code>Define <b>STATIC_URL = '/static/' </b>in settings.py file.</li>
<li>By default <i><u><b>django</b></u><b> </b></i>finds the static files in <b>"static"</b> directory under apps or in root directory. If you want to specify other directories as <b>"static"</b> you should add below configurations to settings.py file</li>
</ol>
<pre class="brush: py">STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]</pre>
<h2 style="text-align: left;">
Serving static files during development</h2>
<div style="text-align: left;">
Add the below code in root urls.py</div>
<pre class="brush:py">from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
]
urlpatterns += static(
settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT
)
</pre>
<h2>
Serving files uploaded by a user during development</h2>
<div style="text-align: left;">
Add the below code in root urls.py </div>
<pre class="brush: py">from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
]
urlpatterns += static(
settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT
)
</pre>
</div>
</div>
Anjaneyulu Battahttp://www.blogger.com/profile/04466094850374273896noreply@blogger.com0tag:blogger.com,1999:blog-4434479834026477776.post-24759769427236766742017-03-19T10:54:00.000+05:302017-04-01T19:17:28.515+05:30django project layout and settings<div dir="ltr" style="text-align: left;" trbidi="on">
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj0HTqxNAH3MF4RUVdOqWh1MLgHu4ejL_h7Ox4TvI6yjoXWslWNP2fpFpfG47FWqmYeE6GLapvHNHsp8YWWAfxuLGQikaKHyDIEPUPqLg4BCYygvp730uhiIEY0lZ_TrmLIllqkmDL1Li7w/s1600/django-project-structure.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj0HTqxNAH3MF4RUVdOqWh1MLgHu4ejL_h7Ox4TvI6yjoXWslWNP2fpFpfG47FWqmYeE6GLapvHNHsp8YWWAfxuLGQikaKHyDIEPUPqLg4BCYygvp730uhiIEY0lZ_TrmLIllqkmDL1Li7w/s1600/django-project-structure.png" /></a></div>
<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
Let's talk about "Django" project structure in depth. You can see the complete project layout in above image.<br />
<br />
<u><b>base/project/:</b></u><b> </b>It is a container for our project. we can give any name to this directory and we can modify it at any time.<br />
<u><b><u><b><u><b>project</b></u>/</b></u>manage.py:</b></u><b> </b>It is created for all django projects. It is a command-line utility, it is used to interact with the "django" project in many ways.<br />
We use below command to run development server<br />
<pre class="brush: py">python manage.py runserver
</pre>
"runserver" is a command which is used to run the server.<br />
To show all available commands run the below command<br />
<pre class="brush: py">python manage.py</pre>
<u><b>project/project:</b></u> This directory contains the project files.<u><b></b></u><br />
<u><b><u><b>project/project</b></u>/__init__.py:</b></u> It is a empty file that tells python to consider the directory as a <a href="https://docs.python.org/3/tutorial/modules.html#tut-packages" rel="nofollow" target="_blank">package.</a><br />
<u><b><u><b>project/project</b></u>/settings.py:</b></u> It contains all configuration settings like database settings, installed apps, root url conf etc.<br />
<u><b><u><b>project/project</b></u>/urls.py:</b></u> It is the root url file. It contains url patterns to map the request to the respective view to process it.<br />
<u><b><u><b>project/project</b></u>/uwsgi.py:</b></u> An entry-point for WSGI-compatible web servers to
serve our project.<br />
<u><b><u><b>project/static:</b></u></b></u> It contains the static assets like css, javascript, images, etc.<br />
<u><b><u><b>project/templates:</b></u></b></u> It contains the html files that will be used to create http response to a request.<br />
<u><b><u><b>project/media:</b></u></b></u> It is a path to store the media contents like files that are uploaded by users.<br />
To get project structure that is shown in above image. we need to update <b>settings.py </b>file with below code.<br />
<br />
<pre class="brush: py">import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
MEDIA_ROOT = os.path.join(BASE_DIR + '/media/')
MEDIA_URL = '/media/'
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, "static"), ]
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ["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',
],
},
},
]
</pre>
To know more about customizing settings visit: <a href="https://docs.djangoproject.com/en/1.10/ref/settings/" rel="nofollow" target="_blank">https://docs.djangoproject.com/en/1.10/ref/settings/</a><br />
<u><b><u><b><u><b>project/</b></u></b></u>app1:</b></u> It is a python package, It contains application related files.<br />
<b><u><b><u><b>project/app1/templatetags:</b></u></b></u><b><b> </b></b></b>It's a directory that contains template tags of our application. Template tags helps us at the time of rendering the template. It takes the context from the template and processes it and again return it to the template. <br />
<b><u><b><u><b>project/app1/templatetags/__init__.py:</b></u></b></u></b> It's empty python file, it tells python to recognize the directory as a python package.<br />
<b><u><b><u><b><b><u><b><u><b>project/app1/templatetags/tags.py:</b></u></b></u></b></b></u></b></u><b><b> </b></b></b>It's a python file, it contains the custom template tags that we will use it in templates.<br />
<b><u><b><u><b><b><u><b><u><b>project/app1/apps.py:</b></u></b></u></b></b></u></b></u></b> It contains the application's configuration.<br />
<b><u><b><u><b><b><u><b><u><b><b><u><b><u><b>project/app1/models.py:</b></u></b></u></b></b></u></b></u></b></b></u></b></u></b> It contains the models(db tables) of application. we represent our database tables with the model in django. ORM(Object Relation Mapper) converts the models to db tables. We do not use raw SQL(Structured Query Language) to query the database, instead we use django queries. ORM convert these queries into SQL equivalent code and performs the db query and again converts the relational data to python objects to make things easier.<br />
<b><b><u><b><u><b>project/app1/migrations:</b></u></b></u><b><b> </b></b></b></b>It contains the database migrations of application, each migration contains the database schema related code.<br />
<b><b><u><b><u><b><b><b><u><b><u><b>project/app1/migrations/__init__.py:</b></u></b></u></b></b></b></u></b></u></b></b> It's empty python file, it tells python to recognize the directory as a python package.<br />
<b><b><u><b><u><b><b><b><u><b><u><b><b><b><u><b><u><b><b><b><u><b><u><b>project/app1/migrations/001_initial.py:</b></u></b></u></b></b></b></u></b></u></b></b></b></u></b></u></b></b></b></u></b></u></b></b> It's a migration file of application. It contains the database schema related code, that is used to create database schema.<br />
<b><u><b><u><b>project/app1/__init__.py:</b></u></b></u></b> It's a python file, it tells python to recognize the directory as a python package.<br />
<b><u><b><u><b>project/app1/admin.py:</b></u></b></u></b> Django provides the inbuilt admin panel.<b><b><b> </b></b></b>This file contains the admin related code. <br />
<b><u><b><u><b><b><u><b><u><b>project/app1/urls.py:</b></u></b></u></b></b></u></b></u></b> It contains url's that are related to the application.<br />
<b><u><b><u><b><b><u><b><u><b>project/app1/views.py:</b></u></b></u></b></b></u></b></u></b> It contains the views(functions/classes) that are mapped from the url's to process the request.<b><u><b><u><b> </b></u></b></u></b><br />
<b><u><b><u><b>project/app1/tests.py:</b></u></b></u></b> It contains the unit tests of the application.<b><u><b><u><b><br /></b></u></b></u></b></div>
Anjaneyulu Battahttp://www.blogger.com/profile/04466094850374273896noreply@blogger.com0tag:blogger.com,1999:blog-4434479834026477776.post-40641095588811321972017-03-18T07:14:00.000+05:302017-03-26T08:51:48.586+05:30django first application<div dir="ltr" style="text-align: left;" trbidi="on">
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEil2_idBpgaQgWNTCqT6NDr-A61uRZwAMUcMOjTKo_uCYzs0aEbY5GPeTm_AAzWsnzH9XVe58Ltc9H3bbPJq0saRRcWY-7J235nLgYwXlaSHOF9_CUwRe6w8tyIIGJiFT_45w84X9fYBC_a/s1600/django-hello-world.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="250" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEil2_idBpgaQgWNTCqT6NDr-A61uRZwAMUcMOjTKo_uCYzs0aEbY5GPeTm_AAzWsnzH9XVe58Ltc9H3bbPJq0saRRcWY-7J235nLgYwXlaSHOF9_CUwRe6w8tyIIGJiFT_45w84X9fYBC_a/s400/django-hello-world.png" width="400" /></a></div>
<div style="text-align: left;">
Let's start our <b>Django</b> application from the beginning. To start our first application we have to follow the below steps. Before going to start our project learn about <a href="http://django-easy-tutorial.blogspot.in/2017/03/django-project-layout-and-settings.html" target="_blank">django project layout</a>.</div>
<div style="text-align: left;">
<br /></div>
<ol style="text-align: left;">
<li>
Create a directory with your project name & change your directory to the project. Lets consider our project as "Library Management"</li>
<pre class="brush: py" style="text-align: left;">mkdir Library && cd Library
</pre>
<li>Now, create <a href="https://django-easy-tutorial.blogspot.in/2015/08/python-virtual-environment-setup-in-ubuntu.html" target="_blank">virtual environment</a> for our project.</li>
<pre class="brush: py" style="text-align: left;">virtualenv env
source env/bin/activate
</pre>
virtual environment is now ready to use.
<li>Install <i>Django</i> package in environment.</li>
<pre class="brush: py" style="text-align: left;">pip install django
</pre>
<li>Start our project Library Management</li>
<pre class="brush: py" style="text-align: left;">django-admin startproject library_management
</pre>
After executing the above commands a new folder "library_management" will be created. Inside that folder you can see another folder "library_management" and a file "manage.py".
Inside "library_management/library_management" folder you can find below files
<div style="background: #000; color: white; text-align: left;">
<b> __init__.py settings.py urls.py wsgi.py</b></div>
<li>Run the below command to test our project setup.</li>
<pre class="brush: py">python manage.py runserver
</pre>
Open your browser and hit the url <b>http://127.0.0.1:8000/</b>. You can see the below output.
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi5pKuUgkTGnUtQwE07c2Z6CpeTXSS3elye6ovWkldOZxbjBdkchiJSakmvUGX-JmRidbBaVmBCUzPbTxBZbs2CeNB6C3tVEgID36tk00ozvNxQJXjV9i1q6iAF1psaqkqZrdM_quL17VeJ/s1600/django_default.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="131" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi5pKuUgkTGnUtQwE07c2Z6CpeTXSS3elye6ovWkldOZxbjBdkchiJSakmvUGX-JmRidbBaVmBCUzPbTxBZbs2CeNB6C3tVEgID36tk00ozvNxQJXjV9i1q6iAF1psaqkqZrdM_quL17VeJ/s640/django_default.png" width="640" /></a></div>
We have successfully setup our first <b>django</b> project.<br /> <small>If you do not see the above output, you might have missed something. so, delete everything that you did and start from the beginning again to save our time. As we are beginners we don't know much to resolve errors.</small>
<li> Now create an application <b>"library"</b> to show <u>"hello world"</u> as response in browser</li>
<pre class="brush: py">python manage.py startapp library
</pre>
After executing the above command in the directory you can observe that a folder with name "library" have created and a file "db.sqlite3" also.
If you look inside of folder "library" you can find the following files.
<div style="background: #000; color: white; text-align: left;">
<b>admin.py apps.py __init__.py <span style="color: blue;">migrations</span> models.py tests.py views.py</b></div>
<li><b style="color: blue;">"db.sqlite3"</b> is file database developed in python. It is best suitable for beginners. we can also use <i>MySQL</i> and <i>Postgres</i> databases. <b style="color: blue;">"library"</b> is our application with its files in it.</li>
<li>Now, open <b>"library_management/urls.py"</b> and replace the contents of file with below code.</li>
<pre class="brush: py">from django.conf.urls import url
from django.contrib import admin
from library import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^hello-world/$', views.hello_world),
]
</pre>
<li>And open <b>"library/views.py"</b> file and replace file contents with below code</li>
<pre class="brush: py">from django.http import HttpResponse
def hello_world(request):
html_source_code = """
<html>
<title> Hello World</title>
<body>
<h1> Hello World</h1>
</body>
</html>
"""
return HttpResponse(html_source_code) </pre>
<li>Open your web-browser and access url <b>"http://127.0.0.1:8000/hello-world/". </b>You can find <i><b>"Hello World" </b></i>as response.</li>
</ol>
Now we have successfully created <b>"hello world"</b> application. In the next post I will explain project, application and modules inside of it. Because it will become more lengthy if I explain it here.
</div>
Anjaneyulu Battahttp://www.blogger.com/profile/04466094850374273896noreply@blogger.com0tag:blogger.com,1999:blog-4434479834026477776.post-77419324483253939742017-03-15T23:45:00.000+05:302017-03-15T23:45:43.628+05:30django request lifecycle<div dir="ltr" style="text-align: left;" trbidi="on">
<div dir="ltr" style="text-align: left;" trbidi="on">
<table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"><tbody>
<tr><td style="text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgw1aOfuCfdsQKL0a3iMNnv9RjkFmroYaNcxbNQCHf5CpGu4liOQU8lEsOI7DNXUYAkQlMNURG7sAEDHy6yM8THPkna85ccVgoiustAPznWzS1Y0DikFDRMmNmW7LjM2uGPkoyEuyo7p9zR/s1600/django-request-life-cycle.png" imageanchor="1" style="margin-left: auto; margin-right: auto;"><img alt="Django Request Lifecycle" border="0" height="538" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgw1aOfuCfdsQKL0a3iMNnv9RjkFmroYaNcxbNQCHf5CpGu4liOQU8lEsOI7DNXUYAkQlMNURG7sAEDHy6yM8THPkna85ccVgoiustAPznWzS1Y0DikFDRMmNmW7LjM2uGPkoyEuyo7p9zR/s640/django-request-life-cycle.png" title="Django Request Lifecycle" width="640" /></a></td></tr>
<tr><td class="tr-caption" style="text-align: center;">Architecture for django application</td></tr>
</tbody></table>
We can divide the request <b>life cycle</b> of the django application into three layers.<br />
1. Browser<br />
2. Server<br />
3. Django<br />
<br />
<h2 style="text-align: left;">
1.Browser:</h2>
<div style="text-align: left;">
Browser(client) is responsible for sending data to the server and also responsible for receiving the response back. </div>
<h2 style="text-align: left;">
2. Server:</h2>
<ul style="text-align: left;">
<li>It receives the request from the browser, based on the request it gives response back. If we take an example of NGINX server. It can handle the 10,000 requests in a second based on the resources of the server(RAM, Processor). </li>
<li>If it receives more than 10,000 requests in a second it creates another process to handle it. </li>
<li>We can divide request resources in two types. <i><b> </b></i></li>
<li><i><b>1. static resource</b></i> </li>
<li><b><i>2.</i> <i>dynamic resource</i></b>(It has to process the data based on request to provide resource) </li>
</ul>
</div>
<ul style="text-align: left;">
<li>If browser request for the static resources like images/css/javascript/etc, then NGINX serves the request without sending it to the uWSGI server.</li>
<li>If browser requests for a dynamic request then NGINX passes it to the uWSGI to process the request. </li>
<li>At this stage NGINX acts like a reverse proxy server. A reverse proxy server is a type of proxy server that typically sits behind the firewall in a private network and directs browser/client requests to the appropriate back-end
server(uWSGI).</li>
<li>Advantages of reverse proxy server are Load balancing, Web acceleration, Security and anonymity.</li>
</ul>
<h2 style="text-align: left;">
3. Django</h2>
<ul style="text-align: left;">
<li>Django layer comes into the picture when request passed from nGINX to the uWSGI it takes the <b><a href="https://docs.djangoproject.com/en/1.10/ref/request-response/" rel="nofollow" target="_blank">request</a> <a href="https://docs.djangoproject.com/en/1.10/topics/http/middleware/" rel="nofollow" target="_blank">middlewares</a></b> from the settings and applies on the request to modify request.</li>
<li>After applying the request middlewares it sends the request to url dispatcher. Url dispatcher is responsible for dispatching the request to a view based on the url pattern</li>
<li>Here we implement the business logic. We access the database resources by writing Django Queries.</li>
<li>The query passes to the ORM(Object Relation Mapper). ORM converts the <b>django</b> query into SQL(Structured Query Language) query and hits the database (MySQL/Postgres,etc). Database returns the query results in a relational table. ORM again converts these relational data into django queryset and returns back to the view.</li>
<li>View passes the context(data that's retrieved from the database) to the template.</li>
<li>Template renders the content with context data and forms the Response(HTML/XML/JSON/etc.) </li>
<li>Again <b><a href="https://docs.djangoproject.com/en/1.10/ref/request-response/" rel="nofollow" target="_blank">response</a> <a href="https://docs.djangoproject.com/en/1.10/topics/http/middleware/" rel="nofollow" target="_blank">middlewares</a></b> which are defined in settings will apply and modifies the request and sends the response to the Browser(Client).</li>
</ul>
</div>
Anjaneyulu Battahttp://www.blogger.com/profile/04466094850374273896noreply@blogger.com0tag:blogger.com,1999:blog-4434479834026477776.post-23875480310060560302017-03-12T23:00:00.000+05:302017-03-12T23:10:36.728+05:30Python Web Development with Django<div dir="ltr" style="text-align: left;" trbidi="on">
<table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"><tbody>
<tr><td style="text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg9r1yU1udhjQDyNvf4Ri2xGw00TmRl6ZxjjEODFX7MZYyB32LlenLZCAwgivL1f0fkHRuvJLbfUp70OpFevq7wEqDOA47GhBLU0tazV2vCyXg2UOw_67R9n57sCnt5fOdpBis0K7snJtLa/s1600/python-web-development-django.png" imageanchor="1" style="margin-left: auto; margin-right: auto;"><img alt="Django web framework" border="0" height="400" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg9r1yU1udhjQDyNvf4Ri2xGw00TmRl6ZxjjEODFX7MZYyB32LlenLZCAwgivL1f0fkHRuvJLbfUp70OpFevq7wEqDOA47GhBLU0tazV2vCyXg2UOw_67R9n57sCnt5fOdpBis0K7snJtLa/s640/python-web-development-django.png" title="Python Web Development with Django" width="640" /></a></td></tr>
<tr><td class="tr-caption" style="text-align: center;">Python Web Development with Django</td></tr>
</tbody></table>
<h2 style="text-align: left;">
Why python?</h2>
<ul style="text-align: left;">
<li>Python is a a <a href="https://en.wikipedia.org/wiki/Free_and_open-source_software" rel="nofollow" title="Free and open-source software">free and open-source</a> programming language.</li>
<li>It supports both functional and object oriented programming</li>
<li>It is well suited for <a href="https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller" rel="nofollow" target="_blank">MVC</a> development</li>
<li>It has extensive documentation.</li>
<li>It has wide range of community support.</li>
<li>It has large standard library of modules</li>
<li>It supports wide range of web-servers.</li>
<li>It has clean and elegant syntax</li>
</ul>
<h2 style="text-align: left;">
Why <i><b>django</b></i> ?</h2>
<div style="text-align: left;">
<ul style="text-align: left;">
<li><u><i>Django</i></u> web framework is a <a href="https://en.wikipedia.org/wiki/Free_and_open-source_software" rel="nofollow" title="Free and open-source software">free and open-source</a> <a href="https://en.wikipedia.org/wiki/Web_framework" rel="nofollow" title="Web framework">web framework </a>written in <a href="https://en.wikipedia.org/wiki/Python_(programming_language)" rel="nofollow" target="_blank">python</a> programming language.</li>
<li>It is used to develop <i>web-applications</i></li>
<li>It follows the model-view-template (MVT) architectural pattern.</li>
<li>Primary goal of django is to simplify the creation of comple, database-driven websites.</li>
<li>Django focuses on re-usability and "pluggability" of components, rapid development, and the principle of don't repeat yourself.</li>
</ul>
<h2>
Advantages</h2>
<ul style="text-align: left;">
<li>It encourages big, tightly-coupled apps.</li>
<li>It has <a href="https://en.wikipedia.org/wiki/Object-relational_mapping" rel="nofollow" target="_blank">Object Relational Mapper(ORM)</a></li>
<li>It has clean URL design</li>
<li>It has Multi lingual support</li>
<li>It has both Template and Text filtering Engine</li>
<li>Form generation and validation API</li>
<li>An extensible authorization system</li>
<li>A caching system for speeding up performance of applications </li>
<li>A feed framework for generating RSS feeds</li>
</ul>
<h2>
Disadvantages</h2>
<ul>
<li>Not the best for small projects</li>
</ul>
<h2 style="text-align: left;">
List of websites developed with Django </h2>
<ol style="text-align: left;">
<li><span style="color: black;"><a class="outbound-link" href="https://www.pinterest.com/" rel="nofollow" target="_blank">Pinterest</a></span></li>
<li><span style="color: black;"><a class="outbound-link" href="http://www.theonion.com/" rel="nofollow" target="_blank">The Onion</a></span></li>
<li><span style="color: black;"><a class="outbound-link" href="https://instagram.com/" rel="nofollow" target="_blank">Instagram</a></span></li>
<li><span style="color: black;"><a class="outbound-link" href="https://disqus.com/" rel="nofollow" target="_blank">Disqus</a></span></li>
<li><span style="color: black;"><a class="outbound-link" href="https://www.spotify.com/" rel="nofollow" target="_blank">Spotify</a></span></li>
<li><span style="color: black;"><a class="outbound-link" href="http://www.mahalo.com/" rel="nofollow" target="_blank">Mahalo</a></span></li>
<li><span style="color: black;"><a class="outbound-link" href="https://www.washingtonpost.com/" rel="nofollow" target="_blank">Washington Post</a></span></li>
<li><span style="color: black;"><a class="outbound-link" href="https://www.mozilla.org/en-US/firefox/new/" rel="nofollow" target="_blank">Firefox </a></span></li>
<li><span style="color: black;"><a class="outbound-link" href="https://www.nasa.gov/" rel="nofollow" target="_blank">NASA</a></span></li>
<li><span style="color: black;"><a class="outbound-link" href="https://bitbucket.org/" rel="nofollow" target="_blank">Bitbucket</a></span></li>
<li><span style="color: black;"><a class="outbound-link" href="http://pitchfork.com/" rel="nofollow" target="_blank">Pitchfork</a></span></li>
<li><span style="color: black;"><a class="outbound-link" href="https://www.eventbrite.com/" rel="nofollow" target="_blank">Eventbrite</a></span></li>
<li><span style="color: black;"><a class="outbound-link" href="https://www.playfire.com/" rel="nofollow" target="_blank">Playfire</a></span></li>
</ol>
</div>
<div style="text-align: left;">
For more information please visit: <a href="https://www.djangoproject.com/start/" rel="nofollow">https://www.djangoproject.com/start/</a></div>
</div>
Anjaneyulu Battahttp://www.blogger.com/profile/04466094850374273896noreply@blogger.com0tag:blogger.com,1999:blog-4434479834026477776.post-55917478585673615572017-03-12T10:32:00.000+05:302017-12-16T16:29:14.673+05:30Usage of "date" from datetime module with use cases - Python<div dir="ltr" style="text-align: left;" trbidi="on"><div><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjM3tsFumT4GatDLN6soqsQtZg8zZEiZVp8Ajy4R-JIHsrpRTY98hdQV0hrcc3GuoKCYhDDOpO2e48Rkh7Tce-uOA3P4TT7c9jNmrW9KRxw6wBFg42U8VLEkVnECeWIeB2W2h5JoXeJ74Sx/s1600/python-date.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="320" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjM3tsFumT4GatDLN6soqsQtZg8zZEiZVp8Ajy4R-JIHsrpRTY98hdQV0hrcc3GuoKCYhDDOpO2e48Rkh7Tce-uOA3P4TT7c9jNmrW9KRxw6wBFg42U8VLEkVnECeWIeB2W2h5JoXeJ74Sx/s320/python-date.png" width="284" /></a></div><ul style="text-align: left;"><li><span class="st" data-hveid="75" data-ved="0ahUKEwiho_rRg9DSAhUEG5QKHQcOCF0Q4EUISzAL"><i>Date</i> is a reference to a particular day represented within a <i>calendar</i> system.</span></li><li><span class="st" data-hveid="75" data-ved="0ahUKEwiho_rRg9DSAhUEG5QKHQcOCF0Q4EUISzAL">We use "<i>date</i>" class to represent a day in calendar in python</span></li><li><span class="st" data-hveid="75" data-ved="0ahUKEwiho_rRg9DSAhUEG5QKHQcOCF0Q4EUISzAL">We import date from "<i>datetime</i>" module </span></li></ul><h3 style="text-align: left;"><span class="st" data-hveid="75" data-ved="0ahUKEwiho_rRg9DSAhUEG5QKHQcOCF0Q4EUISzAL">How to represent <i>"date</i>" in python ?</span></h3><pre class="brush: py">from datetime import date<br />d = date(year=2017, month=4, day=3)<br />print(d)<br /># Output: 2017-04-03<br /></pre></div><div style="text-align: left;"><h3><span class="st" data-hveid="75" data-ved="0ahUKEwiho_rRg9DSAhUEG5QKHQcOCF0Q4EUISzAL">How to get current <i>date</i> in python ?</span></h3><pre class="brush: py">from datetime import date<br />d = date.today()<br />print(d)<br /># Output: we get today's date<br /></pre></div><div style="text-align: left;"><h3><span class="st" data-hveid="75" data-ved="0ahUKEwiho_rRg9DSAhUEG5QKHQcOCF0Q4EUISzAL">How get <i>year, month, day</i> from month ?</span></h3><pre class="brush: py">from datetime import date<br />d = date.today()<br />year = d.year<br />month = d.month<br />day = d.day<br />print("year = %s, month = %s, day = %s" % (year, month, day))<br /># Output: year = 2017, month = 3, day = 12<br /></pre></div><div style="text-align: left;"><h3><span class="st" data-hveid="75" data-ved="0ahUKEwiho_rRg9DSAhUEG5QKHQcOCF0Q4EUISzAL">How to replace year, month, day in date object and get new date object ?</span></h3><pre class="brush: py">from datetime import date<br />d = date(year=2017, month=4, day=3)<br /># replace year with 2015<br />old_date = d.replace(year=2015)<br />print(old_date)<br /># Output: 2015-04-03<br />print(d)<br /># Output: 2017-04-03<br /># in the same way we can replace month, day<br /></pre></div><div style="text-align: left;"><h3><span class="st" data-hveid="75" data-ved="0ahUKEwiho_rRg9DSAhUEG5QKHQcOCF0Q4EUISzAL">How to convert/parse <i>string</i> to <i>date</i> object python ?</span></h3>'2017-04-03' >>> "%Y-%m-%d" <br /><pre class="brush: py">from datetime import datetime<br />s = '2017-04-03'<br />date_object = datetime.strptime(s, "%Y-%m-%d").date()<br />print(date_object)<br /># Output: 2017-04-03<br /></pre>'Monday 03 April 2017' >>> "%A %d %B %Y" <br /><pre class="brush: py">from datetime import datetime<br />s = 'Monday 03 April 2017'<br />date_object = datetime.strptime(s, "%A %d %B %Y").date()<br />print(date_object)<br /># Output: 2017-04-03<br /></pre>'Mon 03 Apr 2017' >>> "%a %d %b %Y" <br /><pre class="brush: py">from datetime import datetime<br />s = 'Mon 03 Apr 2017'<br />date_object = datetime.strptime(s, "%a %d %b %Y").date()<br />print(date_object)<br /># Output: 2017-04-03<br /></pre></div><div style="text-align: left;"><h3><span class="st" data-hveid="75" data-ved="0ahUKEwiho_rRg9DSAhUEG5QKHQcOCF0Q4EUISzAL">How to parse date object to string format python?</span></h3><pre class="brush: py">from datetime import datetime<br />d = date(2017, 04, 03)<br />date_string = d.strftime("%Y-%m-%d")<br /># output: '2017-04-03'<br />date_string = d.strftime("%A %d %B %Y")<br /># output: 'Monday 03 April 2017'<br />date_string = d.strftime("%a %d %b %Y")<br /># output: 'Mon 03 Apr 2017'<br /></pre></div><div style="text-align: left;"><h3><span class="st" data-hveid="75" data-ved="0ahUKEwiho_rRg9DSAhUEG5QKHQcOCF0Q4EUISzAL">How to convert date object to "<i>datetime</i>" object ?</span></h3><pre class="brush: py">from datetime import datetime, date<br />d = date(2017, 04, 03)<br />datetime_object = datetime(d.year, d.month, d.day)<br />print(datetime_object)<br /># output: 2017-04-03 00:00:00<br />print(type(datetime_object))<br /># output: datetime.datetime<br /></pre></div><div style="text-align: left;"><h3><span class="st" data-hveid="75" data-ved="0ahUKEwiho_rRg9DSAhUEG5QKHQcOCF0Q4EUISzAL">How to compare two date objects ?</span></h3><pre class="brush: py">from datetime import date<br />date1 = date(2015, 12, 8)<br />date2 = date(2017, 11, 9)<br /># check if date1 > date2<br />is_date1_greater = date1 > date2<br />print(is_date1_greater)<br /># output: False<br />is_date1_greater = date2 > date1<br />print(is_date1_greater)<br /># output: True<br /></pre></div><div style="text-align: left;"><h3><span class="st" data-hveid="75" data-ved="0ahUKEwiho_rRg9DSAhUEG5QKHQcOCF0Q4EUISzAL">How to get number of days between two dates ?</span></h3><pre class="brush: py">from datetime import date<br />date1 = date(2015, 12, 8)<br />date2 = date(2017, 11, 9)<br />time_delta = date1 - date2<br />print("days = %s" % (time_delta.days))<br /># output: days = -702<br />time_delta = date2 - date1<br />print("days = %s" % (time_delta.days))<br /># output: days = 702<br /></pre></div><h3 style="text-align: left;">How to get week day from date object ?</h3>Return the day of the week represented by the date. Monday == 0, Tuesday == 1, ... , Sunday == 6 <br /><pre class="brush: py">from datetime import date<br />d = date(2015, 12, 8)<br />print(d.strftime("%A"))<br /># Output: Tuesday<br />day_of_week = d.weekday()<br />print(day_of_week)<br /># Output: 1<br /></pre><h3>How to get ISO week day from date object ?</h3>Return the day of the week represented by the date. Monday == 1, Tuesday == 2, ... , Sunday == 7 <br /><pre class="brush: py">from datetime import date<br />d = date(2015, 12, 8)<br />print(d.strftime("%A"))<br /># Output: Tuesday<br />day_of_week = d.isoweekday()<br />print(day_of_week)<br /># Output: 2<br /></pre><a href="https://docs.python.org/2/library/datetime.html" target="_blank">Reference:https://docs.python.org/2/library/datetime.html</a></div>Anjaneyulu Battahttp://www.blogger.com/profile/04466094850374273896noreply@blogger.com0tag:blogger.com,1999:blog-4434479834026477776.post-33950442656232448382017-03-11T08:57:00.000+05:302017-12-16T16:29:14.703+05:30Usage of "datetime" from datetime module with use cases - Python<div dir="ltr" style="text-align: left;" trbidi="on"><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgCS2G_qy_Pi2bFHXSNf7wd12aVMSu6z-FIdHmCRYBVPJa7LA0TiwdUA7Srrg__sHPvN8lZMr5Hbv_VnxYCRnwy4imI4xLqoatTSHl__HcTSKcCzCzV9jCKyHGILwc-NWMYv3oPGRjbQrW6/s1600/python-datetime.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="320" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgCS2G_qy_Pi2bFHXSNf7wd12aVMSu6z-FIdHmCRYBVPJa7LA0TiwdUA7Srrg__sHPvN8lZMr5Hbv_VnxYCRnwy4imI4xLqoatTSHl__HcTSKcCzCzV9jCKyHGILwc-NWMYv3oPGRjbQrW6/s320/python-datetime.png" width="310" /></a></div><ul style="text-align: left;"><li>datetime can be found in the module datetime. </li><li>datetime is a python's representation of date and time in a single object.</li></ul><h3 style="text-align: left;">how to create datetime object in python ? </h3><pre class="brush: py">from datetime import datetime<br />time_date = datetime(<br />year=2017, month=3, day=2, hour=14, minute=0, second=0, microsecond=0, tzinfo=None<br />)<br />print(type(time_date))<br /># Output: 'datetime.datetime'<br />print(time_date)<br /># Output: 2017-03-02 14:00:00<br /></pre><h3 style="text-align: left;">How to get date from datetime object ?</h3><pre class="brush: py">from datetime import datetime<br />time_date = datetime(<br />year=2017, month=3, day=2, hour=14, minute=0, second=0, microsecond=0, tzinfo=None<br />)<br />date = time_date.date()<br />print(type(date))<br /># Output: datetime.date<br />print(date)<br /># Output: 2017-03-02<br /></pre><h3 style="text-align: left;">How to get current datetime object in python ? </h3><pre class="brush: py">from datetime import datetime<br />current_datetime = datetime.now()<br />print(current_datetime)<br /># Output: 2017-03-07 21:31:59.720195 <br /></pre><h3 style="text-align: left;">How to get year, month, day, hour, minute, second in python?</h3><pre class="brush: py">from datetime import datetime<br />current_datetime = datetime.now()<br />year = current_datetime.year<br />month = current_datetime.month<br />day = current_datetime.day<br />hour = current_datetime.hour<br />minute = current_datetime.minute<br />second = current_datetime.second<br />microsecond = current_datetime.microsecond<br />print("year= %s, month=%s, day=%s, hour=%s, minute=%s, second=%s, microsecond=%s" % (year, month, day, hour, minute, second, microsecond))<br /># output: year= 2017, month=3, day=7, hour=21, minute=41, second=50, microsecond=781903<br /></pre><h3 style="text-align: left;">How to convert a datetime object to string with a specific format python(<i><u><span style="font-weight: normal;">datetime.strftime</span></u></i>)? </h3><b>"2017-02-04 12:02:33"</b><br /><pre class="brush:py">from datetime import datetime<br />date = datetime(2017, 2, 4, 12, 2, 33)<br />s = datetime.strftime(d, "%Y-%m-%d %H:%M:%S")<br />print(s)<br />#Output: '2017-02-04 12:02:33'<br /></pre><b>"2017/02/04 12:02:33"</b><br /><pre class="brush:py">from datetime import datetime<br />date = datetime(2017, 2, 4, 12, 2, 33)<br />s = datetime.strftime(d, "%Y/%m/%d %H:%M:%S")<br />print(s)<br />#Output: 2017/02/04 12:02:33<br /></pre><b>"04/02/2017 12:02:33"</b><br /><pre class="brush:py">from datetime import datetime<br />date = datetime(2017, 2, 4, 12, 2, 33)<br />s = datetime.strftime(date, "%d/%m/%Y %H:%M:%S")<br />print(s)<br /># Output: '04/02/2017 12:02:33'<br /></pre><b>"04 February 2017 12:02:33 PM"</b><br /><pre class="brush: py">from datetime import datetime<br />date = datetime(2017, 2, 4, 12, 2, 33)<br />s = datetime.strftime(date, "%d %B %Y %H:%M:%S %p")<br />print(s)<br /># Output: 04 February 2017 12:02:33 PM<br /></pre><b>"Saturday February 2017 12:02:33 PM"</b><br /><pre class="brush: py">from datetime import datetime<br />date = datetime(2017, 2, 4, 12, 2, 33)<br />s = datetime.strftime(date, "%A %B %Y %H:%M:%S %p")<br />print(s)<br /># Output: Saturday February 2017 12:02:33 PM<br /></pre><b>"Sat February 2017 12:02:33 pm"</b><br /><pre class="brush: py">from datetime import datetime<br />date = datetime(2017, 2, 4, 12, 2, 33)<br />s = datetime.strftime(date, "%a %B %Y %H:%M:%S %P")<br />print(s)<br /># Output: Sat February 2017 12:02:33 pm<br /></pre><h3 style="text-align: left;">How to convert a string to datetime object python(<u><i><span style="font-weight: normal;">datetime.strptime</span></i></u>)? </h3><b>"2017-02-04 12:02:33"</b><br /><pre class="brush: py">from datetime import datetime<br />s = "2017-02-04 12:02:33"<br />d = datetime.strptime(s, "%Y-%m-%d %H:%M:%S")<br />print(d)<br /># Output: datetime.datetime(2017, 2, 4, 12, 2, 33)<br /></pre><b>"2017/02/04 12:02:33"</b><br /><pre class="brush: py">from datetime import datetime<br />s = "2017/02/04 12:02:33"<br />d = datetime.strptime(s, "%Y/%m/%d %H:%M:%S")<br />print(d)<br /># Output: datetime.datetime(2017, 2, 4, 12, 2, 33)<br /></pre><b>"04/02/2017 12:02:33"</b><br /><pre class="brush: py">from datetime import datetime<br />s = "04/02/2017 12:02:33"<br />d = datetime.strptime(s, "%d/%m/%Y %H:%M:%S")<br />print(d)<br /># Output: datetime.datetime(2017, 2, 4, 12, 2, 33)<br /></pre><b>"04 February 2017 12:02:33 PM"</b><br /><pre class="brush: py">from datetime import datetime<br />s = "04 February 2017 12:02:33 PM"<br />d = datetime.strptime(s, "%d %B %Y %H:%M:%S %p")<br />print(d)<br /># Output: datetime.datetime(2017, 2, 4, 12, 2, 33)<br /></pre><b>"04 February 2017 12:02:33 PM"</b><br /><pre class="brush: py">from datetime import datetime<br />s = "04 February 2017 12:02:33 PM"<br />d = datetime.strptime(s, "%d %B %Y %H:%M:%S %p")<br />print(d)<br /># Output: datetime.datetime(2017, 2, 4, 12, 2, 33)<br /></pre><b>"Saturday 04 February 2017 12:02:33 PM"</b><br /><pre class="brush: py">from datetime import datetime<br />s = "Saturday 04 February 2017 12:02:33 PM"<br />d = datetime.strptime(s, "%A %d %B %Y %H:%M:%S %p")<br />print(d)<br /># Output: datetime.datetime(2017, 2, 4, 12, 2, 33)<br /></pre><b>"Sat February 2017 12:02:33 pm"</b><br /><pre class="brush: py">from datetime import datetime<br />s = "Sat 04 February 2017 12:02:33 pm"<br />d = datetime.strptime(s, "%a %d %B %Y %H:%M:%S %p")<br />print(d)<br /># Output: datetime.datetime(2017, 2, 4, 12, 2, 33)<br /></pre><a href="https://docs.python.org/2/library/datetime.html" target="_blank">Reference: https://docs.python.org/2/library/datetime.html</a></div>Anjaneyulu Battahttp://www.blogger.com/profile/04466094850374273896noreply@blogger.com0tag:blogger.com,1999:blog-4434479834026477776.post-66194427357754779122017-03-02T23:03:00.000+05:302017-12-16T16:29:14.731+05:30how to use "filter" builtin function in python?<div dir="ltr" style="text-align: left;" trbidi="on"><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgl2OcLp3iRKRbPR5I0WFRU2didJJJq680-WoOpxhq7kaGxEEjcXZC6THI605DBluqgQ70zazRyqoyHFFXUOEzDJiNJX5M6KfKSbXZJR5hvBDO9JFSNTaTparwHT_NTCe6xltm4fHP9Mqt9/s1600/filter_data_python.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="320" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgl2OcLp3iRKRbPR5I0WFRU2didJJJq680-WoOpxhq7kaGxEEjcXZC6THI605DBluqgQ70zazRyqoyHFFXUOEzDJiNJX5M6KfKSbXZJR5hvBDO9JFSNTaTparwHT_NTCe6xltm4fHP9Mqt9/s320/filter_data_python.png" width="320" /></a></div><ul style="text-align: left;"><li><i><b>"filter"</b></i> is a python's built-in function which can be found in module "__builtin__".</li><li>It takes two arguments, first argument as a function and second argument as sequence of objects/elements.</li><li>It passes all objects/elements to given function one after other.</li><li>If function returns "True" then it appends the object/element to a list & returns the list after passing all elements.</li><li>If sequence is a tuple or string, it returns the same type, else return a list. </li><li>If function is None, return the items that are true.</li></ul><br /><h3>Let's see an example for <i><b>"filter"</b></i></h3><h3 style="text-align: left;">Q. Find out the all prime numbers below hundred ? </h3><h4 style="text-align: left;"> 1. Traditional way</h4><pre class="brush: py">num = 100<br />primes = []<br />for i in range(2, 100):<br /> for j in range(2, i):<br /> if i % j == 0:<br /> break<br /> else:<br /> primes.append(i)<br />print(primes)<br /># Output: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]<br /></pre><h4 style="text-align: left;">2. Using function "filter" </h4><pre class="brush: py">def is_prime(num):<br /> for j in range(2, num):<br /> if num % j == 0:<br /> return False<br /> else:<br /> return True<br />primes = filter(is_prime, range(1, 100))<br />print(primes)<br /># Output: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]<br />print(type(primes))<br /># Output: list<br /></pre><h3 style="text-align: left;">Lets test filter by passing "None" as first argument </h3><pre class="brush: py">a = (0, 1, 2, 3)<br />l = filter(None, a)<br />print(l)<br /># Output: (1, 2, 3)<br />print(type(l))<br /># Output: tuple<br /></pre>It converts element to boolean if it returns true then it will add element to list/tuple/string.<br /><h3 style="text-align: left;">Let's apply "filter" on strings.</h3><h4 style="text-align: left;">Remove vowels from string in python. </h4><pre class="brush: py">def remove_vowels(char):<br /> return char.lower() not in ['a', 'e', 'i', 'o', 'u']<br />s = filter(remove_vowels, "this is anjaneyulu batta")<br />print(s)<br /># Output: ths s njnyl btt<br /></pre><br /></div>Anjaneyulu Battahttp://www.blogger.com/profile/04466094850374273896noreply@blogger.com0tag:blogger.com,1999:blog-4434479834026477776.post-26621674244187583712017-03-01T23:31:00.000+05:302017-12-16T16:29:14.756+05:30how to use "reduce" builtin function in python?<div dir="ltr" style="text-align: left;" trbidi="on"><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjG71F695s1bktsUVSbA6_8BJn3dI20aQHbS4IG7pv6UJhfPHdv0hsNZbyGb47mDwZO1sU27v4_IwsFslyJAgJx6i5V8TlMjN-FH7ghXmkIiyjl1DG9AdmHfT4q4mScEqi_yvhmxwTHzOVU/s1600/python-reduce.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="300" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjG71F695s1bktsUVSbA6_8BJn3dI20aQHbS4IG7pv6UJhfPHdv0hsNZbyGb47mDwZO1sU27v4_IwsFslyJAgJx6i5V8TlMjN-FH7ghXmkIiyjl1DG9AdmHfT4q4mScEqi_yvhmxwTHzOVU/s400/python-reduce.jpg" width="400" /></a></div><ul style="text-align: left;"><li>reduce is a built-in function in python module "__builtin__".</li><li>It takes function as first argument and second argument as an sequence of items.</li><li>It applies function on two arguments cumulatively to the items of a sequence from left to right and returns a single value.</li><li>If initial is present, it is placed before the items of the sequence in the calculation, and serves as a default when the sequence is empty.</li><li>It doesn't allow empty sequence.</li></ul>Let's see examples<br /><h3 style="text-align: left;">Let's sum all the elements in a list </h3><h4 style="text-align: left;">traditional way </h4><div style="text-align: left;"><br /></div><pre class="brush: py" style="text-align: left;">l = [1, 2, 3, 5, 6]<br />sum_of_numbers = 0<br />for num in l:<br /> sum_of_numbers += num<br />print(sum_of_numbers)<br /># Output: 17<br /></pre><h4 style="text-align: left;">Let's do it using "reduce" </h4><pre class="brush: py" style="text-align: left;">l = [1, 2, 3, 5, 6]<br /><br />def sum_numbers(a, b):<br /> return a + b<br /><br />sum_of_numbers = reduce(sum_numbers, l)<br />print(sum_of_numbers)<br /># Output: 17<br /></pre><h3 style="text-align: left;">Let's find factorial of number 5</h3><h4 style="text-align: left;">traditional way </h4><pre class="brush: py" style="text-align: left;">num = 5<br />result = 1<br />for i in range(1, num+1):<br /> result = result * i<br />print("Factorial of 5 = %s" % (result))<br /># Output: 120<br /></pre><h4 style="text-align: left;">Let's do it using "reduce" </h4><pre class="brush: py" style="text-align: left;">num = 5<br />result = reduce(lambda x, y : x*y, range(1, num+1))<br />print("Factorial of 5 = %s" % (result))<br /># Output: 120<br /></pre><h3 style="text-align: left;">Let's find out max number in a list of numbers using "reduce" and "max" </h3><pre class="brush: py">l = [3, 1, 5, 10, 7, 6]<br />max_num = reduce(max, l)<br />print("max num = %s" % (max_num))<br /># Output: max num = 10<br /></pre></div>Anjaneyulu Battahttp://www.blogger.com/profile/04466094850374273896noreply@blogger.com0tag:blogger.com,1999:blog-4434479834026477776.post-28616028838334951102017-02-28T23:20:00.000+05:302017-12-16T16:29:14.781+05:30 how to use "map" keyword or function in python?<div dir="ltr" style="text-align: left;" trbidi="on"><div><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjjKzTDcTWSn47p04vrueFebEND4b-A3xi6Bbovcgfpl26_LVpS3zQDH9gFcyU0LFnUhuuJDCS7pLQdD-WKqItD2F3vrp0onXqTcdZqkETr_0uGLOXVe-Jn8Pi6W2pF8HvKImJafoisXD02/s1600/world_map.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="200" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjjKzTDcTWSn47p04vrueFebEND4b-A3xi6Bbovcgfpl26_LVpS3zQDH9gFcyU0LFnUhuuJDCS7pLQdD-WKqItD2F3vrp0onXqTcdZqkETr_0uGLOXVe-Jn8Pi6W2pF8HvKImJafoisXD02/s400/world_map.png" width="400" /></a></div><ul style="text-align: left;"><li>"map' is a built-in function in python.</li><li>It takes first argument as a function or a callable object.</li><li>All other arguments must be sequence of elements otherwise it raises an error.</li><li>we can reduce the number of lines code using map.</li><li>It's like functional programming technique.</li><li>map return a list of the results of applying the function to the items of the argument sequence(s).</li><li> If more than one sequence is given, the function is called with an argument list consisting of the corresponding item of each sequence, substituting 'None' for missing values when not all sequences have the same length.</li></ul><h3 style="text-align: left;">Convert list of numbers to list of strings without using map</h3><pre class="brush: py">l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]<br />output = []<br />for i in l:<br /> output.append(str(i))<br />print(output)<br /># Output: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']<br /></pre><h3 style="text-align: left;">Convert list of numbers to list of strings using map</h3><pre class="brush: py"># I love to use it<br />l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]<br />output = map(str, l)<br />print(output)<br /># Output: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']<br /></pre><h3 style="text-align: left;">Return list of elements by adding numbers of two lists based on their indexes - Traditional way</h3><pre class="brush: py">l1 = [1, 2, 3, 4, 5, 6]<br />l2 = [10, 20, 30, 40, 50, 60]<br />output = []<br />for i, j in zip(l1, l2):<br /> output.append(i+j)<br />print(output)<br /># Output: [11, 22, 33, 44, 55, 66]<br /></pre><h3 style="text-align: left;">Return list of elements by adding numbers of two lists based on their indexes - Functional Programming</h3><pre class="brush: py">l1 = [1, 2, 3, 4, 5, 6]<br />l2 = [10, 20, 30, 40, 50, 60]<br />def sum_elements(a, b):<br /> return a + b<br />output = map(sum_elements, l1, l2)<br />print(output)<br /># Output: [11, 22, 33, 44, 55, 66]<br /></pre><h3 style="text-align: left;">Let's test the map with different types of inputs</h3><h4 style="text-align: left;">how to use multiple arguments with "map" python? </h4><pre class="brush: py" style="text-align: left;">def function(*args):<br /> return args<br />output = map(function, [1,2,3], ("a", "b", "c"), (1.2, 2.3, 3.4))<br />print(output)<br /># Output: [(1, 'a', 1.2), (2, 'b', 2.3), (3, 'c', 3.4)]<br /></pre><h4 style="text-align: left;">how to use multiple arguments of varying length with "map" with python? </h4><pre class="brush: py" style="text-align: left;">def function(*args):<br /> return args<br />output = map(function, [1,2,3], ("a", "b", "c", "d", "e", "f"), (1.2, 2.3, 3.4))<br />print(output)<br /># Output: [(1, 'a', 1.2), (2, 'b', 2.3), (3, 'c', 3.4), (None, 'd', None), (None, 'e', None), (None, 'f', None)]<br /></pre><h4 style="text-align: left;">use "None" instead of function with "map" in python </h4><pre class="brush: py" style="text-align: left;">output = map(None, [1,2,3], ("a", "b", "c"), (1.2, 2.3, 3.4))<br />print(output)<br /># Output: [(1, 'a', 1.2), (2, 'b', 2.3), (3, 'c', 3.4)]<br /></pre><h4 style="text-align: left;">use other data types like "list" instead of function with "map" in python </h4><pre class="brush: py">output = map([], [1,2,3], ("a", "b", "c"), (1.2, 2.3, 3.4))<br /># Output: TypeError: 'list' object is not callable<br /></pre></div></div>Anjaneyulu Battahttp://www.blogger.com/profile/04466094850374273896noreply@blogger.com0tag:blogger.com,1999:blog-4434479834026477776.post-60985800985454660972017-02-25T19:38:00.000+05:302017-12-16T16:29:14.809+05:30Operations and Usage of Sets - Python<div dir="ltr" style="text-align: left;" trbidi="on"><div><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjeRxDCRT9Or79IO-vl_hF1WpT6GI3d3qssZfmGytFLKGxiTNn-5qxruHr2-6AYod8jH4o8p-aUwqgtOwry91rpLOCvLyECjTNvXXedZiUVTQFn8jYFCcTDoogxRijZc3_g1GrnBVcABHIQ/s1600/sets-python.jpeg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="381" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjeRxDCRT9Or79IO-vl_hF1WpT6GI3d3qssZfmGytFLKGxiTNn-5qxruHr2-6AYod8jH4o8p-aUwqgtOwry91rpLOCvLyECjTNvXXedZiUVTQFn8jYFCcTDoogxRijZc3_g1GrnBVcABHIQ/s400/sets-python.jpeg" width="400" /></a></div><ul style="text-align: left;"><li>Set is a built in data-type(data-structure) in python.</li><li>It only stores unique elements.</li><li>It do not contains duplicate elements.</li><li>We can iterate over sets.</li></ul><h3 style="text-align: left;">What is set ? </h3><div style="text-align: left;">In <a href="https://en.wikipedia.org/wiki/Mathematics" title="Mathematics">mathematics</a>, a <b>set</b> is a well-defined collection of distinct objects, considered as a single <a href="https://en.wikipedia.org/wiki/Mathematical_object" title="Mathematical object">object</a> in its own right. </div></div><div><ul style="text-align: left;"></ul></div><h3 style="text-align: left;">How to create a set in python?</h3><pre class="brush: py" style="text-align: left;"># case1: empty set with built-in keyword<br />s = set()<br />print(s)<br /># Output: set([])<br />print(type(s))<br /># Output: set<br /># case2: set with initial data<br />s = {1, 'a', '@', 'batta', 2.22}<br />print(s)<br /># Output: set([2.22, 'batta', 1, 'a', '@'])<br />print(type(s))<br /># Output: set<br /></pre><h3 style="text-align: left;">How to add an element to a set in python ? </h3><pre class="brush: py" style="text-align: left;">s = {1,2,3,4,5,6,'a'}<br />print(s)<br /># Output: set(['a', 1, 2, 3, 4, 5, 6])<br />s.add(100)<br />print(s)<br /># Output: set(['a', 1, 2, 3, 4, 5, 6, 100])<br /></pre><h3 style="text-align: left;">How to remove an element from set in python ?</h3><pre class="brush: py" style="text-align: left;">s = {1,2,3,4,5,6,'a'}<br />r = s.remove(5)<br />print(s)<br /># Output: set(['a', 1, 2, 3, 4, 6])<br />print(r)<br /># Output: None<br />s = {1,2,3,4,5,6,'a'}<br />r = s.discard(5)<br />print(s)<br /># Output: set(['a', 1, 2, 3, 4, 6])<br />print(r)<br /># Output: None<br /></pre><h3 style="text-align: left;">How to remove and get last element from set in python ?</h3><pre class="brush: py" style="text-align: left;">s = {1,2,3,4,5,6,'a'}<br />r = s.pop()<br />print(s)<br /># Output: set([1, 2, 3, 4, 5, 6])<br />print(r)<br /># Output: 'a'<br /></pre><h3 style="text-align: left;">How to clear or empty the set in python?</h3><pre class="brush: py" style="text-align: left;">s = {'a', 1,2,3,4,5,6}<br />s.clear()<br />print(s)<br /># Output: set([])<br /></pre><h3 style="text-align: left;">How to copy set1 to set2 ?</h3><pre class="brush: py" style="text-align: left;">s1 = {1,2,3,4, 'a', 'hello', 1.255}<br /># id - it is a built-in function it returns the memory location of python object.<br />s2 = s1.copy()<br />print(id(s1))<br /># Output: 139864877446360<br />print(id(s2))<br /># Output: 139864877446128<br /># if we do not use 'copy' <br />s3 = {1,2,3,4}<br />s4 = s3<br />print(id(s3))<br /># Output: 139864878456528<br />print(id(s4))<br /># Output: 139864878456528<br /></pre><h3 style="text-align: left;">How to find difference of two sets in python ?</h3><pre class="brush: py">s1 = {1,2,3,4,5,6,7,8}<br />s2 = {4,5,6,9, 10, 11, 12, 13, 14}<br />difference = s1.difference(s2)<br />print(difference)<br /># Output: set([8, 1, 2, 3, 7]) <br /># shortcut method<br />difference = s1 - s2<br />print(difference)<br /># Output: set([8, 1, 2, 3, 7]) <br /># It do not modify the initial data in s1, s2<br />print(s1)<br /># Output: set([1, 2, 3, 4, 5, 6, 7, 8])<br />print(s2)<br /># Output: set([4, 5, 6, 9, 10, 11, 12, 13, 14])<br /></pre><h3 style="text-align: left;">How to update the difference of set1, set2 into set1 ? </h3><pre class="brush: py">s1 = {1,2,3,4,5,6,7,8}<br />s2 = {4,5,6,9, 10, 11, 12, 13, 14}<br />difference = s1.difference_update(s2)<br />print(difference)<br /># Output: None<br />print(s1)<br /># Output: set([1, 2, 3, 7, 8])<br />print(s2)<br /># Output: set([4, 5, 6, 9, 10, 11, 12, 13, 14])<br /></pre><h3 style="text-align: left;">How to find the common elements in set1, set2 in python?</h3><pre class="brush: py">s1 = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}<br />s2 = {4, 5, 6, 9, 10, 11, 12, 13, 14}<br />intersection = s1.intersection(s2)<br />print(intersection)<br /># Output: set([4, 5, 6, 9, 10, 11])<br /></pre><h3 style="text-align: left;">How to check whether set1 and set2 contains common elements or not ? </h3><pre class="brush: py"># find if sets disjoint or not<br />set1 = set([1, 2.55, 3, "a"])<br />set2 = set(["hello", "world", "batta"])<br />is_disjoint = set1.isdisjoint(set2)<br />print(is_disjoint)<br /># Output: True<br /># Because there are no common elements<br />set1 = set([1, 2.55, 3, "a"])<br />set2 = set(["hello", 1, "a"])<br />is_disjoint = set1.isdisjoint(set2)<br />print(is_disjoint)<br /># Output: False<br /># common elements are 1, "a"<br /></pre><h3 style="text-align: left;">How to check if given set s1 is subset of other set s2 or not ? </h3><pre class="brush: py"># case1<br />set1 = {0, 1, 2, 3, "abcd", 5, 6, 7, 8, 9} # superset<br />set2 = {1, 3, 5} # subset<br />result = set2.issubset(set1)<br />print(result)<br /># Output: True<br /># case2<br />set1 = {0, 1, 2, 3, "abcd", 5, 6, 7, 8, 9} # superset<br />set2 = {1, 3, 5} # subset<br />result = set1.issubset(set2)<br />print(result)<br /># Output: False<br /># case3<br />set1 = {0, 1, 2, 3, "abcd", 5, 6, 7, 8, 9}<br />set2 = {1, 3, 5, "extra element"}<br />result = set2.issubset(set1)<br />print(result)<br /># Output: False<br /></pre><h3 style="text-align: left;">How to check if given set s1 is superset of other set s2 or not ? </h3><pre class="brush: py"># case1<br />set1 = {0, 1, 2, 3, "abcd", 5, 6, 7, 8, 9} # superset<br />set2 = {1, 3, 5} # subset<br />result = set1.issuperset(set2)<br />print(result)<br /># Output: True<br /># case2<br />set1 = {0, 1, 2, 3, "abcd", 5, 6, 7, 8, 9} # superset<br />set2 = {1, 3, 5} # subset<br />result = set2.issuperset(set1)<br />print(result)<br /># Output: False<br /># case3<br />set1 = {0, 1, 2, 3, "abcd", 5, 6, 7, 8, 9}<br />set2 = {1, 3, 5, "extra element"}<br />result = set1.issuperset(set2)<br />print(result)<br /># Output: False<br /></pre><h3 style="text-align: left;">How to combine(<a href="https://en.wikipedia.org/wiki/Union_(set_theory)" target="_blank">union</a>) set1 and set2 ?</h3><pre class="brush: py">set1 = {0, 1, 2, 3, 5, 6, 7, 8, 9, 'abcd'}<br />set2 = {1, 3, 5, 'extra element'}<br />result = set1.union(set2) # it will not modify the original sets & returns union of two sets.<br />print(result)<br /># Output: {0, 1, 2, 3, 5, 6, 7, 8, 9, 'abcd', 'extra element'}<br /># check if original sets changed or not<br />print(set1)<br /># Output: {0, 1, 2, 3, 5, 6, 7, 8, 9, 'abcd'}<br />prnt(set2)<br /># Output: {1, 3, 5, 'extra element'}<br /></pre><h3 style="text-align: left;">How to update set1 with other set set2 ? </h3><pre class="brush: py">set1 = {0, 1, 2, 3, 5, 6, 7, 8, 9, 'abcd'}<br />set2 = {1, 3, 5, 'extra element'}<br />result = set1.update(set2) # it will update the operating set & returns None.<br />print(result)<br /># Output: None<br />print(set1)<br /># Output: {'abcd', 1, 2, 3, 5, 6, 7, 8, 9, 'extra element', 0}<br />print(set2)<br /># Output: {1, 3, 5, 'extra element'} <br /></pre><h3 style="text-align: left;">How to find symmetric difference of two sets ? </h3>symmetric difference is known as the disjunctive union, of two sets is the set of elements which are in either of the sets and not in their intersection. <br /><pre class="brush: py">set1 = {0, 1, 2, 3, 5, 6, 7, 8, 9, 'abcd'}<br />set2 = {1, 3, 5, 'extra element'}<br />result = set1.symmetric_difference(set2) # It will not change the original sets.<br /># it removes common elements in both sets and returns the union of remaining elements.<br />print(result)<br /># Output: {0, 2, 6, 7, 8, 9, 'abcd', 'extra element'}<br /># print original sets<br />print(set1)<br /># Output: {0, 1, 2, 3, 5, 6, 7, 8, 9, 'abcd'}<br />print(set2)<br /># Output: {1, 3, 5, 'extra element'}<br /></pre><h3 style="text-align: left;">How to find symmetric difference of two sets and update the result in same set? </h3><pre class="brush: py">set1 = {0, 1, 2, 3, 5, 6, 7, 8, 9, 'abcd'}<br />set2 = {1, 3, 5, 'extra element'}<br />result = set1.symmetric_difference_update(set2)<br /># it removes common elements in both sets and updates set1 with union of remaining elements.<br />print(result)<br /># Output: None<br /># print original sets<br />print(set1)<br /># Output: {0, 2, 6, 7, 8, 9, 'abcd', 'extra element'}<br />print(set2)<br /># Output: {1, 3, 5, 'extra element'}<br /></pre>Note: You can pass any iterable data to set methods. </div>Anjaneyulu Battahttp://www.blogger.com/profile/04466094850374273896noreply@blogger.com0