<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by chepkirui dorothy on Medium]]></title>
        <description><![CDATA[Stories by chepkirui dorothy on Medium]]></description>
        <link>https://medium.com/@doroh_dev?source=rss-4ece44e4327d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*b5z0i_y7c4tIRBIZS8stQg.png</url>
            <title>Stories by chepkirui dorothy on Medium</title>
            <link>https://medium.com/@doroh_dev?source=rss-4ece44e4327d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 13:29:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@doroh_dev/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Understanding data types in Python.]]></title>
            <link>https://medium.com/@doroh_dev/understanding-data-types-in-python-d7b8c7e99594?source=rss-4ece44e4327d------2</link>
            <guid isPermaLink="false">https://medium.com/p/d7b8c7e99594</guid>
            <category><![CDATA[data-types-in-python]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-type]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[chepkirui dorothy]]></dc:creator>
            <pubDate>Wed, 25 Oct 2023 06:09:31 GMT</pubDate>
            <atom:updated>2023-10-25T06:09:31.684Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>A beginner’s guide to exploring the basics of data types in Python.</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*L9np7Ujhtj0vpybI" /></figure><p>Variables in Python belong to a data type. A data type is a classification that shows which value a variable has. It ensures that correct operations are done to the variable without causing errors.</p><p>Data types in Python fall into two categories: primitive and non-primitive types.</p><p><strong>Primitive data types</strong></p><p>Primitive data types contain simple values of data and are building blocks. They are:</p><ul><li>Integer</li><li>Float</li><li>String</li><li>Boolean</li></ul><p>Let’s look into each and their properties.</p><p><strong>Integer</strong></p><p>An integer is a numerical data type that represents a whole number, both negative and positive.</p><pre>num = 6<br><br>print(type(num))</pre><pre>&lt;class &#39;int&#39;&gt;</pre><p>We can do arithmetic operations on them.</p><pre>x = -6<br><br>y = 5<br><br>print( &quot;-6 + 5 is&quot; , x + y )#addition<br><br>print( &quot;-6 - 5 is&quot; ,x - y )#subtraction<br><br>print( &quot;-6 *5 is&quot; ,x* y )#multiplication<br><br>print( &quot;-6 / 5 is&quot; ,x / y )#division<br><br>print( &quot;-6 % 5 is&quot; ,x % y )#modulus</pre><pre>-6 + 5 is -1<br><br>-6 - 5 is -11<br><br>-6 * 5 is -30<br><br>-6 / 5 is -1.2<br><br>-6 % 5 is 4</pre><p><strong>Float</strong></p><p>A float is a numeric data type used to represent decimal numbers.</p><pre>num = 6.0<br><br>print(type(num))</pre><pre>&lt;class &#39;float&#39;&gt;</pre><p>We can also do arithmetic operations, just like the integers.</p><pre>x = -6.0<br><br>y = 5<br><br>print( &quot;-6 + 5 is&quot; , x + y )#addition<br><br>print( &quot;-6 - 5 is&quot; ,x - y )#subtraction<br><br>print( &quot;-6 *5 is&quot; ,x* y )#multiplication<br><br>print( &quot;-6 / 5 is&quot; ,x / y )#division<br><br>print( &quot;-6 % 5 is&quot; ,x % y )#modulus</pre><pre>-6 + 5 is -1.0<br><br>-6 - 5 is -11.0<br><br>-6 * 5 is -30.0<br><br>-6 / 5 is -1.2<br><br>-6 % 5 is 4.0</pre><p><strong>Strings</strong></p><p>A string is a collection on characters. An example is a name — like Aron. Aron is made up of four characters, ‘a’,’r’, ‘o’, ’n’. They are enclosed with either single quotes or double quotes.</p><pre>name = &#39;Aron&#39; <br>surname = &quot;Koech&quot;<br>print(type(name)) <br>print(name) <br>print(type(surname)) <br>print(surname)</pre><pre>&lt;class &#39;str&#39;&gt;<br>Aron<br>&lt;class &#39;str&#39;&gt;<br>Koech</pre><p>We can concatenate the variables to be one word.</p><pre>print(name +&#39; &#39;+ surname)<br>print(name , surname)</pre><pre>Aron Koech <br>Aron Koech</pre><p>We have combined the name and surname using string concatenation in the first line, with a space in between.</p><p>The second line of code uses comma-separated values to give the same output.</p><p><strong>Boolean</strong></p><p>Boolean is a data type that represents a binary value, either True or False. It is commonly used to evaluate conditions in decision-making processes.</p><pre>x = -6<br><br>y = 5<br><br>print(x == y)</pre><pre>False</pre><p>==(equality operator) is used to check if x and y variables are equal. If they are equal, it prints True, otherwise False.</p><p><strong>Non-primitive data types</strong></p><p>They are complex data types, that can store collection of values in different formats. They are:</p><ul><li>Lists</li><li>Tuples</li><li>Sets</li><li>Dictionaries</li></ul><p><strong>Lists</strong></p><p>Lists are data types that store a collection of values, such as integers and strings. They are stored inside [ ] brackets. Lists are ordered, meaning the order will not change. They are also mutable, meaning the elements can be modified after they have been created.</p><pre>x = [1, 2, 3, 4, 5] # creates a list of integers<br><br>colors = [&#39;blue&#39;, &#39;pink&#39;, &#39;yellow&#39;, &#39;brown&#39;] # creates a list of strings<br><br>list = [5, 10.4, &#39;Purple&#39;, False] # creates a list of mixed data types<br><br>print(x)<br><br>print(colors)<br><br>print(list)</pre><pre>[1, 2, 3, 4, 5]<br><br>[&#39;blue&#39;, &#39;pink&#39;, &#39;yellow&#39;, &#39;brown&#39;]<br><br>[5, 10.4, &#39;Purple&#39;, False]</pre><p>To access an element in the list:</p><pre>print(colors[2])</pre><p>This prints the color element at index 2, which is yellow.</p><p>Lists can also be sliced.</p><pre>print(colors[2:])<br><br>print(x[1:3])<br><br>print(list[:2])</pre><pre>[&#39;yellow&#39;, &#39;brown&#39;]<br><br>[2, 3]<br><br>[5, 10.4]</pre><p>We can change an element in a list. Suppose we want to replace the second color to purple.</p><pre>colors[1] = &#39;purple&#39;<br><br>print(colors)</pre><pre>[&#39;blue&#39;, &#39;purple&#39;, &#39;yellow&#39;, &#39;brown&#39;]</pre><p>Tuples</p><p>Tuples are data types that contain ordered, immutable elements. The elements are enclosed in ( ) brackets.</p><pre>x = (1, 2, 3, 4, 5)<br><br>print(x)</pre><pre>(1, 2, 3, 4, 5)</pre><p>We can access individual elements in a tuple by indexing, just like lists.</p><pre>print(x[2])</pre><p>This prints the element in index 2, which is 3.</p><p>We can also access the range of elements using slicing.</p><pre>print(x[2:])</pre><pre>(3, 4, 5)</pre><p>This prints the elements from index 2 to the last element.</p><p><strong>Sets</strong></p><p>Sets are collections of unique elements. They are unordered and mutable.</p><pre>x = (1,2,1,3,2,3,2,4,4,5)<br><br>print(set(x))</pre><pre>{1, 2, 3, 4, 5}</pre><p>Only the unique elements are printed.</p><p><strong>Dictionaries</strong></p><p>Dictionaries are data types that are made up of key-value elements in pairs.</p><p>They are stored using curly {} brackets.</p><pre>dict = {&#39;Eliud&#39;:1, &#39;Peter&#39;:2, &#39;Andrew&#39;:3, &#39;Mike&#39;:4}<br><br>print(dict)</pre><pre>{&#39;Eliud&#39;: 1, &#39;Peter&#39;: 2, &#39;Andrew&#39;: 3, &#39;Mike&#39;: 4}</pre><p>You can access individual values by referring to their keys.</p><pre>print(dict[&#39;Eliud&#39;])</pre><p>This will return 1, which is its key.</p><p>You can also change the value of the keys.</p><pre>dict[&#39;Eliud&#39;]=10<br><br>print(dict)</pre><pre>{&#39;Eliud&#39;: 10, &#39;Peter&#39;: 2, &#39;Andrew&#39;: 3, &#39;Mike&#39;: 4}</pre><p><strong>Conclusion</strong></p><p>Data types are categorized as primitive and non-primitive. There is still more to cover on data types. Check out <a href="https://docs.python.org/3/library/datatypes.html">python data types</a> to learn more.</p><p><em>Originally published at </em><a href="https://doroh.hashnode.dev/understanding-data-types-in-python"><em>https://doroh.hashnode.dev</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7b8c7e99594" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Django ORM in a Nutshell]]></title>
            <link>https://python.plainenglish.io/django-orm-in-a-nutshell-c4667d154992?source=rss-4ece44e4327d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c4667d154992</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[orm]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[chepkirui dorothy]]></dc:creator>
            <pubDate>Wed, 25 Oct 2023 05:44:06 GMT</pubDate>
            <atom:updated>2023-10-26T11:28:59.081Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2Qu1K-iX6uMsBX86" /><figcaption>Photo by <a href="https://unsplash.com/@pakata?utm_source=Hashnode&amp;utm_medium=referral">Pakata Goh</a> on <a href="https://unsplash.com/?utm_source=Hashnode&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Python’s Django framework would not be complete if it did not include a way to interact with databases. The feature that makes it more powerful is its ORM.</h4><p><strong>What is ORM</strong></p><p>ORM (Object-Relational Mapping) is a technique that uses an object-oriented paradigm to query and manipulate data from a database. Django has used this technique to create its own Object Relational Mapper, also known as Django ORM. It is used to query and retrieve data from various relational databases, such as SQLite, PostgreSQL, and MySQL. Simply put, Django ORM is a database abstraction API that lets you create, retrieve, update and delete objects. The ORM automates this transmission, so the developer does not need to write any SQL. This speeds up and eliminates errors throughout the development process.</p><p>Django ORM provides an alternative to writing the good old Structured Query Language (SQL). Let’s create a simple bank account database to better understand how to query data using Django ORM. The bank has a customer, while the customer has one or many accounts. It has two models: Customer and Account. The Customer model has a user field, while the Account model has four fields: name, balance, customer and timestamp. The customer model has used Django’s built-in User model. This tutorial will not go into detail about the User model. To better understand how the User model works, check <a href="https://docs.djangoproject.com/en/4.0/topics/auth/default/#user-objects">User</a>.</p><p>Create a <a href="http://models.py/"><em>models.py</em></a>:</p><pre>from django.db import models<br>from django.contrib.auth.models import User<br><br># Create your models here.<br><br>class Customer(models.Model):<br>    user=models.OneToOneField(User, on_delete=models.CASCADE)<br>    def __str__(self):<br>        return self.user.username<br><br>class Account(models.Model):<br>    name = models.CharField(max_length=30, unique=True, default=&#39;&#39;)<br>    balance=models.DecimalField( max_digits=12, decimal_places=2)<br>    customer=models.ForeignKey(Customer, on_delete=models.CASCADE)<br>    timestamp = models.DateTimeField(auto_now_add = True)<br>    def __str__(self):<br>        return self.name</pre><p>Django Field types used are:</p><ul><li><strong><em>OneToOneField</em> </strong>— is used to define a one-to-one relationship, whereby one record in one table corresponds to one and only one record in another table. Here, Customer has a One-To-One relationship with the existing User model.</li><li><strong><em>CharField</em></strong>- A field where text-based data can be stored. In the Accounts model, the name of the account should have a maximum length of 30 and be unique.</li><li><strong><em>DecimalField</em></strong> — It is a fixed-precision decimal number represented by a Decimal object in Python. Accounts balance has a maximum digit of twelve with two decimal points.</li><li><strong><em>DateTimeField</em></strong> — A field to store date and time, represented in Python by a <em>datetime.datetime</em> instance. <em>auto_now_add</em> means that when the object is first created, the field is automatically set to that time.</li><li><strong><em>ForeignKey</em> </strong>— It is used to define a <em>many-to-one</em> relationship. A customer can have many accounts, but one account cannot be held by more than one customer. <em>on_delete=models.CASCADE</em> tells Django that when the referenced item is deleted, all objects with references to it are also deleted. In this case, when a customer is deleted, Django deletes their accounts as well.</li></ul><p>After creating a sample database above, run migrations. Migrations are Django’s way of propagating changes you make to your models (adding a field, deleting a model, etc.) into your database schema.</p><pre>python manage.py migrate</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/0*Y3urQK04s_LV1E7w" /></figure><p>Django shell provides easy access to ORM, allowing you to easily interact with the database. To access the shell, run the following command from the main directory of your Django project.</p><pre>python manage.py shell</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/0*eJxR1DmEHGMmUDaR" /></figure><p>Import all models to the interactive console you have just created.</p><pre>&gt;&gt;&gt; from bank.models import *<br>&gt;&gt;&gt; from django.contrib.auth.models import User</pre><p>This imports Customer, Accounts and User models.</p><p><strong>Create objects</strong></p><p>Django employs an easy-to-use mechanism to express database-table data in Python objects: A model class represents a database table, while a model instance in that class represents a specific entry in the database table. To create an object, use <strong>create()</strong> method which takes keyword arguments. Here, <em>first_name</em>, <em>last_name</em> and <em>username</em> are keyword arguments. Then use the <strong>save()</strong> method to save it in the database.</p><p>To create a new user:</p><pre>d=User.objects.create(first_name=&#39;tom&#39;,last_name=&#39;holland&#39;, username=&#39;holland&#39;)<br>d.save()<br><br>e = User.objects.create(first_name= &#39;jake&#39;, last_name= &#39;candy&#39;, username= &#39;candy&#39;)<br>e.save()</pre><p>To check that the user objects have been saved:</p><pre>User.objects.all()</pre><p>The <strong>all()</strong> method returns a QuerySet of all the objects in the database. This will return all the user objects created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/0*5mzBIGE3H4Iyum9L" /></figure><p>You have created user objects. To create customer objects, pass the “parent” object as this object’s primary key:</p><pre>cust1 = Customer(user=d)<br>cust1.save() <br><br>cust2 = Customer(user=e) <br>cust2.save()</pre><p>To check saved customers:</p><pre>Customer.objects.all()</pre><p>This gives the list of all the customers that you have created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/0*YVJ3IXfWZghpebAC" /></figure><p><strong>Read objects</strong></p><p>To retrieve objects from the database, use <strong>get()</strong> or <strong>filter()</strong> method.</p><p><strong>get()</strong> is used to return a required object. If the item doesn’t exist or if there are multiple items that meet your criteria, it throws an error.</p><p><strong>filter()</strong> returns a queryset object if more than one object matches your query. If no matching items were found, it returns an empty Queryset without throwing an error.</p><p>Let’s say you had users who shared the same first name, Jane.</p><pre>a= User.objects.filter(first_name=&#39;jane&#39;)</pre><p>The result will be a Queryset will all users whose first name is jane.</p><p><strong>Update objects</strong></p><p>You can make changes to a user’s data and update them on the database by using <strong>save()</strong> method. If you wanted to change <em>cust1</em> username from richie to richard and update the changes:</p><pre>d=User.objects.get(username= &#39;richie&#39;)<br>d.username=&#39;richard&#39; <br>d.save() <br><br>cust1=Customer.objects.get(user=d) <br>cust1.save()</pre><p><strong>Delete objects</strong></p><p>Django auto-generates a primary key called <em>id</em> by default if you did not specify one. The customer objects can be accessed by using <em>id</em>.</p><pre>b=Customer.objects.get(id=2)</pre><p>The output is the corresponding Customer object. To delete the above Customer object:</p><pre>b=Customer.objects.get(id=2).delete()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/0*cvujr4QzETqzPLPO" /></figure><p>The changes made in the Django shell are available in the Django admin interface. The following images show users and customers respectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IxsFFQ3jAl2Er7O4" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gv4wtn0s_Fpfz9oz" /></figure><p><strong>Conclusion</strong></p><p>You have learned how to create, update, read, and delete data in Django using its ORM. This sums up the basic functionalities to get you started querying databases. Happy coding.</p><p><em>Originally published at </em><a href="https://doroh.hashnode.dev/django-orm-in-a-nutshell"><em>https://doroh.hashnode.dev</em></a><em>.</em></p><h3>In Plain English</h3><p><em>Thank you for being a part of our community! Before you go:</em></p><ul><li><em>Be sure to </em><strong><em>clap</em></strong><em> and </em><strong><em>follow</em></strong><em> the writer! 👏</em></li><li><em>You can find even more content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><strong><em> 🚀</em></strong></li><li><em>Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. 🗞️</em></li><li><em>Follow us: </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a><strong><em>(X</em></strong>), <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a>, <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a>, <a href="https://discord.gg/in-plain-english-709094664682340443"><strong><em>Discord</em></strong></a><strong><em>.</em></strong></li><li><em>Check out our other platforms: </em><a href="https://stackademic.com/"><strong><em>Stackademic</em></strong></a>, <a href="https://cofeed.app/"><strong><em>CoFeed</em></strong></a>, <a href="https://venturemagazine.net/"><strong><em>Venture</em></strong></a>.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c4667d154992" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/django-orm-in-a-nutshell-c4667d154992">Django ORM in a Nutshell</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Age Calculator Using Tkinter In Python]]></title>
            <link>https://medium.com/@doroh_dev/building-age-calculator-using-tkinter-in-python-cbdabdd3ed07?source=rss-4ece44e4327d------2</link>
            <guid isPermaLink="false">https://medium.com/p/cbdabdd3ed07</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[tkinter]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[age]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[chepkirui dorothy]]></dc:creator>
            <pubDate>Wed, 25 Oct 2023 05:22:44 GMT</pubDate>
            <atom:updated>2023-10-25T05:22:44.687Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Yowt9-jde-_K6e8p" /><figcaption>Photo by <a href="https://unsplash.com/@sincerelymedia?utm_source=Hashnode&amp;utm_medium=referral">Sincerely Media</a> on <a href="https://unsplash.com/?utm_source=Hashnode&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Suppose we want to create an application whereby one can input their birthdate and the program will calculate their age.</h4><p>We will be building an age calculator using Tkinter. Tkinter is the standard library in Python used to create Graphical User interfaces (GUIs). We will also import the datetime module, which supplies classes for manipulating dates and times.</p><p><strong>Importing required modules</strong></p><p>We will first install the modules needed from the command line interface.</p><pre>pip install tkinter</pre><p><em>datetime</em> is a built-in Python module. We do not need to install it as it is already there.</p><p>Next, we import the modules in our code editor.</p><pre>from tkinter import *<br>from datetime import date, datetime</pre><p>We are importing all libraries in the <em>tkinter</em> module. We also import <em>date</em> and <em>datetime</em> libraries from <em>datetime</em> module.</p><p><strong>Designing the interface</strong></p><p>We will then design what our age calculator interface will look like. We will be using some of the tkinter widgets:</p><ul><li>Label — a widget used to specify the display boxes where we can place the text or images.</li><li>Button — is used to add buttons that can display texts or images that convey the purpose of the buttons.</li><li>Entry — a widget used to accept single-line text strings from a user.</li></ul><pre>root = Tk() #initializes tkinter to create display window<br>root.geometry(&#39;500x300&#39;) # width and height of the window<br>root.resizable(0, 0) # sets fix size of window<br>root.title(&#39; Age calculator&#39;) # gives the window a title<br><br>#the rest of the code<br>root.mainloop()</pre><p>We first create a tkinter instance called root, which aids in the display of the root window and manages all of the other tkinter application components. We then set the width and height of the window, and give it a title. The <em>mainloop()</em> method runs the script and displays the output window.</p><pre>yourAge = Label(root,fg=&quot;red&quot;,text = &quot;Date     Month     Year&quot;,font=&#39;arial 12 bold&#39;).place(x = 210)<br>setYourAlarm = Label(root,text = &quot;Enter birthday: &quot;,bg=&quot;grey&quot;,font=&quot;arial 11 bold&quot;).place(x=80, y=40)<br><br>date = StringVar()<br>month = StringVar()<br>year = StringVar()<br>dateTime= Entry(root,textvariable = date, relief = RAISED, width = 4,font=(20)).place(x=210,y=40)<br>monthTime= Entry(root,textvariable = month,width = 4,font=(20)).place(x=270,y=40)<br>yearTime = Entry(root,textvariable = year,width = 4,font=(20)).place(x=330,y=40)</pre><p>We create label widgets, which will display where the date, month, and year data will be input.</p><p><em>StringVar()</em> is used to edit a widget’s text, and determine whether they have been read, overwritten, or do not exist at all. We create entry widgets for the date, month, and year where one will input their birthday. <em>StringVar()</em> then holds the string data.</p><p><em>place()</em> method allows us to position our widgets by setting corresponding x and y values.</p><p>The interface so far looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/0*DccisgoFxk0zpsjx" /></figure><p><strong>Adding age function</strong></p><pre>def age():<br>    # Get current date<br>    today = datetime.today().date()<br><br>setAge_year = int(year.get())<br>    setAge_month = int(month.get())<br>    setAge_date = int(date.get())<br>    current_age = today.year-int(setAge_year)<br>    if today.month &lt; setAge_month or today.month == setAge_month and today.day &lt; setAge_date:<br>         current_age -= 1<br>    CurrentLabel = Label(root, text=f&#39;You are: {current_age} years old&#39;,fg=&#39;black&#39;)<br>    CurrentLabel.place(relx=0.2, rely=0.8, anchor=CENTER)</pre><p>We first define a function <em>age</em>. We then get the current date by using the <em>datetime</em> method. The function then gets the three entries and finds the difference between the current year and the input year. It then checks to make sure that the input month and date are greater than the current month and date. If not, it means the current age is less by one year.</p><p>We then create a label widget that will display the user’s age.</p><p><strong>Creating buttons</strong></p><p>We then create two buttons, one which the user clicks to get their age, and another which when clicked destroys the window.</p><pre>submit = Button(root,text = &quot;Calculate your age&quot;,fg=&quot;red&quot;,width = 20,command=age,font=(&quot;arial 15 bold&quot; )).place(x=90,y=100)<br>exit = Button(root,text = &quot;Exit&quot;,fg=&quot;red&quot;,width = 10,command=root.destroy,font=(&quot;arial 20 bold&quot; )).place(x=150,y=140)</pre><p>The final interface will be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/0*pgkws_KnhgvW30es" /></figure><p>When we input date, month, and year, it calculates the age.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/0*nt2cILD8EVbdriYH" /></figure><p>The complete code is:</p><pre>from tkinter import *<br>from datetime import date, datetime<br><br>root = Tk() #initializes tkinter to create display window<br>root.geometry(&#39;500x300&#39;) # width and height of the window<br>root.resizable(0, 0) # sets fix size of window<br>root.title(&#39; Age calculator&#39;) # gives the window a title<br><br>yourAge = Label(root,fg=&quot;red&quot;,text = &quot;Date     Month     Year&quot;,font=&#39;arial 12 bold&#39;).place(x = 210)<br>setYourAlarm = Label(root,text = &quot;Enter birthday: &quot;,bg=&quot;grey&quot;,font=&quot;arial 11 bold&quot;).place(x=80, y=40)<br>date = StringVar()<br>month = StringVar()<br>year = StringVar()<br>dateTime= Entry(root,textvariable = date, relief = RAISED, width = 4,font=(20)).place(x=210,y=40)<br>monthTime= Entry(root,textvariable = month,width = 4,font=(20)).place(x=270,y=40)<br>yearTime = Entry(root,textvariable = year,width = 4,font=(20)).place(x=330,y=40)<br>def age():<br>    # Get current date<br>    today = datetime.today().date()<br>    setAge_year = int(year.get())<br>    setAge_month = int(month.get())<br>    setAge_date = int(date.get())<br>    current_age = today.year-int(setAge_year)<br>    if today.month &lt; setAge_month or today.month == setAge_month and today.day &lt; setAge_date:<br>         current_age -= 1<br><br>    CurrentLabel = Label(root, text=f&#39;You are: {current_age} years old&#39;,fg=&#39;black&#39;)<br>    CurrentLabel.place(relx=0.2, rely=0.8, anchor=CENTER)<br>submit = Button(root,text = &quot;Calculate your age&quot;,fg=&quot;red&quot;,width = 20,command=age,font=(&quot;arial 15 bold&quot; )).place(x=90,y=100)<br>exit = Button(root,text = &quot;Exit&quot;,fg=&quot;red&quot;,width = 10,command=root.destroy,font=(&quot;arial 20 bold&quot; )).place(x=150,y=140)<br>root.mainloop()</pre><p><strong>Conclusion</strong></p><p>We have successfully created an age calculator in Python using <em>tkinter</em>. Happy coding.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cbdabdd3ed07" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a simple YouTube video downloader with python]]></title>
            <link>https://medium.com/@doroh_dev/build-a-simple-youtube-video-downloader-with-python-c4257a041bbf?source=rss-4ece44e4327d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c4257a041bbf</guid>
            <category><![CDATA[newprogrammer]]></category>
            <category><![CDATA[youtube-download]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[chepkirui dorothy]]></dc:creator>
            <pubDate>Wed, 25 Oct 2023 04:53:26 GMT</pubDate>
            <atom:updated>2023-10-25T05:25:17.367Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*twGW2jGdW7_kOu_a" /><figcaption>Photo by <a href="https://unsplash.com/@alexbemore?utm_source=Hashnode&amp;utm_medium=referral">Alexander Shatov</a> on <a href="https://unsplash.com/?utm_source=Hashnode&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Looking to create a simple YouTube video downloader? This article will show you how.</h3><p>If you have tried to download a YouTube video before, then you know the frustration of going through a million ads, just to get a two-megabyte file. In this article, we will create our own simple YouTube video downloader using Python.</p><p><strong>Requirements</strong></p><p>Before we begin, you should have:</p><ul><li>python. If not, follow <a href="https://www.python.org/downloads/">this</a> guide to install it.</li><li>a code editor</li><li>Pytube</li><li>Tkinter</li></ul><p>Pytube is a lightweight Python library for downloading YouTube videos. Tkinter is a standard GUI(graphical user interface) library for Python.</p><p>To install Pytube and Tkinter, run the following commands on the CLI (command line interface) using a pip installer.</p><pre>pppip install tk<br>Pip install pytube</pre><p>If you are using Python 2.x, install Tkinter as Tkinter (notice the uppercase T).</p><pre>pip install Tkinter</pre><p>We will follow the following steps in building a YouTube downloader:</p><ol><li>Import required libraries</li><li>Create display window</li><li>Create link entry</li><li>Create download function</li></ol><p><strong>Step 1: Import required libraries</strong></p><p>We need to import the modules that we installed.</p><pre>from tkinter import * # import all libraries from tkinter module<br>from pytube import YouTube # import YouTube library from pytube module</pre><p><strong>Step 2: Create a display window</strong></p><pre>root = Tk() # initializes tkinter to create display window<br>root.geometry(&#39;400x250&#39;) # width and height of the window<br>root.resizable(0, 0) # sets fix size of window<br>root.title(&#39; our awesome youtube downloader&#39;) # gives the window a title<br><br>Label(root,text = &#39;Youtube Video Downloader&#39;, font =&#39;arial 20 bold&#39;).pack()<br># The rest of the code <br>root.mainloop() # executes when we want to run the program</pre><ul><li>Label() widget above displays texts that users cannot modify.</li><li>root is the name of the window.</li></ul><p>When we run the code above, it gives us a blank window. The remaining code will go in between Tk() and mainloop(). The resulting window is as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/0*iLD_2lb_N0qEsot8" /></figure><p><strong>Step 3: Create link entry</strong></p><p>The next step is to create an entry where we can paste a YouTube link.</p><pre>var = StringVar() # specifies variable type<br>Label(root, text = &#39;Paste Link Here:&#39;, font = &#39;arial 15 bold&#39;).place(x= 100 , y = 60)<br><br>label = Message( root, textvariable = var, relief = RAISED )<br>link_enter = Entry(root, width = 70,textvariable = var).place(x = 32, y = 90)<br>var.set(&#39;Paste Link Here:&#39;)</pre><ul><li>var stores the URL entered as a string.</li><li>Entry() widget is used when we want to create a text field.</li><li>textvariable is used to obtain the current text variable’s value for the entry widget.</li><li>place() is used to position the widget at a certain location.</li></ul><p>The output of the above code is as shown in the picture below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/0*t9UVwFySGLlqZeHr" /></figure><p><strong>Step 4: Create a download function</strong></p><p>Now that we have our window up and running, we need to create a function to download the videos. We also need a button that, when clicked, will call this function.</p><pre>def Downloader():<br>    url =YouTube(str(var.get())) # gets youtube link from link entered and converts it to string<br>    video = url.streams.first() # video is downloaded in the first stream the video is in<br>    video.download() # initializes the download<br>    Label(root, text = &#39;DOWNLOADED&#39;, font = &#39;arial 15&#39;).place(x= 180 , y = 210) # shows &quot;DOWNLOADED&quot; when the download is complete<br>Button(root,text = &#39;DOWNLOAD&#39;, font = &#39;arial 15 bold&#39; ,bg = &#39;red&#39;, padx = 2, command = Downloader).place(x=180 ,y = 150)</pre><p>The function <em>Downloader</em> above takes a YouTube URL entered, looks for the first stream (360p, 720p,1080p e.t.c) and downloads the video. The final output is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/0*5Fa2PF8I6upEKxLE" /></figure><p>After pasting the URL as below, hit the <em>DOWNLOAD</em> button. Wait a few seconds, and you should have your video downloaded.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/0*LOLcOa9Ueeap4Jkb" /></figure><p><strong>Conclusion</strong></p><p>We have successfully developed a YouTube video downloader using Python. I hope this has been helpful. Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c4257a041bbf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting started with Django]]></title>
            <link>https://medium.com/@doroh_dev/getting-started-with-django-2f560f86c64?source=rss-4ece44e4327d------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f560f86c64</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[to-do-list]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[chepkirui dorothy]]></dc:creator>
            <pubDate>Tue, 02 Aug 2022 10:37:57 GMT</pubDate>
            <atom:updated>2022-08-02T10:37:57.100Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NfhL3MkSsJMj9iGz" /><figcaption>Photo by <a href="https://unsplash.com/@cgower?utm_source=medium&amp;utm_medium=referral">Christopher Gower</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Build a simple to-do list app.</h4><p>If you are comfortable with python language and looking to get into web development, Django is a perfect choice. In this tutorial, you will learn the fundamentals of Django programming by building a simple to-do list.</p><p><strong>What is Django?</strong></p><p>Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. Although it uses slightly different terminology, Django adheres to the MVC(Model-View-Controller) pattern closely. In its most basic form, Django is an MTV (Model-Template-View) framework. Django refers to Views as Templates and Controllers as Views. As a result, the Python code will be in views and models, while the HTML code will be in templates. Instagram and Pinterest are examples of big companies already running on Django.</p><p><strong>Why Django?</strong></p><ul><li>Fast. Django was developed to reduce the time developers took applications from concept to completion.</li><li>Secure. Django is serious about security and aids developers in avoiding many frequent security pitfalls.</li><li>Scalable. Some of the high-traffic websites developed using Django. Django can swiftly and adaptably scale the website to handle even the highest traffic demands.</li></ul><p><strong>Prerequisites</strong></p><ul><li>An understanding of python.</li><li>Python. To download, click <a href="https://www.python.org/downloads/">here</a></li><li>A code editor</li><li>Unix-based operating system</li><li>An understanding of HTML</li></ul><p><strong>Setting up the development environment</strong></p><p>A Django application should be developed and run in a separate environment. By creating a separate Python environment, you avoid installing Python packages on a global scale. First, create a new directory where your app will be stored.</p><pre>mkdir folder_name<br>cd folder_name</pre><p>(You can change <em>folder_name </em>to what you choose to name your folder). While inside <em>folder_name</em>, install virtualenv using Python installer *pip. Virtualenv is a tool for creating isolated virtual python environments.</p><pre>pip install virtualenv</pre><p>After the installation is complete, create a virtual environment.</p><pre>virtualenv venv</pre><p>Note that you can change the name <em>venv</em> to your preferred name. To activate, run the code below:</p><pre>source venv/bin/activate</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HObObuuZItdX-m96.png" /></figure><p>Now that the virtual environment is activated, you can create a Django project.</p><p><strong>Install Django</strong></p><p>To install Django, use the following command:</p><pre>pip install django</pre><p><strong>Start a Django project</strong></p><p>Now that we have Django installed, the next step is to create a project.</p><pre>django-admin startproject myproject</pre><p>The project’s name is <em>myproject</em>. You can change it to your preferred name.</p><p><strong>Project structure</strong></p><p>When a Django Project is created, it includes some basic files by default, such as <a href="http://manage.py/">manage.py</a>. To better understand its structure, here is what <em>myproject</em> looks like:</p><pre>.<br>├── manage.py<br>└── myproject<br>    ├── asgi.py<br>    ├── __init__.py<br>    ├── settings.py<br>    ├── urls.py<br>    └── wsgi.py</pre><p>The above files are:</p><p><a href="http://manage.py/"><strong>manage.py</strong></a><strong> </strong>— A command-line utility that allows you to interact with this Django project in a variety of ways.</p><p><strong>init.py </strong>— An empty file that instructs Python that this directory should be treated as a Python package.</p><p><a href="http://settings.py/"><strong>settings.py</strong></a> — This file contains all the website settings. Here, you can register applications you create, configure databases, etc.</p><p><a href="http://urls.py/"><strong>urls.py</strong></a><strong> </strong>— This file stores all links to the project.</p><p><a href="http://asgi.py/"><em>asgi.py</em></a><em> </em>and <a href="http://wsgi.py/"><em>wsgi.py</em></a><em> </em>are advanced at this point. Here is a basic definition.</p><p><a href="http://asgi.py/"><strong>asgi.py</strong></a> — An entry-point for ASGI-compatible web servers to serve your project.</p><p><a href="http://wsgi.py/"><strong>wsgi.py</strong></a> — This file is required for the WSGI deployment of the project. It is used to facilitate communication between your Django application and the web server.</p><p><strong>Making migrations</strong></p><p>Migrations are Django’s way of propagating changes you make to your models (adding a field, deleting a model, etc.) into your database schema. First, change the directory to where the project is. Make sure it has a <a href="http://manage.py/"><em>manage.py</em></a> file in it.</p><pre>cd myproject</pre><p>To make migrations:</p><pre>python manage.py migrate</pre><p>The command <em>migrate</em> applies and unapplies migrations in the database schema. Running the code above will give:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/0*ldWxEi6RJoSs3idA.png" /></figure><p><strong>Running server</strong></p><p>To confirm that everything works well, run the server.</p><pre>python manage.py runserver</pre><p>This gives the following output in the command line.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/0*wPv42nWSacesiKky.png" /></figure><p>The server is live. Visit <a href="http://127.0.0.1:8000/"><em>http://127.0.0.1:8000/</em></a> with your web browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qShFn6Istfrt57uJ.png" /></figure><p>Congratulations. You have successfully created a Django project.</p><p><strong>Creating a Django app</strong></p><p>A Django application is a Python package that is specifically intended for a Django project. You can have many Django apps under one project. Each app created is an independent module. Let’s create a simple to-do app.</p><pre>python manage.py startapp todo</pre><p>The to-do app directory is:</p><pre>.<br>├── db.sqlite3<br>├── manage.py<br>├── myproject<br>└── todo<br>    ├── admin.py<br>    ├── apps.py<br>    ├── __init__.py<br>    ├── migrations<br>    │   └── __init__.py<br>    ├── models.py<br>    ├── tests.py<br>    └── views.py</pre><p><a href="http://models.py/"><strong>models.py</strong></a> file contains the essential fields and behaviors of the data you’re storing.</p><p><a href="http://admin.py/"><strong>admin.py</strong></a><strong> </strong>file is the command-line utility for administrative duties in Django.</p><p><a href="http://views.py/"><strong>views.py</strong></a> file contains Python functions that take HTTP requests and return HTTP response, like HTML documents.</p><p><strong>Configure todo app</strong></p><p>To include the app in your project, add your project name to the INSTALLED_APPS list. To achieve that, open the <a href="http://settings.py/">settings.py</a> file in your code editor. Django automatically creates a list of apps it installs to the project.</p><pre>INSTALLED_APPS = [<br>    &#39;django.contrib.admin&#39;,<br>    &#39;django.contrib.auth&#39;,<br>    &#39;django.contrib.contenttypes&#39;,<br>    &#39;django.contrib.sessions&#39;,<br>    &#39;django.contrib.messages&#39;,<br>    &#39;django.contrib.staticfiles&#39;, <br>    &#39;todo&#39; # new app<br>]</pre><p><strong>Defining models</strong></p><p>A model is the single, definitive source of data information. It contains the data’s essential fields and behaviors. Each model corresponds to a single database table. Django comes with SQLite configured out of the box as its database. Other databases, such as Postgres, can be used. Designing a good data model is a make or break for any app. Take your time to visualize what your app will look like. Your to-do list app should contain:</p><ul><li>A title</li><li>When the task is created</li></ul><p>Open <a href="http://models.py/">models.py</a> in the editor. At a glance, it just looks like this:</p><pre>from django.db import models</pre><pre># Create your models here.</pre><p>Add the codes for your data models here.</p><pre>from django.db import models</pre><pre># Create your models here.</pre><pre>class TodoItem(models.Model):<br>    title = models.CharField(max_length=100)<br>    created = models.DateTimeField(auto_now_add = True)</pre><pre>def __str__(self):<br>        return self.title</pre><p>Great. You’ve defined one model class. The next step is to do the migrations by running two commands, <em>makemigrations </em>and <em>migrate</em>.</p><p><em>makemigrations</em> separates out your model changes into separate migration files, which is like commits, and <em>migrate</em> applies them to your database.</p><pre>python manage.py makemigrations<br>python manage.py migrate</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/0*iNV5auSGPDbBA-QK.png" /></figure><p><strong>Django admin interface</strong></p><p>Now that you have created the data model and database, you need to add data to the models. Luckily, the Django admin site provides a quick way to create some test data.</p><p>A superuser can only access the Django admin interface. A superuser is someone who can access the whole Django server. To create one:</p><pre>python manage.py createsuperuser</pre><p>Follow the prompts and you should be a superuser.</p><p>You then need to tell the admin that <em>TodoItem</em> has an admin interface by registering the models in <a href="http://admin.py/"><em>admin.py</em></a>.</p><pre>from django.contrib import admin<br>from .models import TodoItem<br># Register your models here.</pre><pre>admin.site.register(TodoItem)</pre><p>The admin interface app is ready. Make sure the server is running. On your browser, go to <a href="http://127.0.0.1:8000/admin"><em>127.0.0.1:8000/admin</em></a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/0*tKViX6bBdkTzZB-m.png" /></figure><p>Fill in the username and password that you had set up earlier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/0*g6BnuXBg3g1beQqO.png" /></figure><p>The admin interface has Todo items listed.</p><p>To create the first to-do item, click on <em>add</em>. This will give you an interface where you can add the title of the to-do item and save it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/0*pqTXMXKfs-U05pe4.png" /></figure><p>Create as many items as you can. You will use them in the testing process of the app interface.</p><p><strong>Django views</strong></p><p>Django views and templates are used to create the interface people will interact. You need to create a view function first, then pass the data to the template.</p><p>A view is a Python function that accepts a web request and delivers an appropriate web response. Anything that a web browser can show can be this response, including the HTML of a Web page, a redirect, a 404 error, an XML document, an image, etc.</p><p><strong>Types of views</strong></p><p>Views are implemented in two different ways:</p><ul><li>Using functions</li><li>Using classes</li></ul><p><strong>Function-based views(FBV)</strong></p><p>Function-based views are created by passing an HttpRequest object as a parameter to a Python function that produces a HttpResponse object. Function-based views are often classified into four fundamental techniques, namely, CRUD (Create, Retrieve, Update, Delete). CRUD is the foundation of any development framework. An example of FBV is:</p><pre>from django.http import HttpResponse</pre><pre># create a function<br>def home(request):</pre><pre>return HttpResponse(&quot;&lt;h1&gt;Hello world&lt;/h1&gt;&quot;)</pre><ul><li>First, you import class <em>HttpResponse</em> from <em>django.http</em> library.</li><li>Next, you define a function called home. Each view function accepts an <em>HttpRequest </em>object, commonly named request, as its first argument.</li><li>The created response is contained in a HttpResponse object that the view returns. Every view function must return a HttpResponse object.</li></ul><p><strong>Class based views (CBV)</strong></p><p>Class-based views offer an alternate method for implementing views as Python objects rather than functions. They do not replace function-based views, but they have several differences and advantages when compared to them. An example is:</p><pre>class MyCreateView(View):<br>  template_name = &#39;home.html&#39;<br>  form_class = MyForm</pre><p>where the template name is <em>home.html</em></p><p>In this tutorial, you will use function-based views.</p><p>It is time to define your first view. Open <a href="http://views.py/"><em>views.py</em></a> in your code editor and enter:</p><pre>from django.shortcuts import render<br>from .models import TodoItem</pre><pre># Create your views here.</pre><pre>def home(request):<br>    todo = TodoItem.objects.all()<br>    return render(request, &#39;home.html&#39;, { &#39;todo_list&#39;: todo })</pre><p><strong>Templates</strong></p><p>A template contains both the static and dynamic portions of the desired HTML output. A template in Django is basically a <em>.html</em> file written in HTML, CSS, and JavaScript.</p><p>Create a template folder in the root directory, the same folder where <a href="http://manage.py/"><em>manage.py</em></a> is.</p><pre>.<br>├── db.sqlite3<br>├── manage.py<br>├── myproject<br>├── templates<br>└── todo</pre><p>Add this to <a href="http://settings.py/"><em>settings.py</em></a>.</p><pre>TEMPLATES = [<br>    {<br>        &#39;BACKEND&#39;: &#39;django.template.backends.django.DjangoTemplates&#39;,<br>        &#39;DIRS&#39;: [BASE_DIR/&#39;templates&#39;], #here<br>        &#39;APP_DIRS&#39;: True,<br>        &#39;OPTIONS&#39;: {<br>            &#39;context_processors&#39;: [<br>                &#39;django.template.context_processors.debug&#39;,<br>                &#39;django.template.context_processors.request&#39;,<br>                &#39;django.contrib.auth.context_processors.auth&#39;,<br>                &#39;django.contrib.messages.context_processors.messages&#39;,<br>            ],<br>        },<br>    },<br>]</pre><p>The next thing is to create a base template that contains the code you want to appear on every page. Other HTML files will inherit this template.</p><p><strong>Create a base template</strong></p><p>In the templates folder, create a new file and name it <em>base.html</em></p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot; dir=&quot;ltr&quot;&gt;<br>  &lt;head&gt;<br>    &lt;!-- Required meta tags --&gt;<br>    &lt;meta charset=&quot;utf-8&quot;&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt;<br>    &lt;!--Simple.css--&gt;<br>    &lt;link rel=&quot;stylesheet&quot; href=&quot;https://cdn.simplecss.org/simple.min.css&quot;&gt;<br>    &lt;title&gt;Django To-do Lists&lt;/title&gt;</pre><pre>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;div class=&quot;container&quot;&gt;<br>    {% block content %}<br>          &lt;!-- For each page, this text will be replaced with alternative html code. --&gt;<br>    {% endblock %}<br>&lt;/div&gt;</pre><pre>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>A block is used to override certain elements of a template.</p><p>This means that you have a content block that is overridden by children who inherit from this template. You can achieve this by using the <em>extends </em>keyword in child templates.</p><p>Add a homepage template. In the same folder, create a new file and name it <em>home.html</em></p><pre>{% extends &quot;base.html&quot; %}<br>{% block content %}</pre><pre>{% if todo_list %}<br>&lt;h3&gt;Todo lists&lt;/h3&gt;<br>{% endif %}</pre><pre>&lt;div&gt;<br>  {% for todo in todo_list %}<br>  &lt;div style=&quot;padding:5px; margin-top:15px; border-width:0.5px;border-radius:15px; border-style:solid&quot;&gt;<br>      &lt;p &gt;{{ todo.id }} . {{ todo.title }}&lt;/p&gt;<br>      &lt;p&gt; &lt;span style=&quot;color:green;&quot;&gt;Created:&lt;/span&gt; {{todo.created}}&lt;/p&gt;</pre><pre>  &lt;/div&gt;<br>  {% empty %}<br>  &lt;h4&gt;You have no lists!&lt;/h4<br>  {% endfor %}<br>&lt;/div&gt;</pre><pre>{% endblock %}</pre><p>The first line of the code means that you are extending <em>base.html</em>, everything in <em>base.html</em> will be rendered in <em>home.html</em> excluding code between <em>{% block content %}</em> and <em>{% endblock %} </em>tags.</p><p>The next bit of code is an <em>if</em> statement that returns the heading <em>Todo list</em> if there is a list of to-do items. The heading won’t appear if the list is empty.</p><p>For loop is bracketed inside <em>{% for todo in todo_list %}</em> and <em>{% endfor %}</em> tags. <em>{% empty %}</em> tag lets you define what it should display when the list is empty.</p><p><em>{{ }}</em> syntax is used to interpolate a variable that has been declared as one of the built-in options or your own that you have constructed using any number of methods (models, view context, etc.). In <em>{{ todo.created }}</em>, you’re rendering the created property of the loop variable todo_list.</p><p><strong>URLs</strong></p><p>Each view in Django must be associated with a URL pattern. This is accomplished using the URLConf Python package (URL configuration). Every URLConf module must include the variable urlpatterns, which is a collection of URL patterns that must be matched against the requested URL. These patterns will be examined in order until the first match is discovered. The view associated with the first match is then triggered. Django launches an appropriate error handling view if no URL pattern matches.</p><p>The <a href="http://urls.py/"><em>urls.py</em></a> file is inside <em>myproject</em> folder. Open it and enter the following code:</p><pre>from django.contrib import admin<br>from django.urls import path<br>from todo import views</pre><pre>urlpatterns = [<br>    path(&#39;admin/&#39;, admin.site.urls),<br>    path(&#39;&#39;, views.home, name=&#39;home&#39;),<br>]</pre><p>The first path is auto-generated by Django. It renders the admin page. The second path is an empty path that tells Django to execute the <em>home</em> view.</p><p>Run the server. Enter <a href="http://127.0.0.1:8000/"><em>http://127.0.0.1:8000/</em></a> in your browser and the site will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/0*F96KL1mSSXrUBZ4o" /></figure><p><strong>Create tasks</strong></p><p>So far, your Todo app looks good. But it lacks functionality. You can’t add a task. Back to <a href="http://views.py/">views.py</a>. Define a function called add that takes a request as an argument.</p><pre>def add(request):<br>    title = request.POST[&quot;title&quot;]<br>    todo = TodoItem.objects.create(title=title)<br>    todo.save()<br>    return redirect(&quot;home&quot;)</pre><p><a href="http://request.post/"><em>request.POST</em></a> is a dictionary-like object that lets you access submitted data by a key name. Here, <a href="http://request.post/">request.POST</a>[‘title’] returns the title as a string. <em>TodoItem.objects.create</em> creates a new title. <em>todo.save() </em>saves the newly created title to the dictionary. Finally, it returns you back to home.</p><p>In <em>home.html</em>, add the following code right above <em>{% endblock %}</em> tag.</p><pre>&lt;form  action=&quot;/add&quot; method=&quot;post&quot;&gt;{% csrf_token %}<br>    &lt;div style=&quot;padding:5px; margin-top:15px; &quot; &gt;</pre><pre>        &lt;input type=&quot;text&quot; name=&quot;title&quot; placeholder=&quot;Enter a new task...&quot;&gt;<br>        &lt;br&gt;<br>    &lt;/div&gt;<br>    &lt;button  type=&quot;submit&quot;&gt;Add&lt;/button&gt;<br>&lt;/form&gt;</pre><p>You’ve created a element that, when the user submits it, will generate a POST request with the user-updated form data as part of its content. The action attribute specifies where to send the form data when a form is submitted. <em>{% csrf_token %}</em> prevents malicious attacks by generating a secure token.</p><p>Create a route that connects it to <em>add </em>views. In <a href="http://urls.py/"><em>urls.py</em></a>, add this below the other path.</p><pre>path(&#39;add&#39;, views.add, name=&#39;add&#39;),</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/0*cabUL06Ohe3cI233" /></figure><p><strong>Delete tasks</strong></p><p>To delete the tasks, first, create a <em>delete</em> function in <a href="http://views.py/">views.py</a>.</p><pre>def delete(request, todo_id):<br>    todo = TodoItem.objects.get(id=todo_id)<br>    todo.delete()<br>    return redirect(&quot;home&quot;)</pre><p>Django’s<em> get()</em> method returns a single object that matches the specified lookup parameter. The delete view gets <em>todo_id</em> as an argument, uses the id to locate the correct record, deletes that record and redirects the user back to the home view.</p><p>Updating the <a href="http://urls.py/"><em>urls.py</em></a>:</p><pre>path(&#39;delete/&lt;int:todo_id&gt;/&#39;, views.delete, name=&#39;delete&#39;),</pre><p>This locates individual <em>todo_id </em>which are integers.</p><p>Finally, in <em>home.html</em>, make changes by adding one line of code:</p><pre>&lt;div&gt;<br>  {% for todo in todo_list %}<br>  &lt;div style=&quot;padding:5px; margin-top:15px; border-width:0.5px;border-radius:15px; border-style:solid&quot;&gt;<br>      &lt;p &gt;{{ todo.id }} . {{ todo.title }}&lt;/p&gt;<br>      &lt;p&gt; &lt;span style=&quot;color:green;&quot;&gt;Created:&lt;/span&gt; {{todo.created}}&lt;/p&gt;<br>&lt;a class= &quot;btn btn-secondary&quot; href=&quot;/delete/{{ todo.id }}&quot;&gt;delete&lt;/a&gt; #new code for delete <br>  &lt;/div&gt;<br>  {% empty %}<br>  &lt;h4&gt;You have no lists!&lt;/h4<br>  {% endfor %}<br>&lt;/div&gt;</pre><p>The tag defines a hyperlink, which is used to link from one page to another. <em>href</em> attribute contains a link that shows the link destination.</p><p>Reload your browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/0*-cCFhTtEg-YQ5XEu" /></figure><p>Clicking the delete button will delete the task listed.</p><p>Congrats. You have successfully created a to-do list.</p><p><strong>Conclusion</strong></p><p>You’ve come a long way, from installing Django to building a Django application. To recap, you’ve learned how to:</p><ul><li>Create a virtual environment</li><li>Create new data using the Django admin interface</li><li>Structure data models</li><li>Use function-based views</li><li>Create URL configurations.</li><li>Use templates to display your lists</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f560f86c64" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>