<?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"><channel><title><![CDATA[How Rishabh Learnt]]></title><description><![CDATA[My journey of getting into Web development.]]></description><link>https://blog.therishabhdev.com</link><generator>RSS for Node</generator><lastBuildDate>Wed, 15 Apr 2026 13:51:04 GMT</lastBuildDate><atom:link href="https://blog.therishabhdev.com/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Go flow controls]]></title><description><![CDATA[Go flow controls
Just like any programming language Go also provides flow controls to control the program execution. In this post, I will be discussing if-else, for loop and switch statements.
If-else
If-else statement is used to execute only some sp...]]></description><link>https://blog.therishabhdev.com/go-flow-controls</link><guid isPermaLink="true">https://blog.therishabhdev.com/go-flow-controls</guid><category><![CDATA[golang]]></category><category><![CDATA[Beginner Developers]]></category><category><![CDATA[backend]]></category><category><![CDATA[Devops]]></category><category><![CDATA[coding]]></category><dc:creator><![CDATA[Rishabh Kumar Bahukhandi]]></dc:creator><pubDate>Sun, 12 Nov 2023 07:13:43 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1699699381558/23e5d165-78f7-4f95-a517-0e2ebfae6a56.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-go-flow-controls">Go flow controls</h1>
<p>Just like any programming language Go also provides flow controls to control the program execution. In this post, I will be discussing if-else, for loop and switch statements.</p>
<h2 id="heading-if-else">If-else</h2>
<p>If-else statement is used to execute only some specific code when a certain condition is <strong>true</strong>. You can also provide an else block that gets executed if the condition results in <strong>false.</strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1699729494246/77adbf3b-57c7-421e-bf2d-60041cebf728.png" alt class="image--center mx-auto" /></p>
<p><code>If-else</code> statements can also be chained together by putting an if statement in the <code>else</code> block of another <code>if</code> statement. Similarly, you can put one <code>if</code> statement in another <code>if</code> statement and this is called a nested <code>if</code> statement.</p>
<p>In Go syntax for writing an <code>if</code> statement is as follows:</p>
<p><code>if &lt;condition&gt; {</code></p>
<p><code>//Your code will come here</code></p>
<p><code>}</code></p>
<p>You can also add an initialization statement just before the condition.</p>
<p><code>if &lt;initialization&gt;; &lt;condition&gt; {</code></p>
<p><code>//Your code will come here</code></p>
<p><code>}</code></p>
<p>Observe that the condition is not enclosed in the parentheses. Also, the <code>else</code> keyword should come at the same line as the closing braces of <code>if</code> block.</p>
<p><mark>Note: Variables declared in the if statement are only available inside the if statement.</mark></p>
<h3 id="heading-code-example">Code example</h3>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> <span class="hljs-string">"fmt"</span>

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
<span class="hljs-comment">// if-else statement</span>
    <span class="hljs-keyword">var</span> a <span class="hljs-keyword">int</span> = <span class="hljs-number">6</span>
    <span class="hljs-keyword">if</span> a&lt;<span class="hljs-number">20</span>{
        fmt.Println(<span class="hljs-string">"A is less than 20"</span>)
    }<span class="hljs-keyword">else</span>{
        fmt.Println(<span class="hljs-string">"A is greater than 19"</span>)
    }


    <span class="hljs-comment">// if statement with initialization statement</span>
    <span class="hljs-keyword">if</span> x:=<span class="hljs-number">10</span>;x &gt; <span class="hljs-number">30</span> {
        fmt.Println(<span class="hljs-string">"x is greater than 5"</span>)
    } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> x &gt; <span class="hljs-number">5</span> {
        fmt.Println(<span class="hljs-string">"x is greater than 5 but not greater than 30"</span>)
    } <span class="hljs-keyword">else</span> {
        fmt.Println(<span class="hljs-string">"x is 5 or less"</span>)
    }

    <span class="hljs-comment">// nested if-else</span>
    y := <span class="hljs-number">10</span>

    <span class="hljs-keyword">if</span> y &gt; <span class="hljs-number">5</span> {
        fmt.Println(<span class="hljs-string">"x is greater than 5"</span>)
        <span class="hljs-keyword">if</span> y &gt; <span class="hljs-number">2</span> {
            fmt.Println(<span class="hljs-string">"x is greater than 2 but not greater than 5"</span>)
        } <span class="hljs-keyword">else</span> {
            fmt.Println(<span class="hljs-string">"x is 2 or less"</span>)
        }

    }
}
</code></pre>
<h2 id="heading-loop">Loop</h2>
<p>If you want to repeat something again and again, a loop is all that you need. All programming languages provide loops. Let's start with the for loop.</p>
<p>For loops have three components namely, initialization, condition and lastly update statement.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1699729510405/585b6add-1792-4241-b77a-a391936f2a8c.png" alt class="image--center mx-auto" /></p>
<p>The syntax for writing <strong>for loop in Go</strong> is as follows</p>
<p><code>for &lt;initialization&gt;;&lt;condition&gt;;&lt;updation&gt; {</code></p>
<p><code>//Your code comes here</code></p>
<p><code>}</code></p>
<p>Initialization and updation components of the loop are optional.</p>
<p>There is also another kind of loop called the <strong>while loop</strong>. While loop goes on running as long as the loop condition results in <strong><em>true.</em></strong></p>
<p>Syntax of while loop in Go</p>
<p><code>for &lt;condition&gt;{</code></p>
<p><code>// Your code comes here</code></p>
<p><code>}</code></p>
<p>Note here also the condition is not enclosed in parentheses</p>
<h3 id="heading-code-example-1">Code example</h3>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> <span class="hljs-string">"fmt"</span>

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    <span class="hljs-comment">// Basic for loop</span>
    <span class="hljs-keyword">for</span> i := <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">5</span>; i++ {
        fmt.Println(i)
    }
    <span class="hljs-comment">// for loop with only condition</span>
    count := <span class="hljs-number">5</span>
    <span class="hljs-keyword">for</span> ;count&gt;<span class="hljs-number">0</span>;{
        fmt.Println(count)
        count--
    }
    <span class="hljs-comment">// while loop</span>
    i := <span class="hljs-number">0</span>
    <span class="hljs-keyword">for</span> i &lt; <span class="hljs-number">5</span> {
        fmt.Println(i)
        i++
    }
}
</code></pre>
<h2 id="heading-switch-case">Switch-case</h2>
<p>The switch-case statement is a convenient way to write chained if-else statements. To write a switch statement you have to write <code>switch</code> keyword and provide a variable to it after that you write each case. Depending on which case matches with the variable, the code block gets executed. If none of the cases matches then control moves to the next statement. You can optionally provide a default case that gets executed when none of the cases matches.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1699729534832/bdbc87f5-309b-4317-a6b8-ea185790f1b6.png" alt class="image--center mx-auto" /></p>
<p>For the case value, you can provide a constant, a variable or even an expression. Here is the syntax for writing the switch-case statement:</p>
<p><code>switch &lt;variable&gt;{</code></p>
<p><code>case &lt;value&gt;:</code></p>
<p><code>//case code comes here</code></p>
<p><code>case &lt;value&gt;:</code></p>
<p><code>// case code comes here</code></p>
<p><code>...........// more cases can be written here</code></p>
<p><code>case default:</code></p>
<p><code>// default case code</code></p>
<p><code>}</code></p>
<p>Keep in mind that like other languages(C/C++, java, etc) you do not put a <code>break</code> at the end of each case. And if one case gets executed, rest of the cases are ignored, if you want to execute the rest of the cases use <code>fallthrough</code> keyword.</p>
<h3 id="heading-code-example-2">Code example</h3>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> <span class="hljs-string">"fmt"</span>

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    day := <span class="hljs-string">"Tuesday"</span>

    <span class="hljs-keyword">switch</span> day {
    <span class="hljs-keyword">case</span> <span class="hljs-string">"Monday"</span>:
        fmt.Println(<span class="hljs-string">"It's Monday."</span>)
    <span class="hljs-keyword">case</span> <span class="hljs-string">"Tuesday"</span>:
        fmt.Println(<span class="hljs-string">"It's Tuesday."</span>)
    <span class="hljs-keyword">case</span> <span class="hljs-string">"Wednesday"</span>:
        fmt.Println(<span class="hljs-string">"It's Wednesday."</span>)
    <span class="hljs-keyword">case</span> <span class="hljs-string">"Thursday"</span>:
        fmt.Println(<span class="hljs-string">"It's Thursday."</span>)
    <span class="hljs-keyword">case</span> <span class="hljs-string">"Friday"</span>:
        fmt.Println(<span class="hljs-string">"It's Friday."</span>)
    <span class="hljs-keyword">case</span> <span class="hljs-string">"Saturday"</span>:
        fmt.Println(<span class="hljs-string">"It's Saturday."</span>)
    <span class="hljs-keyword">case</span> <span class="hljs-string">"Sunday"</span>:
        fmt.Println(<span class="hljs-string">"It's Sunday."</span>)
    <span class="hljs-keyword">default</span>:
        fmt.Println(<span class="hljs-string">"Invalid day."</span>)
    }
}
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>So in this blog, I wrote about the control flow statements like if-else, loops and switch-case statements. You can combine these statements with different operators to write complex logic. So this was it for the control flow statement.</p>
<p>For related posts here is the <a target="_blank" href="https://rishabhdev.hashnode.dev/series/golang">link</a></p>
<p>For more updates subscribe to my newsletter.</p>
<h3 id="heading-like-share-and-comment-on-this-post-it-encourages-me-to-keep-writing-blog">Like, share and comment on this post, it encourages me to keep writing blog</h3>
<p>Give your feedback, it helps me to improve.</p>
<h3 id="heading-link-to-the-previous-posthttpsrishabhdevhashnodedevgo-operators"><a target="_blank" href="https://rishabhdev.hashnode.dev/go-operators">Link to the previous post</a></h3>
]]></content:encoded></item><item><title><![CDATA[How becoming a programming Tutor helped me]]></title><description><![CDATA[Becoming a programming tutor
Last year, I signed up for a tutoring platform, and this year, by some chance I got a student from the United Kingdom. And this is where my journey as a tutor started.
I had been learning programming and other tech-relate...]]></description><link>https://blog.therishabhdev.com/how-becoming-a-programming-tutor-helped-me</link><guid isPermaLink="true">https://blog.therishabhdev.com/how-becoming-a-programming-tutor-helped-me</guid><category><![CDATA[Programming Blogs]]></category><category><![CDATA[Tutorial]]></category><category><![CDATA[Python]]></category><category><![CDATA[Java]]></category><category><![CDATA[beginner]]></category><dc:creator><![CDATA[Rishabh Kumar Bahukhandi]]></dc:creator><pubDate>Fri, 27 Oct 2023 17:02:13 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1697882909049/c6843515-bb51-4440-8501-6213d0d50de0.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-becoming-a-programming-tutor">Becoming a programming tutor</h1>
<p>Last year, I signed up for a tutoring platform, and this year, by some chance I got a student from the United Kingdom. And this is where my journey as a tutor started.</p>
<p>I had been learning programming and other tech-related stuff like how technologies work under the hood. Though I was working as a freelance web developer, I still felt like I was missing something, I was learning but not progressing much.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698424782844/448d411c-a7ae-4c81-ba59-0c98efaa64e6.jpeg" alt /></p>
<h2 id="heading-learning-and-building-skills">Learning and building skills</h2>
<p>I used to spend hours every day focussing on web development. My knowledge was increasing. I was trying different things and also, every couple of months I used to go back to the basics, like programming language, frameworks, etc. I was building projects and all.</p>
<h2 id="heading-got-a-message-for-a-tutoring-session">Got a message for a tutoring session</h2>
<p>3rd March 2023, I got a message from a software engineering student for learning Python. I scheduled a demo session so that I could talk to him and understand the problems he faced. It was a good session. I showed him how I would be teaching him programming. He knew what was going on but struggled with practical coding. So, we started to work on it. Slowly building the foundations and writing codes.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698424826615/14ba3024-8a14-431a-bb7b-1eded8174126.jpeg" alt /></p>
<h2 id="heading-the-result-of-our-efforts">The result of our efforts</h2>
<p>He passed the subject successfully. Though it was focused on data structures and algorithms. But, since he understood Python properly he was able to come up with the solutions for the problems.</p>
<p>After this, he and some of his friends started learning Java from me. I started my programming journey with Java when I was in school. But by teaching it I learned something amazing, that I hadn't paid attention to earlier.</p>
<h2 id="heading-teaching-others-taught-me">Teaching others taught me</h2>
<p>As I was teaching Object Oriented Programming, I observed and realized how the frameworks work, and how inheritance and abstraction are used and this was an eye-opener for me. Learning something and understanding what, how, why and when of something are very different. This teaching experience helped me to become better.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698425698065/0ad3044e-1314-4db2-8500-d00cc299897c.jpeg" alt /></p>
<h2 id="heading-feeling-good-for-helping-others">Feeling good for helping others</h2>
<p>I taught two students Object Oriented Programming with Java. One of them scored above 80 out of 100 and the other one scored above 90 out of 100. By watching them grow and improve, it made me excited to share more of my knowledge with them. They benefitted from my learning and it was a big win for me. More importantly, it made me happy.</p>
<h2 id="heading-got-more-students">Got more students</h2>
<p>Through that same platform I got another student but this time it was a 14-year-old child. I wasn't sure, whether I would be able to teach a young child or not. So, I just accepted it and we had a demo session. It wasn't how I expected it to be, it was kind of good. Since he was a school student and not a college undergraduate, I had to be more cautious and understanding.</p>
<p>My main objective was to teach him Python in the simplest way possible. After a few lessons I observed that, to make him comfortable with coding I had to give him challenging coding tasks. So, we spent a couple of sessions just coding programs one after another.</p>
<p>So I would just explain to him what he has to do and he would try it on his own. I explained to him how to think about writing programs and how to visualize them and we covered some basic algorithms.</p>
<p>Later on, I got suggested to more students through word of mouth(recommendations from the people I taught).</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>So I will conclude by saying whatever you learn, find people who are interested in learning it and if possible teach them. It gives you a new perspective and sometimes it also challenges you to explain a complex concept simply. Well, sometimes I do struggle to explain some concepts because in my mind I can visualize them, so I try different ways to explain and observe what explanation is easiest to understand.</p>
<p>I would recommend everyone if possible to give it a try, not to create a livelihood out of it but to gain some experience of teaching.</p>
<h3 id="heading-if-you-liked-reading-this-article-give-it-a-like-and-share-it-with-someone-who-may-find-it-useful">If you liked reading this article, <mark>give it a like and share it with someone who may find it useful</mark>.</h3>
<h3 id="heading-for-more-updates-subscribe-to-my-newsletter">For more updates <mark>subscribe</mark> to my newsletter.</h3>
]]></content:encoded></item><item><title><![CDATA[Go operators]]></title><description><![CDATA[Operators are used to perform mathematical or logical operations. Go provides several operators that can be categorized into various groups like arithmetic operators, comparison(relational) operators, assignment operators, logical operators, bitwise ...]]></description><link>https://blog.therishabhdev.com/go-operators</link><guid isPermaLink="true">https://blog.therishabhdev.com/go-operators</guid><category><![CDATA[Go Language]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[backend]]></category><category><![CDATA[learning]]></category><category><![CDATA[coding]]></category><dc:creator><![CDATA[Rishabh Kumar Bahukhandi]]></dc:creator><pubDate>Fri, 20 Oct 2023 14:00:12 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1697804126040/4118d9d7-6970-47a2-8e94-8e81a8129aea.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Operators are used to perform mathematical or logical operations. Go provides several operators that can be categorized into various groups like arithmetic operators, comparison(relational) operators, assignment operators, logical operators, bitwise operators and miscellaneous operators.</p>
<p>Let's have a quick look at these operators and their uses.</p>
<h2 id="heading-arithmetic-operators">Arithmetic Operators</h2>
<p>These operators are used for performing mathematical operations like addition, subtraction, multiplication, division and modulus.</p>
<p>For those who are new to programming, modulus operators return the remainder of a division operation.</p>
<p>The code snippet below shows how to use arithmetic operators.</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main
<span class="hljs-keyword">import</span> <span class="hljs-string">"fmt"</span>

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">var</span> a <span class="hljs-keyword">int</span> = <span class="hljs-number">20</span>
    <span class="hljs-keyword">var</span> b <span class="hljs-keyword">int</span> = <span class="hljs-number">30</span>
    <span class="hljs-comment">// Addition</span>
    fmt.Println(a + b)
    <span class="hljs-comment">// prints 50</span>

    <span class="hljs-comment">// Subtraction</span>
    fmt.Println(b - a)
    <span class="hljs-comment">// prints 10</span>

    <span class="hljs-comment">// Multiplication</span>
    fmt.Println(a * b)
    <span class="hljs-comment">//prints 600</span>

    <span class="hljs-comment">// Division</span>
    fmt.Println(b / a)
    <span class="hljs-comment">// prints 1, (logically it should be 1.5) reason is given below</span>

    <span class="hljs-comment">// Modulus</span>
    fmt.Println(b % a)
    <span class="hljs-comment">// prints 10</span>
}
</code></pre>
<p>All the results were as per expectation but the division returned the value 1.</p>
<p>The reason for this behavior is that, for the result to be a floating point number both the operands must be of a float type.</p>
<h2 id="heading-comparison-operators">Comparison Operators</h2>
<p>Comparison operators are also called as the relational operators. These operators are used to compare two values. Comparison operators include equality, inequality, less than, less than equal to, greater than and greater than equal to. These operations result in a boolean value i.e. either true or false.</p>
<p>The usage of these operators is demonstrated below.</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main
<span class="hljs-keyword">import</span> fmt

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span>{
 <span class="hljs-comment">// Equality check</span>
    fmt.Println(a==b);
    <span class="hljs-comment">// results in false</span>

    <span class="hljs-comment">// inequality check</span>
    fmt.Println(a!=b)
    <span class="hljs-comment">//results in true</span>

    <span class="hljs-comment">// less than </span>
    fmt.Println(a&lt;b)
    <span class="hljs-comment">// results in true</span>

    <span class="hljs-comment">// less than or equal to </span>
    fmt.Println(a&lt;=b)
    <span class="hljs-comment">//results in true</span>

    <span class="hljs-comment">// greater than</span>
    fmt.Println(a&gt;b)
    <span class="hljs-comment">// results in false</span>

    <span class="hljs-comment">// greater than or equal to</span>
    fmt.Println(a&gt;=b)
    <span class="hljs-comment">// results in false</span>
}
</code></pre>
<h2 id="heading-assignment-operators">Assignment operators</h2>
<p>The assignment operator is used to assign value to a variable. Assignment operators can also be combined with operators for some common combination of operations like add and assign value( += ), subtract and assign value( -= ) and so on.</p>
<p>All of the assignment operators are listed below.</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main
<span class="hljs-keyword">import</span> <span class="hljs-string">"fmt"</span>

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span>{
    <span class="hljs-keyword">var</span> a <span class="hljs-keyword">float32</span> = <span class="hljs-number">10</span>
        fmt.Println(<span class="hljs-string">"Initial Value of a:"</span>,a)
        <span class="hljs-comment">// Add and assign</span>
        a += <span class="hljs-number">5</span>
        <span class="hljs-comment">// is equivalent to a = a + b</span>
        fmt.Println(<span class="hljs-string">"Value of a after adding 5:"</span>,a)

        <span class="hljs-comment">// subtract and assign</span>
        a -= <span class="hljs-number">5</span>
        <span class="hljs-comment">// is equivalent to a = a - b</span>
        fmt.Println(<span class="hljs-string">"Value of a after subtracting 5:"</span>,a)

        <span class="hljs-comment">// Multiply and assign</span>
        a *= <span class="hljs-number">5</span>
        <span class="hljs-comment">// is equivalent to a = a * 5</span>
        fmt.Println(<span class="hljs-string">"Value of a after multiplying by 5:"</span>,a)

        <span class="hljs-comment">// Divide and assign</span>
        a /= <span class="hljs-number">5</span>
        <span class="hljs-comment">// is equivalent to a = a / 5</span>
        fmt.Println(<span class="hljs-string">"Value of a after dividing by 5:"</span>,a)
}
</code></pre>
<h2 id="heading-logical-operators">Logical Operators</h2>
<p>Logical operators are used to combine conditional expressions. AND, OR and NOT are logical operations with the following properties.</p>
<h3 id="heading-and">AND</h3>
<p><strong>Logical AND</strong> results in <code>true</code> only when both conditions are <code>true</code>, otherwise it results in a false.</p>
<p><code>&lt;condition 1&gt; &amp;&amp; &lt;condition 2&gt;</code></p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Condition 1</td><td>Condition2</td><td>Result</td></tr>
</thead>
<tbody>
<tr>
<td>true</td><td>true</td><td>true</td></tr>
<tr>
<td>true</td><td>false</td><td>false</td></tr>
<tr>
<td>false</td><td>true</td><td>false</td></tr>
<tr>
<td>false</td><td>false</td><td>false</td></tr>
</tbody>
</table>
</div><h3 id="heading-or">OR</h3>
<p><strong>Logical OR</strong> results in <code>false</code> only if both conditions are <code>false</code>, otherwise it results in <code>true</code>.</p>
<p><code>&lt;condition 1&gt; || &lt;condition 2&gt;</code></p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Condition 1</td><td>Condition2</td><td>Result</td></tr>
</thead>
<tbody>
<tr>
<td>true</td><td>true</td><td>true</td></tr>
<tr>
<td>true</td><td>false</td><td>true</td></tr>
<tr>
<td>false</td><td>true</td><td>true</td></tr>
<tr>
<td>false</td><td>false</td><td>false</td></tr>
</tbody>
</table>
</div><h3 id="heading-not">NOT</h3>
<p><strong>Logical NOT negates the value from true to false and vice versa</strong></p>
<p><code>!&lt;condition&gt;</code></p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Condition</td><td>result</td></tr>
</thead>
<tbody>
<tr>
<td>true</td><td>false</td></tr>
<tr>
<td>false</td><td>true</td></tr>
</tbody>
</table>
</div><p><strong>Using logical AND (&amp;&amp;)</strong></p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> <span class="hljs-string">"fmt"</span>

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span>{
    <span class="hljs-keyword">var</span> a <span class="hljs-keyword">int</span> = <span class="hljs-number">10</span>
    <span class="hljs-keyword">var</span> b <span class="hljs-keyword">int</span> = <span class="hljs-number">15</span>
    <span class="hljs-comment">// combining two conditions together</span>
    <span class="hljs-keyword">if</span> a&lt;<span class="hljs-number">20</span> &amp;&amp; a&gt;<span class="hljs-number">5</span>{
        fmt.Println(<span class="hljs-string">"A is greater than 5 and less than 20"</span>)
    }<span class="hljs-keyword">else</span>{
        fmt.Println(<span class="hljs-string">"A is either less than 6 or A is greater than 19"</span>)
    }
}
</code></pre>
<p><strong>Using logical OR ( || )</strong></p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> <span class="hljs-string">"fmt"</span>

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span>{
    <span class="hljs-keyword">var</span> a <span class="hljs-keyword">int</span> = <span class="hljs-number">10</span>
    <span class="hljs-keyword">var</span> b <span class="hljs-keyword">int</span> = <span class="hljs-number">15</span>
    <span class="hljs-comment">// combining two conditions together with ||</span>
    <span class="hljs-keyword">if</span> a&gt;<span class="hljs-number">20</span> || a&lt;<span class="hljs-number">5</span>{
        fmt.Println(<span class="hljs-string">"A is less than 5 or greater than 20"</span>)
    }<span class="hljs-keyword">else</span>{
        fmt.Println(<span class="hljs-string">"A is greater than 4 and A is less than 21"</span>)
    }
}
</code></pre>
<p><strong>Using logical NOT ( ! )</strong></p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main
<span class="hljs-keyword">import</span> <span class="hljs-string">"fmt"</span>

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span>{
    <span class="hljs-keyword">var</span> isActive <span class="hljs-keyword">bool</span> = <span class="hljs-literal">false</span>
    <span class="hljs-keyword">if</span> !isActive{
        fmt.Println(isActive)
        isActive = !isActive
    }
    fmt.Println(!isActive)
}
</code></pre>
<h2 id="heading-bitwise-operators">Bitwise Operators</h2>
<p>Bitwise operators perform operations at the bit level. Bitwise operations are faster than normal operations since they directly manipulate the bits. Bitwise operators include bitwise AND ( &amp; ), bitwise OR ( | ), bitwise XOR ( ^ ), bitwise clear ( &amp;^ ), left shift( &lt;&lt; ) and right shift ( &gt;&gt; ).</p>
<h3 id="heading-bitwise-and-truth-table">Bitwise AND truth table</h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td>bit 1</td><td>bit 2</td><td>result bit</td></tr>
</thead>
<tbody>
<tr>
<td>1</td><td>1</td><td>1</td></tr>
<tr>
<td>1</td><td>0</td><td>0</td></tr>
<tr>
<td>0</td><td>1</td><td>0</td></tr>
<tr>
<td>0</td><td>0</td><td>0</td></tr>
</tbody>
</table>
</div><h3 id="heading-bitwise-or-truth-table">Bitwise OR truth table</h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td>1</td><td>1</td><td>1</td></tr>
</thead>
<tbody>
<tr>
<td>1</td><td>0</td><td>1</td></tr>
<tr>
<td>0</td><td>1</td><td>1</td></tr>
<tr>
<td>0</td><td>0</td><td>0</td></tr>
</tbody>
</table>
</div><h3 id="heading-bitwise-xor-truth-table">Bitwise XOR truth table</h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td>1</td><td>1</td><td>0</td></tr>
</thead>
<tbody>
<tr>
<td>1</td><td>0</td><td>1</td></tr>
<tr>
<td>0</td><td>1</td><td>1</td></tr>
<tr>
<td>0</td><td>0</td><td>0</td></tr>
</tbody>
</table>
</div><h3 id="heading-bitwise-and-not-bit-clear-amp-operator">Bitwise AND NOT (Bit clear &amp;^) Operator</h3>
<p>This operator is used to unset the specific bits. Observe the following example.</p>
<p><code>result = number1 &amp;^ number2</code></p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Number 1</td><td>1</td><td>1</td><td>0</td></tr>
</thead>
<tbody>
<tr>
<td>Number 2</td><td>0</td><td>1</td><td>0</td></tr>
<tr>
<td>Result</td><td>1</td><td>0</td><td>0</td></tr>
</tbody>
</table>
</div><p>Therefore, <code>result = 1 0 0</code></p>
<p>In short, this operator takes the number2 and inverts its bits, then it performs the bitwise &amp; on the number1 and the inverted number2.</p>
<p>The effect of this operation is that for every set bit of number2, the corresponding bit of number1 will be unset.</p>
<h3 id="heading-shift-operators">Shift Operators</h3>
<p><strong>Left shift ( &lt;&lt; )</strong></p>
<p>This operator shifts the bits of the operand by a specified number to the left and adds that many zeroes at the end of the number.</p>
<p>Example: shifting bits of 101110 to the left by 2</p>
<p><code>result = 101110&lt;&lt;2</code></p>
<p><code>result = 111000</code></p>
<p>n&lt;&lt;k is equivalent to n*2^k</p>
<p><mark>Shifting bits of a number n to the left by k is equivalent to multiplying the number by 2^k</mark></p>
<p><strong>Right shift ( &gt;&gt; )</strong></p>
<p>This operator shifts the bits of the operand by a specified number to the right and adds that many zeroes at the beginning of the number.</p>
<p>Example: shifting bits of 101110 to right by 2</p>
<p><code>result = 101110&gt;&gt;2</code></p>
<p><code>result = 001011</code></p>
<p>n&gt;&gt;k is equivalent to the floor of n/(2^k)</p>
<p><mark>Shifting the bits of a number to the right by k is equivalent to the floor of the division of the number by 2^k.</mark></p>
<h2 id="heading-miscellaneous-operators">Miscellaneous Operators</h2>
<p>Address operator ( &amp; )</p>
<p>if you put &amp; in front of an addressable operand of type T, it will give you a pointer of type T to its address location. You can store or pass the address of a struct instance to a function.</p>
<p>Receiver operator ( &lt;- )</p>
<p>This operator is used for passing values between concurrently running goroutines. In the upcoming Go concurrency-related posts I will discuss this operator.</p>
<h3 id="heading-references">References</h3>
<p>To read more about Golang operators you can use the following.</p>
<p>Go specifications - <a target="_blank" href="https://go.dev/ref/spec#Operators">Operators</a></p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>This post was a quick overview of the operators in Go. Being aware of all the operators provided by a programming language is crucial to utilize all the features of the language. I hope this post will help you in your Go learning journey. Comment and share your learnings.</p>
<h2 id="heading-subscribe-to-my-newsletter-for-more-updates"><mark>Subscribe to my newsletter for more updates</mark></h2>
<h2 id="heading-like-share-and-follow-my-blog-for-web-development-related-content"><mark>Like</mark>, <mark>share</mark> and <mark>follow</mark> my blog for Web development-related content.</h2>
<h3 id="heading-the-link-to-my-previous-blog-is-herehttpsrishabhdevhashnodedevlearning-go-basic-2">The link to my previous blog is <a target="_blank" href="https://rishabhdev.hashnode.dev/learning-go-basic-2">here</a></h3>
]]></content:encoded></item><item><title><![CDATA[Go data types, type casting and constants]]></title><description><![CDATA[Data types, type casting and constants
This blog is in continuation with the previous blog, where I discussed variables and functions in Golang. In this blog, I will be discussing the various data types in Go and the constants. For the previous post,...]]></description><link>https://blog.therishabhdev.com/go-data-types-type-casting-and-constants</link><guid isPermaLink="true">https://blog.therishabhdev.com/go-data-types-type-casting-and-constants</guid><category><![CDATA[Programming Blogs]]></category><category><![CDATA[Go Language]]></category><category><![CDATA[Beginner Developers]]></category><category><![CDATA[backend]]></category><category><![CDATA[Developer]]></category><dc:creator><![CDATA[Rishabh Kumar Bahukhandi]]></dc:creator><pubDate>Fri, 13 Oct 2023 14:00:12 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1696583428035/6ce7fdb5-b2ea-4242-97c5-6205f9356498.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-data-types-type-casting-and-constants">Data types, type casting and constants</h1>
<p>This blog is in continuation with the previous blog, where I discussed variables and functions in Golang. In this blog, I will be discussing the various data types in Go and the constants. For the previous post, the link is <a target="_blank" href="https://hashnode.com/post/clna4q41x000109kygl5k13pn">here</a>.</p>
<h2 id="heading-data-types">Data types</h2>
<p>Data types define what kind of data is stored inside a variable and what operations can be performed on it. For example, if I want to store a number without any fractional part, I will use an integer data type, for real numbers(numbers with fractional part), I will use float/double data type and so on.</p>
<h3 id="heading-list-of-data-types-in-go">List of Data types in Go</h3>
<h3 id="heading-numbers">Numbers</h3>
<ol>
<li><p>Integer</p>
<ul>
<li><p><code>int</code>, <code>int8</code>, <code>int16</code>, <code>int32</code>, <code>int64</code></p>
</li>
<li><p><code>uint</code>, <code>uint8</code>, <code>uint16</code>, <code>uint32</code>, <code>uint64</code>, <code>uintptr</code></p>
</li>
</ul>
</li>
<li><p>Float</p>
<ul>
<li><code>float32</code>, <code>float64</code></li>
</ul>
</li>
<li><p>Complex</p>
<ul>
<li><code>complex64</code>, <code>complex128</code></li>
</ul>
</li>
<li><p>Byte</p>
<ul>
<li><code>byte</code> (alias for <code>uint8</code>)</li>
</ul>
</li>
<li><p>Rune</p>
<ul>
<li><code>rune</code> (alias for <code>int32</code>) for storing unicode character</li>
</ul>
</li>
</ol>
<h3 id="heading-text">Text</h3>
<p>String</p>
<ol>
<li><ul>
<li><code>string</code> is a sequence of bytes.</li>
</ul>
</li>
</ol>
<h3 id="heading-boolean">Boolean</h3>
<p><code>bool</code> can store either a <code>true</code> or <code>false</code>.</p>
<h2 id="heading-types-to-be-discussed-in-later-posts">Types to be discussed in later posts</h2>
<h3 id="heading-array">Array</h3>
<p>Array denotes a numbered sequence of elements of a single type. Arrays have fixed size. Once created you cannot change the maximum size of the array. Arrays are 0 indexed.</p>
<h3 id="heading-slice">Slice</h3>
<p>Slices are just a section of an array. In Go, slices are used for creating dynamic arrays. Slice has size and capacity.</p>
<h3 id="heading-custom-data-type">Custom Data type</h3>
<p>You can create custom data types by combining different data types using <code>struct</code>, I will discuss the struct in the upcoming blog posts.</p>
<h2 id="heading-using-data-types">Using data types</h2>
<p>In Go, while creating the variable, after writing the variable name we write the data type that can be any of the above-mentioned as well as user-defined structs.</p>
<pre><code class="lang-go"><span class="hljs-keyword">import</span> <span class="hljs-string">"fmt"</span>
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span>{
    <span class="hljs-keyword">var</span> age <span class="hljs-keyword">uint</span> = <span class="hljs-number">16</span>
<span class="hljs-comment">//  age is a value that can hold a uint value</span>
    <span class="hljs-keyword">var</span> name <span class="hljs-keyword">string</span> = <span class="hljs-string">"Rishabhdev"</span>
<span class="hljs-comment">//  name is a variable that holds sequence of characters(string)</span>
    <span class="hljs-keyword">var</span> pi <span class="hljs-keyword">float64</span> = <span class="hljs-number">3.14</span>
<span class="hljs-comment">//  pi is a variable of float64 type</span>
    <span class="hljs-keyword">var</span> isStudent <span class="hljs-keyword">bool</span> = <span class="hljs-literal">true</span>
    fmt.Println(<span class="hljs-string">"Age:"</span>,age)
    fmt.Println(<span class="hljs-string">"Name:"</span>,name)
    fmt.Println(<span class="hljs-string">"is Student:"</span>,isStudent)
    fmt.Println(<span class="hljs-string">"Value of Pi:"</span>,pi)
}
</code></pre>
<p>Similarly, you can create a variable with any data type.</p>
<h2 id="heading-constants">Constants</h2>
<p>Constants are the named values that cannot be changed. The rules for naming constants are the same as variables, usually, constants' names are capitalized to differentiate them from the variables. If you provide the data type to a constant then it is called a <strong>Typed constant</strong> and if you do not provide the data type to the constant then it is an <strong>Untyped constant.</strong> Constants are declared using the <code>const</code> keyword then followed by the constant name and type.</p>
<p>Typed constant syntax</p>
<p><code>const &lt;name&gt; &lt;type&gt; = &lt;value&gt;</code></p>
<p>Untyped constant syntax</p>
<p><code>const &lt;name&gt; = &lt;value&gt;</code></p>
<h3 id="heading-using-constants">Using constants</h3>
<p>The following code shows how to create constants in Go.</p>
<p>Typed constants example</p>
<pre><code class="lang-go"><span class="hljs-keyword">const</span> TEAM_SIZE <span class="hljs-keyword">uint</span> = <span class="hljs-number">12</span>

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span>{
    fmt.Println(<span class="hljs-string">"Maximum number of players in the Team:"</span>,TEAM_SIZE)
}
</code></pre>
<p>Untyped constant example</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span>{
    <span class="hljs-keyword">const</span> PI = <span class="hljs-number">3.14159265359</span>
    fmt.Println(PI)
}
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Having knowledge of data types is very important. Using constants is also important to stop certain values from changing. In the upcoming blog, I will be discussing <strong>Operators in Go.</strong> I will be showing you different kinds of operators in Go namely arithmetic, comparison, logical, assignment and bitwise operators.</p>
<p>Keep supporting me by reacting and commenting on my blog posts. This encourages me to keep on writing more blogs.</p>
<p><mark>Link to previous blog is</mark> <a target="_blank" href="https://rishabhdev.hashnode.dev/learning-go-basics-1">here</a></p>
<h2 id="heading-follow-like-share-and-subscribe-to-the-newsletter-for-upcoming-blog-posts"><strong><mark>Follow, like, share and subscribe to the newsletter for upcoming blog posts.</mark></strong></h2>
]]></content:encoded></item><item><title><![CDATA[Go variables and functions]]></title><description><![CDATA[Go variables and functions
Introduction
Go a.ka. golang is a statically-typed compiled high-level programming language as you can find on google yourself. Now let's look at some other aspects of go. Go is a procedural language which means that we def...]]></description><link>https://blog.therishabhdev.com/go-variables-functions</link><guid isPermaLink="true">https://blog.therishabhdev.com/go-variables-functions</guid><category><![CDATA[Go Language]]></category><category><![CDATA[golang]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[General Programming]]></category><category><![CDATA[Web Development]]></category><dc:creator><![CDATA[Rishabh Kumar Bahukhandi]]></dc:creator><pubDate>Tue, 03 Oct 2023 09:40:38 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1696091094313/5b721ecd-33f3-417d-b3e7-b8779cb1c654.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-go-variables-and-functions">Go variables and functions</h1>
<h2 id="heading-introduction">Introduction</h2>
<p>Go a.ka. golang is a statically-typed compiled high-level programming language as you can find on google yourself. Now let's look at some other aspects of go. Go is a procedural language which means that we define a series of instructions called procedures to create programs. It supports concurrency in the form of go routine which are light-weight threads. It is a modern programming language developed by Ken Thompson, Robe Pike, and Robert Griesemer in 2007 and released in 2009 as an open-source programming language.</p>
<h2 id="heading-use-cases">Use Cases</h2>
<p>Go is a very fast language and it has built-in support for network programming and concurrency. Some of the major use cases of go are the following.</p>
<ul>
<li><p><strong>DevOps and Cloud computing:</strong> Many of the DevOps tools like docker, Kubernetes, Graphana, Prometheus, etc. are written in Go.</p>
</li>
<li><p><strong>Web Development</strong>: Golang is being used to write high-performance backends. Frameworks like fiber and gin can be used to build backends in Go. Go is also widely used to build microservices.</p>
</li>
</ul>
<p>Other than these two, you can do almost anything with Go.</p>
<h2 id="heading-basics-variables">Basics: Variables</h2>
<p>Variables are named locations in the computer memory where you can store data. You can access the value using the name of the variable. To create variables in go look at the following code snippet.</p>
<pre><code class="lang-go"><span class="hljs-comment">// This the main function where the program execution begins</span>
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span>{
    <span class="hljs-comment">// Now I am creating a variable named 'name' of type string</span>
    <span class="hljs-comment">// with value Rishabh</span>
    <span class="hljs-keyword">var</span> name <span class="hljs-keyword">string</span> = <span class="hljs-string">"Rishabh"</span>
}
</code></pre>
<p>So the basic syntax is as follows</p>
<pre><code class="lang-go"><span class="hljs-comment">// creating a variable without any initial value</span>
<span class="hljs-keyword">var</span> &lt;variable-name&gt; &lt;data-<span class="hljs-keyword">type</span>&gt;
<span class="hljs-comment">// or</span>
<span class="hljs-comment">// creating a variable with given value</span>
<span class="hljs-keyword">var</span> &lt;variable-name&gt; &lt;data-<span class="hljs-keyword">type</span>&gt; = &lt;value&gt;
<span class="hljs-comment">// If value is provided data-type can be omitted</span>
<span class="hljs-keyword">var</span> &lt;variable-name&gt; = &lt;value&gt;
</code></pre>
<p>Now there is another way to create variables in Go, check this out</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span>{
<span class="hljs-comment">// this is another way to create variable</span>
    name := <span class="hljs-string">"Rishabh"</span>
}
</code></pre>
<p>Pay attention that I am not providing any data type information while creating the variable. Go compiler is smart enough to infer the type of variable depending on the value to the right of <code>:=</code> .</p>
<p>Note you cannot use the second syntax in the global scope, i.e. it is valid only inside functions.</p>
<pre><code class="lang-go"><span class="hljs-comment">// Invalid statement, since it is outside the function</span>
country := <span class="hljs-string">"Wakanda"</span>
<span class="hljs-comment">// Valid statement, You can use var syntax to create variable </span>
<span class="hljs-comment">// outside the functions. </span>
<span class="hljs-keyword">var</span> leader <span class="hljs-keyword">string</span> = <span class="hljs-string">"Black panther"</span>

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span>{
<span class="hljs-comment">//  valid statement</span>
    <span class="hljs-keyword">var</span> number <span class="hljs-keyword">int</span> = <span class="hljs-number">99</span>
<span class="hljs-comment">//  valid statement, allowed inside functions</span>
    number2 := <span class="hljs-number">50</span> 
}
</code></pre>
<p><em>Note</em>: <mark>You cannot use short-hand assignments outside the functions.</mark></p>
<h3 id="heading-multiple-assignments-on-the-same-line">Multiple assignments on the same line</h3>
<p>You can assign values to multiple variables on the same line, by separating variables by <code>,(comma)</code> and providing values in the same order as variables like in the following code.</p>
<pre><code class="lang-go"><span class="hljs-keyword">import</span> <span class="hljs-string">"fmt"</span>
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span>{
    <span class="hljs-keyword">var</span> a,b,c <span class="hljs-keyword">int</span> = <span class="hljs-number">45</span>,<span class="hljs-number">66</span>,<span class="hljs-number">99</span>
<span class="hljs-comment">// a = 45, b = 66, c = 99</span>
    fmt.Println(a,b,c)
    x,y,z := <span class="hljs-number">10</span>,<span class="hljs-number">20</span>,<span class="hljs-number">30</span>
<span class="hljs-comment">// x = 10, y = 20, z = 30</span>
    fmt.Println(x,y,z)
}
</code></pre>
<h2 id="heading-functions">Functions</h2>
<p>The function is a named group of statements that performs some specific task. For writing functions, there are three important parts,</p>
<ol>
<li><p>Name of the function</p>
</li>
<li><p>Input of the function</p>
</li>
<li><p>Output of the function.</p>
</li>
</ol>
<h3 id="heading-function-syntax">Function syntax</h3>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> &lt;<span class="hljs-title">name</span> <span class="hljs-title">of</span> <span class="hljs-title">function</span>&gt;<span class="hljs-params">(&lt;list of arguments(input)</span>&gt;) &lt;<span class="hljs-title">return</span>-<span class="hljs-title">type</span>&gt;</span> {
    &lt;body of the function&gt;
}

<span class="hljs-comment">// Example of a function</span>
<span class="hljs-comment">// this function takes two integers, adds them and</span>
<span class="hljs-comment">// returns an integer i.e. sum</span>
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">sum</span><span class="hljs-params">(num1 <span class="hljs-keyword">int</span>, num2 <span class="hljs-keyword">int</span>)</span> <span class="hljs-title">int</span></span>{
    <span class="hljs-keyword">return</span> num1+num2
}
</code></pre>
<p>If the arguments of a function are of the same type you can omit data types for all but the last argument. Observe the following code</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">sum</span><span class="hljs-params">(num1, num2 <span class="hljs-keyword">int</span>)</span> <span class="hljs-title">int</span></span> {
    <span class="hljs-keyword">return</span> num1+num2
}
</code></pre>
<h3 id="heading-multiple-return-values">Multiple return values</h3>
<p>Any number of values can be returned by a function. You just need to provide the list of return types in the function signature</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">twoValues</span><span class="hljs-params">(x, y <span class="hljs-keyword">int</span>)</span><span class="hljs-params">(<span class="hljs-keyword">int</span>,<span class="hljs-keyword">int</span>)</span></span>{
    <span class="hljs-keyword">return</span> y,x
}
</code></pre>
<p>Notice how I have provided a list of return types after the argument list.</p>
<h3 id="heading-named-return-types">Named return types</h3>
<p>You can also name the return types and in this way, there is no need to write the name of the returned value Go will automatically return the named return values.</p>
<p>For now, observe the following code.</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">myFunction</span><span class="hljs-params">(a <span class="hljs-keyword">int</span>, b <span class="hljs-keyword">int</span>)</span><span class="hljs-params">(z <span class="hljs-keyword">int</span>)</span></span>{
    z = a + b
    <span class="hljs-keyword">return</span>
}
</code></pre>
<p>In the above code, you can see I haven't returned anything but since I have named the returned variable, Go will automatically return the <code>z.</code></p>
<p>As per Go documentation, you should use named return values only for short functions.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>This is it for this blog I will be discussing data types, type casting and constants in the next one. I am going to share all my learnings, in a way that would help others. Feel free to suggest or discuss programming.</p>
<p>I will be posting more Go content, So stay tuned. More blog posts are coming where I will dive deep into this modern language.</p>
<p><mark>Link to next blog is</mark> <a target="_blank" href="https://rishabhdev.hashnode.dev/learning-go-basic-2">here</a>.</p>
<h3 id="heading-like-comment-share-and-follow-for-more">Like, Comment, Share and Follow for more.</h3>
<p>Keep supporting, It motivates me to keep creating content.</p>
]]></content:encoded></item><item><title><![CDATA[Model Formset in Django]]></title><description><![CDATA[Django Model Formsets
Introduction
Formset is a way of working with multiple forms at the same time. Using Formset you can use multiple forms on a single page. In this article, we will be creating formset using a model and see all the options that ar...]]></description><link>https://blog.therishabhdev.com/model-formset-in-django</link><guid isPermaLink="true">https://blog.therishabhdev.com/model-formset-in-django</guid><category><![CDATA[Python]]></category><category><![CDATA[Django]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[backend]]></category><category><![CDATA[Beginner Developers]]></category><dc:creator><![CDATA[Rishabh Kumar Bahukhandi]]></dc:creator><pubDate>Mon, 24 Jul 2023 11:58:43 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1690051501204/b9a73d46-6c18-4fe9-8cef-f557aeadff26.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-django-model-formsets">Django Model Formsets</h1>
<h2 id="heading-introduction">Introduction</h2>
<p>Formset is a way of working with multiple forms at the same time. Using Formset you can use multiple forms on a single page. In this article, we will be creating formset using a model and see all the options that are available to customize formset.</p>
<h2 id="heading-creating-formset">Creating Formset</h2>
<p>To create a formset we use the <code>modelformset_factory</code> function. You pass the Model and fields for which you want to make the <code>Formset</code>. <code>modelformset_factory</code> returns the Formset for the given model with the provided fields. Therefore it will be something like this:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> django.forms <span class="hljs-keyword">import</span> modelformset_factory,ModelForm
<span class="hljs-keyword">from</span> django.db <span class="hljs-keyword">import</span> models

<span class="hljs-comment"># Note Model Definition</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Note</span>(<span class="hljs-params">models.Model</span>):</span>
    title = models.CharField(max_length=<span class="hljs-number">80</span>)
    description = models.TextField()


<span class="hljs-comment"># Here we create a formset of Note</span>
NoteFormset = formset_factory(Note, fields=[<span class="hljs-string">'title'</span>,<span class="hljs-string">'description'</span>])
</code></pre>
<p>While creating a formset you can pass an additional parameter <strong>extra</strong> with a number then the <strong>Formset</strong> will contain that many empty forms.</p>
<p>If you have created a <code>ModelForm</code> with custom fields you can pass it to <code>modelformset_factory</code></p>
<pre><code class="lang-python"><span class="hljs-comment">#Example </span>
<span class="hljs-comment">#Creating formset from NoteForm For Note with 5 empty forms</span>
NoteFormset = formset_factory(Note,NoteForm, extra=<span class="hljs-number">5</span>)
<span class="hljs-comment"># This will create 5 empty forms in the formset</span>
</code></pre>
<h2 id="heading-formset-with-initial-data">Formset with initial data</h2>
<p>You can provide initial data for forms by passing a list of dictionaries with data. This will create forms equal to the length of initial data provided(<em>Total number of dictionaries in the initial data list</em>) + the value of the <code>extra</code> parameter passed during the creation of <strong>Formset</strong>. If you want to fill data from the database you can pass queryset as keyword argument and the forms will be filled with the data from the passed queryset.</p>
<p>Look at this code for better clarity.</p>
<pre><code class="lang-python">NoteFormset = formset_factory(NoteForm,extra=<span class="hljs-number">5</span>)
<span class="hljs-comment"># This formet contains 5 empty forms</span>
<span class="hljs-comment"># This list contain 3 dictionaries</span>
data = [
        {<span class="hljs-string">'title'</span>:<span class="hljs-string">"note no-1"</span>,<span class="hljs-string">"description"</span>:<span class="hljs-string">"description-1"</span>},
        {<span class="hljs-string">'title'</span>:<span class="hljs-string">"note no-2"</span>,<span class="hljs-string">"description"</span>:<span class="hljs-string">"description-2"</span>},
        {<span class="hljs-string">'title'</span>:<span class="hljs-string">"note no-3"</span>,<span class="hljs-string">"description"</span>:<span class="hljs-string">"description-3"</span>}
        ]
<span class="hljs-comment"># We passed the initial data to the NoteFormset</span>
<span class="hljs-comment"># Now forms contain 3 forms with data and 5 empty forms</span>
<span class="hljs-comment"># So total 8 </span>
<span class="hljs-comment"># filling the form with initial data</span>
forms = NoteFormset(initial=data)

<span class="hljs-comment"># Passing data from database</span>
<span class="hljs-comment"># for filling formset with queryset</span>
forms = NoteFormset(queryset=Note.objects.all())
<span class="hljs-comment"># for keeping the formset empty</span>
forms = NoteFormset(queryset=Note.objects.none())
</code></pre>
<p>In this way, you can provide data to be filled in the forms of the <code>formset</code>.</p>
<h2 id="heading-controlling-the-number-of-forms-in-a-formset">Controlling the number of forms in a Formset</h2>
<p>You can also control the number of forms to be displayed. For this, you need to pass another parameter called <code>max_num</code> to the <code>Formset</code>. Have a look at the following snippet.</p>
<pre><code class="lang-python"><span class="hljs-comment"># This list contain 3 dictionaries</span>
data = [
        {<span class="hljs-string">'title'</span>:<span class="hljs-string">"note no-1"</span>,<span class="hljs-string">"description"</span>:<span class="hljs-string">"description-1"</span>},
        {<span class="hljs-string">'title'</span>:<span class="hljs-string">"note no-2"</span>,<span class="hljs-string">"description"</span>:<span class="hljs-string">"description-2"</span>},
        {<span class="hljs-string">'title'</span>:<span class="hljs-string">"note no-3"</span>,<span class="hljs-string">"description"</span>:<span class="hljs-string">"description-3"</span>}
        ]

formset = NoteFormset(initial=data, extra=<span class="hljs-number">4</span>, max_num=<span class="hljs-number">5</span>)
<span class="hljs-comment"># This form will display 3 forms filled with data and 2 empty forms</span>
<span class="hljs-comment"># Keep this in mind if the number of forms with data exceeds the max_num</span>
<span class="hljs-comment"># then also all the forms with the data will be created but 0 empty forms</span>
</code></pre>
<p>Even if you provide the <code>max_num</code> less than forms with data then all forms with data + empty forms till <code>max_num</code> will be created.</p>
<p>Another parameter <code>absolute_max</code> can be passed to <code>formset_factory</code> to set the limit for the number of forms to create from POST data or initial data. In this way even if the initial data exceeds the <code>absolute_max</code> still only <code>absolute_max</code> number of forms will be instantiated.</p>
<pre><code class="lang-python">NoteFormset = formset_factory(Note, NoteForm, absolute_max=<span class="hljs-number">30</span>)
<span class="hljs-comment"># Now NoteFormset cannot contain forms more than absolute_max value</span>
</code></pre>
<p><strong><mark>Note:</mark></strong> <mark>Absolute_max should be greater than max_num else ValueError will be raised</mark></p>
<h3 id="heading-passing-the-post-data-to-a-formset">Passing the POST data to a formset</h3>
<p>To pass POST data you simply do this</p>
<p>If your form also deals with files/images don't forget to pass <code>request.FILES</code> to the <code>formset</code> while processing formset</p>
<pre><code class="lang-python">formset = NoteFormset(request.POST, request.FILES)
<span class="hljs-keyword">if</span> formset.is_valid():
    formset.save()
</code></pre>
<h2 id="heading-formset-validation">Formset validation</h2>
<p>To validate a <code>formset</code> call <code>is_valid()</code>. This will validate if the data entered in the forms was valid or not. <code>is_valid()</code> method returns a boolean denoting whether <code>formset</code> is valid or not.</p>
<h2 id="heading-rendering-formset-in-templates">Rendering Formset in templates</h2>
<p>Now, we will be looking at how to render formset in a template</p>
<pre><code class="lang-python"><span class="hljs-comment"># View function</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">process_form</span>(<span class="hljs-params">request</span>):</span>
    <span class="hljs-keyword">if</span> request.method==<span class="hljs-string">'POST'</span>:
        <span class="hljs-comment"># processing formset</span>
        <span class="hljs-keyword">return</span> redirect(<span class="hljs-string">'next view'</span>)
    data = Note.objects.all()
    <span class="hljs-comment"># If we do not provide any argument to the formset then</span>
    <span class="hljs-comment"># also it will be filled with queryset of the model</span>
    formset = NoteFormset()
    <span class="hljs-keyword">return</span> render(request,<span class="hljs-string">'template/form.html'</span>,context={<span class="hljs-string">'formset'</span>,formset})
</code></pre>
<p>Let's look at <mark>form.html</mark></p>
<p><strong>Note</strong>: <mark>If you are dealing with files/images in the form don't miss</mark> <code>enctype="multipart/form-data"</code></p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">method</span>=<span class="hljs-string">"post"</span> <span class="hljs-attr">enctype</span>=<span class="hljs-string">"multipart/form-data"</span>&gt;</span>
    {% csrf_token %}
    {{ formset.management_form }}
    {% for form in formset %}
        {{ form.as_p }}
    {% endfor %}
    <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"Save"</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
</code></pre>
<p><mark>It is important to include a management form inside the HTML form. So you will add </mark> <code>{{formset.management_form}}</code></p>
<p>And this is all that you need to know to start using model formsets. For learning more about formset read the official docs here <a target="_blank" href="https://docs.djangoproject.com/en/4.2/topics/forms/formsets/"><strong>Formset</strong></a> and <a target="_blank" href="https://docs.djangoproject.com/en/4.2/topics/forms/modelforms/#model-formsets"><strong>ModelFormset</strong></a>.</p>
<h3 id="heading-so-are-still-reading-why-dont-you-like-this-post-and-share-it-will-your-fellow-pythonistas-and-learners"><strong>So are still reading why don't you like this post and share it will your fellow pythonistas and learners?</strong></h3>
<h3 id="heading-share-your-views-and-story-of-learning-tech"><strong><mark>Share your views and story of learning tech.</mark></strong></h3>
]]></content:encoded></item><item><title><![CDATA[Creating Templates for Authentication]]></title><description><![CDATA[Overview
In this blog post, we will be creating templates for our authentication system. We will be creating a base template that will contain the common elements of all the templates and then we will create other templates which inherit from the bas...]]></description><link>https://blog.therishabhdev.com/creating-templates-for-authentication</link><guid isPermaLink="true">https://blog.therishabhdev.com/creating-templates-for-authentication</guid><category><![CDATA[Python]]></category><category><![CDATA[Django]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[Frontend Development]]></category><category><![CDATA[backend]]></category><dc:creator><![CDATA[Rishabh Kumar Bahukhandi]]></dc:creator><pubDate>Sun, 26 Mar 2023 18:01:49 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1679582527390/4c6adcec-8a97-4d19-ab99-e7cf113c1d7a.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-overview">Overview</h1>
<p>In this blog post, we will be creating templates for our authentication system. We will be creating a base template that will contain the common elements of all the templates and then we will create other templates which inherit from the base template. We will be creating templates for logging users in and registration forms for different user types.</p>
<h2 id="heading-getting-started">Getting started</h2>
<ul>
<li><p>Update settings, to let Django know where to find templates &amp; static files(CSS, Js, etc.)</p>
</li>
<li><p>Create a base template</p>
</li>
<li><p>Create other templates</p>
</li>
<li><p>Adding CSS</p>
</li>
<li><p>Django Templating Language Basics</p>
</li>
<li><p>Preview of Templates</p>
</li>
</ul>
<h2 id="heading-updating-the-coresettingspy">Updating the <code>core/settings.py</code></h2>
<p>Firstly we will add the path of our templates to <code>core/settings.py</code>. We will create a folder named 'templates' in the project root where we will store the templates. We will also create separate subfolders for different apps.</p>
<ul>
<li><p>Open the <code>core/settings.py</code></p>
</li>
<li><p>Go to <code>TEMPLATES</code> settings</p>
</li>
<li><p>Add 'templates/' to the <code>DIRS</code> key</p>
</li>
<li><p>Add <code>STATIC_ROOT</code> settings</p>
</li>
<li><p>Add <code>STATICFILES_DIRS</code> settings to list directories to search for static files</p>
<pre><code class="lang-python">  <span class="hljs-comment"># core/settings.py</span>
  TEMPLATES = [
      {
          <span class="hljs-string">'BACKEND'</span>: <span class="hljs-string">'django.template.backends.django.DjangoTemplates'</span>,
          <span class="hljs-comment"># List of directories</span>
          <span class="hljs-string">'DIRS'</span>: [<span class="hljs-string">'templates/'</span>],
          <span class="hljs-comment"># Whether to search inside each app for templates</span>
          <span class="hljs-string">'APP_DIRS'</span>: <span class="hljs-literal">True</span>,
          <span class="hljs-string">'OPTIONS'</span>: {
              <span class="hljs-string">'context_processors'</span>: [
                  <span class="hljs-string">'django.template.context_processors.debug'</span>,
                  <span class="hljs-string">'django.template.context_processors.request'</span>,
                  <span class="hljs-string">'django.contrib.auth.context_processors.auth'</span>,
                  <span class="hljs-string">'django.contrib.messages.context_processors.messages'</span>,
              ],
          },
      },
  ]

  STATIC_ROOT = <span class="hljs-string">'collected_static/'</span>
  <span class="hljs-comment"># url used to refer files in STATIC_ROOT</span>
  STATIC_URL = <span class="hljs-string">'static/'</span>

  <span class="hljs-comment"># List of paths to look for static files</span>
  STATICFILES_DIRS = [
     <span class="hljs-string">'static/'</span>
  ]
</code></pre>
<p>  <strong><mark>Note</mark></strong>: <strong>DIRS is a list of paths for Django to look for templates. APP_DIRS tells Django to also look inside each app</strong></p>
</li>
<li><p>Now Django will look for templates in the 'templates' folder in the project root and the templates folder inside each application.</p>
</li>
<li><p>It will also look for static files from directories in <code>STATICFILES_DIRS</code></p>
</li>
</ul>
<h2 id="heading-creating-a-base-template">Creating a base template</h2>
<p>Create a simple HTML document and save it as <code>base.html</code> inside <code>templates/authentication</code>.</p>
<p>We have included some template tags for including static files and adding named placeholders which will be replaced when the actual web page will be rendered.</p>
<pre><code class="lang-xml"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
{%load static%}
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">http-equiv</span>=<span class="hljs-string">"X-UA-Compatible"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"IE=edge"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>{%block title%}{%endblock%}<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"{%static 'main.css'%}"</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">""</span>&gt;</span>
      {% if messages %}
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">hr</span>&gt;</span>
            {% for message in messages %}
            <span class="hljs-tag">&lt;<span class="hljs-name">center</span>&gt;</span>{{ message }}<span class="hljs-tag">&lt;/<span class="hljs-name">center</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">hr</span>&gt;</span>
            {% endfor %}
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      {% endif %}
        {%block content%}{%endblock%}
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<h2 id="heading-creating-the-remaining-templates">Creating the remaining templates</h2>
<ul>
<li>Login Template</li>
</ul>
<pre><code class="lang-xml">{%extends 'authentication/base.html'%}
{%block title%}Login{%endblock%}

{%block content%}
<span class="hljs-tag">&lt;<span class="hljs-name">center</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"title black"</span>&gt;</span>Login with Your Credentials<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"form"</span> <span class="hljs-attr">method</span>=<span class="hljs-string">"post"</span>&gt;</span>
        {%csrf_token%}
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"email"</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"email"</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Email"</span> <span class="hljs-attr">required</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"password"</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"password"</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Password"</span> <span class="hljs-attr">required</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"submit-button"</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"Login"</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">center</span>&gt;</span>
{%endblock%}
</code></pre>
<ul>
<li><p>Registration Template</p>
<p>  In this template, we will be passing our CustomUserCreationForm which will be rendered automatically. Also, this template will be used to create two web pages. We will pass the creation form depending on user type to this template.</p>
</li>
</ul>
<pre><code class="lang-xml">{%extends 'authentication/base.html'%}
{%block title%}Registration{%endblock%}

{%block content%}
    <span class="hljs-tag">&lt;<span class="hljs-name">center</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">'title {%if title == "Teacher Registration" %} purple {% else %} blue {%endif%}'</span>&gt;</span>{{title}}<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"form"</span> <span class="hljs-attr">method</span>=<span class="hljs-string">"post"</span>&gt;</span>
        {%csrf_token%}
        {%for field in form%}
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"label"</span>&gt;</span>{{field.label}}<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"field"</span>&gt;</span>
        {{field}}
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        {%endfor%}
        <span class="hljs-tag">&lt;<span class="hljs-name">hr</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"confirmation"</span>&gt;</span>Check this box for confirmation<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"checkbox"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"confirmation"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"confirmation"</span> <span class="hljs-attr">required</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"submit-button"</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"Register"</span> /&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">center</span>&gt;</span>
{%endblock%}
</code></pre>
<h2 id="heading-adding-css">Adding CSS</h2>
<p>Create a main.css in <code>static</code> folder in the project directory</p>
<pre><code class="lang-css"><span class="hljs-comment">/* static/main.css */</span>
<span class="hljs-selector-tag">body</span> {
  <span class="hljs-attribute">box-sizing</span>: border-box;
  <span class="hljs-attribute">background-color</span>: white;
  <span class="hljs-attribute">font-family</span>: <span class="hljs-string">"Segoe UI"</span>, Tahoma, Geneva, Verdana, sans-serif;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span>;
}
<span class="hljs-selector-tag">input</span> {
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">1rem</span>;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">0.5rem</span>;
  <span class="hljs-attribute">border</span>: none;
  <span class="hljs-attribute">outline</span>: <span class="hljs-number">1px</span> solid grey;
  <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">0.5rem</span>;
}
<span class="hljs-selector-tag">input</span><span class="hljs-selector-pseudo">:focus</span> {
  <span class="hljs-attribute">outline</span>: <span class="hljs-number">2px</span> solid blue;
}
<span class="hljs-selector-class">.title</span> {
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">2rem</span>;
  <span class="hljs-attribute">font-weight</span>: lighter;
  <span class="hljs-attribute">font-family</span>: <span class="hljs-string">"Segoe UI"</span>, Tahoma, Geneva, Verdana, sans-serif;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">4rem</span> <span class="hljs-number">0rem</span>;
  <span class="hljs-attribute">color</span>: white;
  <span class="hljs-attribute">box-shadow</span>: <span class="hljs-number">5px</span> <span class="hljs-number">3px</span> <span class="hljs-number">4px</span> black;
}
<span class="hljs-selector-class">.form</span> {
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">flex-direction</span>: column;
  <span class="hljs-attribute">justify-content</span>: center;
  <span class="hljs-attribute">align-items</span>: center;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">60vh</span>;
}
<span class="hljs-selector-class">.label</span> {
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">0.5rem</span>;
}

<span class="hljs-selector-class">.submit-button</span> {
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">1rem</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">1rem</span> <span class="hljs-number">1.5rem</span>;
  <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#2b7cff</span>;
  <span class="hljs-attribute">color</span>: white;
  <span class="hljs-attribute">outline</span>: none;
  <span class="hljs-attribute">transition</span>: all <span class="hljs-number">0.3s</span> ease-in-out;
}
<span class="hljs-selector-class">.submit-button</span><span class="hljs-selector-pseudo">:hover</span> {
  <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">scale</span>(<span class="hljs-number">1.04</span>);
}
<span class="hljs-selector-class">.purple</span> {
  <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#7323b5</span>;
}
<span class="hljs-selector-class">.blue</span> {
  <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#0047ba</span>;
}
<span class="hljs-selector-class">.black</span> {
  <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#000</span>;
}

<span class="hljs-keyword">@media</span> screen <span class="hljs-keyword">and</span> (<span class="hljs-attribute">min-width:</span> <span class="hljs-number">480px</span>) {
  <span class="hljs-selector-class">.form</span> {
    <span class="hljs-attribute">height</span>: <span class="hljs-number">55vh</span>;
  }
}
<span class="hljs-selector-tag">hr</span>{
    <span class="hljs-attribute">width</span>:<span class="hljs-number">10rem</span>;
}
</code></pre>
<h3 id="heading-project-structure">Project Structure</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1679853133628/900478d4-ef04-456b-8a08-76874aea524e.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-django-templating-language-basics">Django Templating Language Basics</h2>
<ul>
<li><p><code>{% %}</code> notation is used for statement</p>
</li>
<li><p><code>{{ }}</code> notation is used for expressions</p>
</li>
<li><p><code>{%block name %}{%endblock%}</code>: Placeholder that will be replaced when the template will be rendered on user request. We will change the title of the template using the title block and the body of the template using the content block. The rest of the template will remain the same.</p>
</li>
<li><p><code>{{variable}}</code>: you can access variables passed to the templates through a context dictionary.</p>
</li>
</ul>
<p><a target="_blank" href="https://docs.djangoproject.com/en/4.1/ref/templates/language/">For in-depth reading Official Django Templating Language Docs</a></p>
<h2 id="heading-templates-preview">Templates Preview</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1679837248782/e1306221-d2c3-44df-9f62-65725f7c4c9e.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1679837210982/f7f0c9ca-27c4-40b2-8579-cf660a4aa3b5.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1679837224801/4dece15f-81d5-429f-abf5-0e5d67e3a2e8.png" alt class="image--center mx-auto" /></p>
<p>Now, these form templates are fully functional and you can add Students and Teachers using them.</p>
<p>Try starting the project by activating the virtual environment if not yet activated.</p>
<pre><code class="lang-bash"><span class="hljs-comment"># for linux / macOS</span>
<span class="hljs-built_in">source</span> env/bin/activate
python3 manage.py runserver



<span class="hljs-comment"># for windows</span>
./env/Scripts/activate
python manage.py runserver
</code></pre>
<p>After starting the project try the following URLs</p>
<ul>
<li><p><a target="_blank" href="http://127.0.0.1:8000/auth/register-teacher/">127.0.0.1:8000/auth/register-teacher/</a></p>
</li>
<li><p><a target="_blank" href="http://127.0.0.1:8000/auth/register-student/">127.0.0.1:8000/auth/register-student/</a></p>
</li>
<li><p><a target="_blank" href="http://127.0.0.1:8000/auth/login/">127.0.0.1:8000/auth/login/</a></p>
</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Now we have almost completed the authentication and registration part. We learned about templates and how we can define a template once to create any number of web pages with different data, as we have created a single template to render different forms. We also saw how to use static files like CSS in Django.</p>
<p>In the next blog, we will be creating a new app that will handle profile creation. From now on we will be quickly moving forward since we know how to define views, URLs and templates.</p>
<h2 id="heading-like-comment-and-share"><strong><mark>Like, Comment and Share</mark></strong></h2>
<p>Your feedback will be really helpful for improvement. Feel free to connect and discuss technologies.</p>
<p><strong>Happy Learning</strong></p>
<h2 id="heading-references">References</h2>
<p><a target="_blank" href="https://docs.djangoproject.com/en/4.1/ref/templates/language/">Django Template Language</a></p>
<p><a target="_blank" href="https://docs.djangoproject.com/en/4.1/ref/settings/#templates">Templates Settings in Django</a></p>
<p><a target="_blank" href="https://docs.djangoproject.com/en/4.1/ref/settings/#static-files">Static Files Settings in Django</a></p>
<h3 id="heading-previous-parthttpsrishabhdevhashnodedevimplementing-authentication-for-school-management-system-with-django"><a target="_blank" href="https://rishabhdev.hashnode.dev/implementing-authentication-for-school-management-system-with-django">Previous part</a></h3>
]]></content:encoded></item><item><title><![CDATA[Implementing Authentication for School Management System with Django]]></title><description><![CDATA[Overview
For the authentication system, we will start by defining our user model and then creating proxy models to differentiate between different types of users. We will also define custom managers for the models to override the create_user and get_...]]></description><link>https://blog.therishabhdev.com/implementing-authentication-for-school-management-system-with-django</link><guid isPermaLink="true">https://blog.therishabhdev.com/implementing-authentication-for-school-management-system-with-django</guid><category><![CDATA[Python]]></category><category><![CDATA[Django]]></category><category><![CDATA[backend]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[Beginner Developers]]></category><dc:creator><![CDATA[Rishabh Kumar Bahukhandi]]></dc:creator><pubDate>Fri, 17 Mar 2023 12:03:38 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1679040476952/b0acc186-a0e4-4754-a388-aea0b775370c.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-overview">Overview</h1>
<p>For the authentication system, we will start by defining our user model and then creating proxy models to differentiate between different types of users. We will also define custom managers for the models to override the create_user and get_queryset methods.</p>
<p>After defining our models we will be creating our custom user creation form and user change form to create and update our users. Then defining URL paths and writing view functions to process the form data and register different types of users.</p>
<p>For a better, understanding give the following blogs a read.</p>
<h3 id="heading-learn-about-the-structure-of-django-applications-herehttpsrishabhdevhashnodedevstructure-of-django-application"><mark>Learn about the Structure of Django Applications</mark> <a target="_blank" href="https://rishabhdev.hashnode.dev/structure-of-django-application">Here</a></h3>
<h3 id="heading-learn-about-django-models-herehttpsrishabhdevhashnodedevknow-about-models-in-django"><mark>Learn About Django Models</mark> <a target="_blank" href="https://rishabhdev.hashnode.dev/know-about-models-in-django"><strong>Here</strong></a></h3>
<h2 id="heading-defining-custom-user-model">Defining Custom User model</h2>
<p>We will be extending the <code>AbstractBaseUser</code> from <code>django.contrib.auth.models</code> and setting <strong>email</strong> as the username field for logging in users.</p>
<pre><code class="lang-python"><span class="hljs-comment"># authentication/models.py</span>
<span class="hljs-keyword">from</span> django.utils <span class="hljs-keyword">import</span> timezone
<span class="hljs-keyword">from</span> django.db <span class="hljs-keyword">import</span> models
<span class="hljs-keyword">from</span> django.contrib.auth.models <span class="hljs-keyword">import</span> AbstractBaseUser, BaseUserManager, PermissionsMixin

<span class="hljs-comment"># This the user manager with function to create_user and create_superuser methods. Manager is used to perform query operations</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserManager</span>(<span class="hljs-params">BaseUserManager</span>):</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">create_user</span>(<span class="hljs-params">self, email, password=None</span>):</span>
        <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> email <span class="hljs-keyword">or</span> len(email) &lt;= <span class="hljs-number">0</span>:
            <span class="hljs-keyword">raise</span> ValueError(<span class="hljs-string">"Email Field is required!!!!"</span>)
        <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> password:
            <span class="hljs-keyword">raise</span> ValueError(<span class="hljs-string">"Password is required"</span>)

        user = self.model(
            email=self.normalize_email(email)
        )
        user.set_password(password)
        user.save(using=self._db)
        <span class="hljs-keyword">return</span> user

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">create_superuser</span>(<span class="hljs-params">self, email, password</span>):</span>
        user = self.create_user(
            email=self.normalize_email(email),
            password=password
        )
        user.is_admin = <span class="hljs-literal">True</span>
        user.is_staff = <span class="hljs-literal">True</span>
        user.is_teacher = <span class="hljs-literal">True</span>
        user.is_superuser = <span class="hljs-literal">True</span>
        user.save(using=self._db)
        <span class="hljs-keyword">return</span> user

<span class="hljs-comment"># This is the custom user model with type attribute for differentiating user types. Default type is student</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span>(<span class="hljs-params">AbstractBaseUser,PermissionsMixin</span>):</span>
    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Types</span>(<span class="hljs-params">models.TextChoices</span>):</span>
        STUDENT = <span class="hljs-string">"STUDENT"</span>, <span class="hljs-string">"student"</span>
        TEACHER = <span class="hljs-string">"TEACHER"</span>, <span class="hljs-string">"teacher"</span>
    type = models.CharField(
        max_length=<span class="hljs-number">8</span>, choices=Types.choices, default=Types.STUDENT)
    email = models.EmailField(unique=<span class="hljs-literal">True</span>, max_length=<span class="hljs-number">100</span>)
    date_joined = models.DateTimeField(default=timezone.now)
    is_active = models.BooleanField(default=<span class="hljs-literal">True</span>)
    is_admin = models.BooleanField(default=<span class="hljs-literal">False</span>)
    is_staff = models.BooleanField(default=<span class="hljs-literal">False</span>)
    is_superuser = models.BooleanField(default=<span class="hljs-literal">False</span>)
    is_teacher = models.BooleanField(default=<span class="hljs-literal">False</span>)
    is_student = models.BooleanField(default=<span class="hljs-literal">False</span>)
    USERNAME_FIELD = <span class="hljs-string">'email'</span>
    objects = UserManager()

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__str__</span>(<span class="hljs-params">self</span>) -&gt; str:</span>
        <span class="hljs-keyword">return</span> str(self.email)

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">has_perm</span>(<span class="hljs-params">self, perm, obj=None</span>) -&gt; bool:</span>
        <span class="hljs-keyword">return</span> self.is_admin

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">has_module_perms</span>(<span class="hljs-params">self, app_label</span>) -&gt; bool:</span>
        <span class="hljs-keyword">return</span> <span class="hljs-literal">True</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">save</span>(<span class="hljs-params">self, *args, **kwargs</span>):</span>
        <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> self.type <span class="hljs-keyword">or</span> self.type == <span class="hljs-literal">None</span>:
            self.type = User.Types.STUDENT
        <span class="hljs-keyword">return</span> super().save(*args, **kwargs)
</code></pre>
<h2 id="heading-defining-proxy-model-for-different-user-types">Defining Proxy model for different user types</h2>
<p>Proxy models operate on the same database table of concrete class in our case it is User but proxy models can have different behavior, permissions and meta options. We have used proxy models since both students and teachers should be able to login into the system.</p>
<pre><code class="lang-python"><span class="hljs-comment"># authentication/models.py</span>
<span class="hljs-comment"># Manager for student</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">StudentManager</span>(<span class="hljs-params">models.Manager</span>):</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">create_user</span>(<span class="hljs-params">self, email, password=None</span>):</span>
        <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> email <span class="hljs-keyword">or</span> len(email) &lt;= <span class="hljs-number">0</span>:
            <span class="hljs-keyword">raise</span> ValueError(<span class="hljs-string">"Email is Required!!"</span>)
        <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> password:
            <span class="hljs-keyword">raise</span> ValueError(<span class="hljs-string">"Password is Required!!"</span>)
        email = email.lower()
        user = self.model(
            email=self.normalize_email(email)
        )
        user.set_password(password)
        user.save(using=self._db)
        <span class="hljs-keyword">return</span> user

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_queryset</span>(<span class="hljs-params">self, *args, **kwargs</span>):</span>
        queryset = super().get_queryset(*args, **kwargs)
        queryset = queryset.filter(type=User.Types.STUDENT)
        <span class="hljs-keyword">return</span> queryset

<span class="hljs-comment"># Student proxy model</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Student</span>(<span class="hljs-params">User</span>):</span>
    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Meta</span>:</span>
        proxy = <span class="hljs-literal">True</span>

    objects = StudentManager()

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">save</span>(<span class="hljs-params">self, *args, **kwargs</span>):</span>
        self.type = User.Types.STUDENT
        self.is_student = <span class="hljs-literal">True</span>
        super().save(*args, **kwargs)

<span class="hljs-comment"># Manager for Teacher model</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">TeacherManager</span>(<span class="hljs-params">models.Manager</span>):</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">create_user</span>(<span class="hljs-params">self, email, password=None</span>):</span>
        <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> email <span class="hljs-keyword">or</span> len(email) &lt;= <span class="hljs-number">0</span>:
            <span class="hljs-keyword">raise</span> ValueError(<span class="hljs-string">"Email Required!!"</span>)
        <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> password:
            <span class="hljs-keyword">raise</span> ValueError(<span class="hljs-string">"Password is Required!!"</span>)
        email = email.lower()
        user = self.model(
            email=self.normalize_email(email)
        )
        user.set_password(password)
        user.save(using=self._db)
        <span class="hljs-keyword">return</span> user

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_queryset</span>(<span class="hljs-params">self, *args, **kwargs</span>):</span>
        queryset = super().get_queryset(*args, **kwargs)
        queryset = queryset.filter(type=User.Types.TEACHER)
        <span class="hljs-keyword">return</span> queryset

<span class="hljs-comment"># Teacher proxy model</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Teacher</span>(<span class="hljs-params">User</span>):</span>

    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Meta</span>:</span>
        proxy = <span class="hljs-literal">True</span>

    objects = TeacherManager()

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">save</span>(<span class="hljs-params">self, *args, **kwargs</span>):</span>
        self.type = User.Types.TEACHER
        self.is_teacher = <span class="hljs-literal">True</span>
        self.is_staff = <span class="hljs-literal">True</span>
        <span class="hljs-keyword">return</span> super().save(*args, **kwargs)
</code></pre>
<p>For each proxy model, we have overridden the save method to change the attributes as per the proxy model and save the model</p>
<h2 id="heading-creating-usercreationform-and-userchangeform">Creating UserCreationForm and UserChangeForm</h2>
<p>Now we will extend the UserCreationForm and UserChangeForm and modify them as per our Proxy model. While defining a Form in Django we define the model in the inner class Meta along with fields to be exposed through the form.</p>
<pre><code class="lang-python"><span class="hljs-comment"># authentication/forms.py</span>
<span class="hljs-keyword">from</span> django.contrib.auth.forms <span class="hljs-keyword">import</span> UserCreationForm, UserChangeForm
<span class="hljs-keyword">from</span> authentication.models <span class="hljs-keyword">import</span> Student, Teacher, User

<span class="hljs-comment"># Creation form for our Concrete Model</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CustomUserCreationForm</span>(<span class="hljs-params">UserCreationForm</span>):</span>
    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Meta</span>:</span>
        model = User
        fields = (<span class="hljs-string">'email'</span>,)

<span class="hljs-comment"># Change form for updating User</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CustomUserChangeForm</span>(<span class="hljs-params">UserChangeForm</span>):</span>
    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Meta</span>:</span>
        model = User
        fields = (<span class="hljs-string">'email'</span>,)

<span class="hljs-comment"># Creation form for Teacher proxy model</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">TeacherCreationForm</span>(<span class="hljs-params">UserCreationForm</span>):</span>
    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Meta</span>:</span>
        model = Teacher
        fields = (<span class="hljs-string">'email'</span>,)

<span class="hljs-comment"># Change form for updating Teacher</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">TeacherChangeForm</span>(<span class="hljs-params">UserChangeForm</span>):</span>
    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Meta</span>:</span>
        model = Teacher
        fields = (<span class="hljs-string">'email'</span>,)

<span class="hljs-comment"># Creation form for Student proxy model</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">StudentCreationForm</span>(<span class="hljs-params">UserCreationForm</span>):</span>
    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Meta</span>:</span>
        model = Student
        fields = (<span class="hljs-string">'email'</span>,)

<span class="hljs-comment"># Change form for updating Student</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">StudentChangeForm</span>(<span class="hljs-params">UserChangeForm</span>):</span>
    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Meta</span>:</span>
        model = Student
        fields = (<span class="hljs-string">'email'</span>,)
</code></pre>
<h2 id="heading-updating-coresettingspy-and-coreurlspy">Updating <strong>core/settings.py</strong> and <strong>core/urls.py</strong></h2>
<p>The next step is to add our authentication app to the installed_apps list</p>
<pre><code class="lang-python"><span class="hljs-comment"># core/settings.py</span>
INSTALLED_APPS = [
    <span class="hljs-string">'django.contrib.admin'</span>,
    <span class="hljs-string">'django.contrib.auth'</span>,
    <span class="hljs-string">'django.contrib.contenttypes'</span>,
    <span class="hljs-string">'django.contrib.sessions'</span>,
    <span class="hljs-string">'django.contrib.messages'</span>,
    <span class="hljs-string">'django.contrib.staticfiles'</span>,
<span class="hljs-comment"># I have added authentication app here</span>
    <span class="hljs-string">'authentication'</span>,
]
<span class="hljs-comment"># Settings to use our custom user for authentication</span>
AUTH_USER_MODEL = <span class="hljs-string">'authentication.User'</span>
</code></pre>
<pre><code class="lang-python"><span class="hljs-comment"># core/urls.py</span>
<span class="hljs-keyword">from</span> django.contrib <span class="hljs-keyword">import</span> admin
<span class="hljs-keyword">from</span> django.urls <span class="hljs-keyword">import</span> path, include
<span class="hljs-comment"># Here we have included authentication urls to the main django project</span>
<span class="hljs-comment"># All path starting with 'auth/' will be looked up in authentication app urls file</span>
urlpatterns = [
    path(<span class="hljs-string">'admin/'</span>, admin.site.urls),
    path(<span class="hljs-string">'auth/'</span>,include(<span class="hljs-string">'authentication.urls'</span>))
]
</code></pre>
<h2 id="heading-defining-url-paths-and-view-functions">Defining URL paths and View Functions</h2>
<p>Create a <code>urls.py</code> file in the <code>authentication</code> folder and add the following lines to it</p>
<pre><code class="lang-python"><span class="hljs-comment"># authentication/urls.py</span>
<span class="hljs-keyword">from</span> django.urls <span class="hljs-keyword">import</span> path
<span class="hljs-keyword">from</span> django.contrib.auth.views <span class="hljs-keyword">import</span> LoginView
<span class="hljs-keyword">from</span> . <span class="hljs-keyword">import</span> views
<span class="hljs-comment"># path( "path string/", views.function, name="optional name of path"</span>
urlpatterns = [
path(<span class="hljs-string">''</span>,
    views.homepage,
    name=<span class="hljs-string">"homepage"</span>
    ),
path(
    <span class="hljs-string">'login/'</span>,
    views.loginUser,
    name=<span class="hljs-string">"login"</span>
    ),
path(
    <span class="hljs-string">'logout/'</span>,
    views.logoutUser,
    name=<span class="hljs-string">"logout"</span>
    ),
path(
    <span class="hljs-string">'register-student/'</span>
    ,views.registerStudent,
    name=<span class="hljs-string">"register-student"</span>
    ),
path(
    <span class="hljs-string">'register-teacher/'</span>,
    views.registerTeacher,
    name=<span class="hljs-string">"register-teacher"</span>
     ),
]
</code></pre>
<p>Now we will create view functions that are triggered as per the URL path that the client accesses in our web application.</p>
<pre><code class="lang-python"><span class="hljs-comment"># authentication/views.py</span>
<span class="hljs-keyword">from</span> django.shortcuts <span class="hljs-keyword">import</span> redirect, render
<span class="hljs-keyword">from</span> django.contrib <span class="hljs-keyword">import</span> messages
<span class="hljs-keyword">from</span> authentication.forms <span class="hljs-keyword">import</span> StudentCreationForm, TeacherCreationForm


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">homepage</span>(<span class="hljs-params">request</span>):</span>
    <span class="hljs-keyword">return</span> render(request, <span class="hljs-string">"homepage.html"</span>)


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">registerStudent</span>(<span class="hljs-params">request</span>):</span>
    <span class="hljs-keyword">if</span> request.method==<span class="hljs-string">'POST'</span>:
        form = StudentCreationForm(request.POST)
        <span class="hljs-keyword">if</span> form.is_valid():
            form.save()
            messages.success(request,<span class="hljs-string">'Registered Successfully'</span>)
        <span class="hljs-keyword">else</span>:
            messages.error(request,<span class="hljs-string">'Please recheck the form data'</span>)
        <span class="hljs-keyword">return</span> redirect(<span class="hljs-string">'register-student'</span>)
    form = StudentCreationForm()
    title = <span class="hljs-string">"Student Registration"</span>
    <span class="hljs-keyword">return</span> render(request, <span class="hljs-string">'authentication/register.html'</span>, {<span class="hljs-string">'form'</span>: form,<span class="hljs-string">'title'</span>:title})


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">registerTeacher</span>(<span class="hljs-params">request</span>):</span>
    <span class="hljs-keyword">if</span> request.method==<span class="hljs-string">'POST'</span>:
        form = TeacherCreationForm(request.POST)
        <span class="hljs-keyword">if</span> form.is_valid():
            form.save()
            messages.success(request,<span class="hljs-string">'Registered Successfully'</span>)
        <span class="hljs-keyword">else</span>:
            messages.error(request,<span class="hljs-string">'Please recheck the form data'</span>)
        <span class="hljs-keyword">return</span> redirect(<span class="hljs-string">'register-teacher'</span>)
    form = TeacherCreationForm()
    title = <span class="hljs-string">"Teacher Registration"</span>
    <span class="hljs-keyword">return</span> render(request, <span class="hljs-string">'authentication/register.html'</span>, {<span class="hljs-string">'form'</span>: form,<span class="hljs-string">'title'</span>:title})


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">loginUser</span>(<span class="hljs-params">request</span>):</span>
    <span class="hljs-keyword">if</span> request.method==<span class="hljs-string">'POST'</span>:
        email = request.POST[<span class="hljs-string">'email'</span>]
        password = request.POST[<span class="hljs-string">'password'</span>]
        user = authenticate(request,email=email,password=password)
        <span class="hljs-keyword">if</span> user <span class="hljs-keyword">is</span> <span class="hljs-keyword">not</span> <span class="hljs-literal">None</span>:
            login(request,user)
            messages.success(request,<span class="hljs-string">"Logged in Successfully"</span>)
            <span class="hljs-keyword">return</span> redirect(<span class="hljs-string">'homepage'</span>)
        <span class="hljs-keyword">else</span>:
            messages.error(request,<span class="hljs-string">"Invalid credentials!"</span>)
    <span class="hljs-keyword">return</span> render(request,<span class="hljs-string">'authentication/login.html'</span>)


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">logoutUser</span>(<span class="hljs-params">request</span>):</span>
    logout(request)
    <span class="hljs-keyword">return</span> redirect(<span class="hljs-string">'login'</span>)
</code></pre>
<p>For using the creation form we create an instance of the form and pass it to the template for rendering. We have created different functions for each user type and are passing different creation forms as per type to the template.</p>
<h2 id="heading-registering-model-for-admin-panel">Registering model for Admin panel</h2>
<p>Now finally we will be registering our models to the admin panel</p>
<pre><code class="lang-python"><span class="hljs-comment"># authentication/admin.py</span>
<span class="hljs-keyword">from</span> django.contrib <span class="hljs-keyword">import</span> admin
<span class="hljs-keyword">from</span> .models <span class="hljs-keyword">import</span> *

admin.site.register(User)
admin.site.register(Teacher)
admin.site.register(Student)
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>We have almost completed the backend of the authentication system. We created our User models, proxy models for different user types, URL routes, and views functions for registering users, logging users in and logging them out.</p>
<p><strong>In the next part, we will create templates i.e. the front end of our authentication system.</strong></p>
<h3 id="heading-previous-parthttpsrishabhdevhashnodedevbuilding-a-school-management-system-with-django"><a target="_blank" href="https://rishabhdev.hashnode.dev/building-a-school-management-system-with-django"><strong>Previous Part</strong></a></h3>
<h3 id="heading-next-parthttpsrishabhdevhashnodedevcreating-templates-for-authentication"><a target="_blank" href="https://rishabhdev.hashnode.dev/creating-templates-for-authentication"><strong>Next Part</strong></a></h3>
<h2 id="heading-follow-like-share-comment-and-support"><mark>Follow, like, share, comment and support</mark></h2>
]]></content:encoded></item><item><title><![CDATA[Building a School Management System with Django]]></title><description><![CDATA[Overview
We will be building a full-fledged school management system and deploying it to the web. We will be starting from scratch and gradually building up on the foundation of our Django knowledge. There will be a proper explanation for every code ...]]></description><link>https://blog.therishabhdev.com/building-a-school-management-system-with-django</link><guid isPermaLink="true">https://blog.therishabhdev.com/building-a-school-management-system-with-django</guid><category><![CDATA[Django]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[Python]]></category><category><![CDATA[backend]]></category><category><![CDATA[Programming Blogs]]></category><dc:creator><![CDATA[Rishabh Kumar Bahukhandi]]></dc:creator><pubDate>Sun, 12 Mar 2023 17:35:42 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1679054877639/4ad26331-6ade-4893-bc47-7a1f23c4ff78.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-overview">Overview</h1>
<p>We will be building a full-fledged school management system and deploying it to the web. We will be starting from scratch and gradually building up on the foundation of our Django knowledge. There will be a proper explanation for every code block that we write. Let us first list all functionalities that we will be having in our school management system. Managing</p>
<ul>
<li><p>Student records</p>
</li>
<li><p>Teacher records</p>
</li>
<li><p>Attendance records</p>
</li>
<li><p>Subjects</p>
</li>
<li><p>academic reports/performance</p>
</li>
</ul>
<h2 id="heading-prerequisites">Prerequisites</h2>
<ul>
<li><p>Text editor/ IDE (<strong>Pycharm</strong> or <strong>VS code</strong> or any other you like)</p>
</li>
<li><p>Installed Python 3 interpreter</p>
</li>
<li><p>Familiarity with Python 3</p>
</li>
</ul>
<p>For creating templates</p>
<ul>
<li><p>HTML</p>
</li>
<li><p>CSS</p>
</li>
<li><p>Javascript</p>
</li>
</ul>
<h2 id="heading-setting-up-a-virtual-environment">Setting up a virtual environment</h2>
<p>Before starting with the project we need to create a virtual environment where all the modules and packages we need will be saved. The virtual environment is very useful for development it helps to avoid problems with package version compatibility.</p>
<p>Create a new folder and open it in your text editor</p>
<p>Open integrated terminal in it. For VS code you can press</p>
<p><code>CTRL + Shift + ` </code></p>
<p>To create a virtual environment on Linux / Mac system enter the following command</p>
<pre><code class="lang-bash"><span class="hljs-comment"># python3 -m venv &lt;name of virtual environment&gt;</span>
python3 -m venv env

<span class="hljs-comment"># Activating your newly created virtual environment</span>
<span class="hljs-built_in">source</span> env/bin/activate
</code></pre>
<p>After activating the virtual environment the terminal prompt will look something like this</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1678555462162/f5344f9d-2179-4783-9823-10935e3b8e30.png" alt class="image--center mx-auto" /></p>
<p>Now we need to add some packages that we need to start our Django project. In the terminal type either of the following command.</p>
<pre><code class="lang-bash"><span class="hljs-comment"># Adding Django to the virtual environment</span>
pip3 install django
<span class="hljs-comment"># or</span>
pip install django
</code></pre>
<h2 id="heading-starting-a-new-django-project">Starting a new Django project</h2>
<p>To start a new Django project we will use <code>django-admin</code> CLI tool. Enter the following command to start a new Django project.</p>
<pre><code class="lang-bash">django-admin startproject core .
</code></pre>
<p>Pay attention to the trailing (.). This trailing " . " will start a new Django project in the current directory. If you omit the period in the end. It will create a new folder named core and then inside it will start a new project.</p>
<h2 id="heading-what-do-these-files-do">What do these files do?</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1678640777740/17c67600-9b7e-41f5-bc19-e92b5d7002de.png" alt class="image--center mx-auto" /></p>
<ul>
<li><p><code>core/__init__.py</code></p>
<p>  This file makes the Python interpreter treat the directory as a python module.</p>
</li>
<li><p><code>core/asgi.py</code> and <code>core/wsgi.py</code></p>
<p>  These files are used by the application server to communicate with the Django application.</p>
</li>
<li><p><code>core/settings.py</code></p>
<p>  This file contains very important configurations of our Django application including secret key, static files settings, database configurations, and much more.</p>
</li>
<li><p><code>core/urls.py</code></p>
<p>  This file contains the root URLs of your Django project. Here we define the path for various Django apps.</p>
</li>
</ul>
<h2 id="heading-try-running-the-project">Try running the project</h2>
<p>Start the development server using the following command</p>
<pre><code class="lang-bash">python manage.py runserver
<span class="hljs-comment"># or</span>
python3 manage.py runserver
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1678642235422/0d54e08d-32e0-45a3-9039-8014bb872976.png" alt class="image--center mx-auto" /></p>
<p>Now open up the link in your browser</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1678642352519/95351f6a-abc1-4b34-8405-c4b37cbac8d8.png" alt class="image--center mx-auto" /></p>
<p>To stop the development server press <code>CTRL + C</code></p>
<p>In the next part, we will be creating a new application that will handle the authentication and authorization of our Django project.</p>
<h3 id="heading-next-parthttpsrishabhdevhashnodedevimplementing-authentication-for-school-management-system-with-django"><a target="_blank" href="https://rishabhdev.hashnode.dev/implementing-authentication-for-school-management-system-with-django">Next Part</a></h3>
<hr />
<h2 id="heading-follow-to-get-notified-of-upcoming-parts-of-this-project-happy-learning"><mark>Follow to get notified of upcoming parts of this project. Happy Learning!</mark></h2>
]]></content:encoded></item><item><title><![CDATA[Know about Models in Django]]></title><description><![CDATA[Introduction to Django models
In the process of learning Django, you surely will come across Django models. It is an important component of any Django application. Having good knowledge is essential to create an efficient web application using Django...]]></description><link>https://blog.therishabhdev.com/know-about-models-in-django</link><guid isPermaLink="true">https://blog.therishabhdev.com/know-about-models-in-django</guid><category><![CDATA[Django]]></category><category><![CDATA[Python]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[backend]]></category><category><![CDATA[webdev]]></category><dc:creator><![CDATA[Rishabh Kumar Bahukhandi]]></dc:creator><pubDate>Wed, 07 Dec 2022 11:38:07 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1670181651271/APy07zL7T.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-introduction-to-django-models">Introduction to Django models</h1>
<p>In the process of learning Django, you surely will come across Django models. It is an important component of any Django application. Having good knowledge is essential to create an efficient web application using Django.</p>
<p>Django models define the fields and behavior of the data to be stored. Generally, a single model class defines a single table in the database. Models have fields that represent the columns of the table. We can also provide additional constraints to control what is stored.</p>
<h2 id="heading-how-to-define-models">How to define models</h2>
<p>Django models are simply just classes that subclass <code>django.db.models.Model</code>. Each attribute of a model class is an instance of the appropriate Field class. The Field class determines the type of data stored, the minimum validation required and the widget which will be used while rendering the form field.</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> django.db <span class="hljs-keyword">import</span> models

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Manufacturer</span>(<span class="hljs-params">models.Model</span>):</span>
  name = models.CharField(max_length=<span class="hljs-number">20</span>)

  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__str__</span>(<span class="hljs-params">self</span>):</span>
    <span class="hljs-keyword">return</span> self.name


<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Car</span>(<span class="hljs-params">models.Model</span>):</span>
  model = models.CharField(max_length=<span class="hljs-number">20</span>)
  year = models.PositiveIntegerField()
  manufacturer = models.ForeignKey(Manufacturer, on_delete=models.CASCADE)
</code></pre>
<p>In this code snippet, two models are declared namely Manufacturer and Car. The Manufacturer model has only one field which is <code>name</code> which can contain text of size at most 20 characters whereas the Car model has three fields, namely <code>model</code> that can contain text of size at most 20 characters, <code>year</code> field which can contain only positive integers and <code>manufacturer</code> field that references a Manufacturer in the Manufacturer table.</p>
<h2 id="heading-various-fields-for-models">Various Fields for models</h2>
<p>There are many different Field classes to store different types of data like integers, text, date, time and so on.</p>
<h3 id="heading-here-are-some-of-the-field-classes">Here are some of the Field Classes</h3>
<ul>
<li><p><code>CharField</code> - stores string data</p>
</li>
<li><p><code>IntegerField</code> - stores integer</p>
</li>
<li><p><code>PositiveIntegerField</code> - stores only positive integer</p>
</li>
<li><p><code>DataTimeField</code> - stores date and time</p>
</li>
<li><p><code>DateField</code> - stores only date</p>
</li>
<li><p><code>BooleanField</code> - stores true/false value</p>
</li>
<li><p><code>DecimalField</code> - stores numbers with a decimal point</p>
</li>
<li><p><code>EmailField</code> - stores email</p>
</li>
<li><p><code>FileField</code> - for storing file</p>
</li>
<li><p><code>TextField</code> - for storing large text</p>
</li>
<li><p><code>ImageField</code> - for storing images, and many more...</p>
</li>
</ul>
<p>All Field classes have some common optional arguments. Here are some of them:</p>
<ul>
<li><p><strong>null</strong> - whether you want to allow storing null as a value, the default value is False</p>
</li>
<li><p><strong>blank</strong> - when set to True it allows the field to be blank</p>
</li>
<li><p><strong>choices</strong> - it allows you to have a value from a set of values. For using this option pass a list of 2-tuples to it with the first value of every tuple as the value you want to store and the second value as the display value that the user sees.</p>
</li>
<li><p><strong>default</strong> - use it to give a default value to the field</p>
</li>
<li><p><strong>primary_key</strong> - to use the field as a primary key for the model</p>
</li>
<li><p><strong>unique</strong> - to apply the unique constraint to the field</p>
</li>
</ul>
<h2 id="heading-defining-relationships">Defining Relationships</h2>
<p>Relating different tables to each other is a powerful feature of RDBMS. Django provides ways to implement different relations like one-to-one, many-to-one and many-to-many.</p>
<p><strong>One-to-One relationship</strong></p>
<p>To form an OneToOne relationship we use <code>models.OneToOneField</code></p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> django.db <span class="hljs-keyword">import</span> models

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span>(<span class="hljs-params">models.Model</span>):</span>
    name = models.CharField(max_length=<span class="hljs-number">30</span>)
    age = models.PositiveIntegerField()

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Profile</span>(<span class="hljs-params">models.Model</span>):</span>
    user = models.OneToOneField(User,on_delete=models.CASCADE)
    location = models.CharField(max_length=<span class="hljs-number">100</span>)
</code></pre>
<p>Here we have defined a one-to-one relation between the user model and the profile model. Now in the database, we can store only a single Profile relating to a single user or vice versa.</p>
<p><strong>Many-to-One relationship</strong></p>
<p>To define a many-to-one relationship between two tables, we use <code>models.ForeignKey()</code><strong>.</strong> It needs two parameters, first is the Model with which you want to create the relationship and the second is the <code>on_delete</code> positional argument to define the behavior of the model when the related record is deleted from the related table.</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> django.db <span class="hljs-keyword">import</span> models
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Author</span>(<span class="hljs-params">models.Model</span>):</span>
    name = models.CharField(max_length=<span class="hljs-number">30</span>)
    country = models.CharField(max_length=<span class="hljs-number">40</span>)


<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Book</span>(<span class="hljs-params">models.Model</span>):</span>
    title = models.CharField(max_length=<span class="hljs-number">60</span>)
    author = models.ForeignKey(Author, on_delete=models.CASCADE)
</code></pre>
<p>Here in the above snippet, we have defined two Models viz. Author and Book. Many-to-One relation defined in <code>Book</code> will allow an <code>Author</code> to have multiple '<strong>Books</strong>' but no 'Book' can have more than one Author.</p>
<p><strong>Many-to-Many relationship</strong></p>
<p>For creating Many-to-many relationship, we use <code>models.ManyToManyField()</code><strong>.</strong> It takes in another model as an argument to form a relationship. While defining a many-to-many relationship, you don't need to define the relation in both models just define it in one model.</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> django.db <span class="hljs-keyword">import</span> models

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Student</span>(<span class="hljs-params">models.Model</span>):</span>
    name = models.CharField(max_length=<span class="hljs-number">50</span>)
    age = models.PositiveIntegerField()


<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Course</span>(<span class="hljs-params">models.Model</span>):</span>
    title = models.CharField(max_length=<span class="hljs-number">50</span>)
    students = models.ManyToManyField(Student)
</code></pre>
<p>Now a student can have multiple courses and a course can have multiple students. For more in-depth information regarding <code>ManyToManyField</code> follow this link to the <a target="_blank" href="https://docs.djangoproject.com/en/4.1/topics/db/models/#many-to-many-relationships">Django documentation</a></p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>For developing a decent application using <strong>RDBMS</strong>, it is really important to have good knowledge of different types of relationships. Being good with <strong>RDBMS</strong> concepts will help you manage data efficiently. It is not much important what you are using but how you are using it. Keep learning keep building stuff.</p>
<p><strong><em>In the next blog</em></strong>, we are going to see <strong><em>how to perform queries using the automatically-generated database-access API</em></strong>.</p>
<h3 id="heading-follow-for-more-django-content"><mark>#Follow for more </mark> <strong><mark>Django</mark></strong> <mark>content</mark></h3>
]]></content:encoded></item><item><title><![CDATA[Structure of Django Application]]></title><description><![CDATA[Introduction to Django
Django is one of the most popular backend frameworks out there in the market. It is written in python. It is known for its development speed. A project in Django can be up and running in a minimal amount of time. It has a very ...]]></description><link>https://blog.therishabhdev.com/structure-of-django-application</link><guid isPermaLink="true">https://blog.therishabhdev.com/structure-of-django-application</guid><category><![CDATA[Django]]></category><category><![CDATA[MVT]]></category><category><![CDATA[Python]]></category><category><![CDATA[backend]]></category><category><![CDATA[Web Development]]></category><dc:creator><![CDATA[Rishabh Kumar Bahukhandi]]></dc:creator><pubDate>Sat, 03 Dec 2022 13:07:20 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1670069534996/XY3u2pVcn.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-introduction-to-django">Introduction to Django</h1>
<p><strong>Django is one of the most popular backend frameworks</strong> out there in the market. It is written in python. It is known for its <strong>development speed</strong>. A project in Django can be up and running in a minimal amount of time. It has a very supportive community and many big websites use Django, here are some of them <strong>Mozilla, Instagram, Disqus, National Geographics, Pinterest and many more</strong>.</p>
<h2 id="heading-mvt-model">MVT Model</h2>
<p>Django applications follow MVT architecture which stands for <strong>M</strong>odel <strong>V</strong>iew <strong>T</strong>emplate. There are other architectures like MVC(Model View Controller) followed by other frameworks like Spring in Java. Below is the explanation of Each component of MVT architecture.</p>
<h2 id="heading-models">Models</h2>
<p>Model refers to the database layer that stores, manipulate and retrieve data from the database. In Django, we define models by creating a class that subclasses <code>django.db.models.Model</code> and define fields we want to include in the database as class attributes with built-in Field classes.</p>
<pre><code class="lang-python"><span class="hljs-comment"># Example of Django model</span>
<span class="hljs-keyword">from</span> django.db <span class="hljs-keyword">import</span> models

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Person</span>(<span class="hljs-params">models.Model</span>):</span>
    name = models.CharField(max_length=<span class="hljs-number">50</span>)
    age = models.PositiveIntegerField(default=<span class="hljs-number">0</span>)
    occupation = models.CharField(max_length=<span class="hljs-number">50</span>)
</code></pre>
<h2 id="heading-views">Views</h2>
<p>View refers to the layer that contains all the business logic and this layer interacts with the Model for data and returns an HTML document. There are two types of views in Django functional views and class-based views though, both do the same task.</p>
<pre><code class="lang-python"><span class="hljs-comment"># Example Django View function</span>
<span class="hljs-keyword">from</span> django.shortcuts <span class="hljs-keyword">import</span> render
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">home</span>(<span class="hljs-params">request</span>):</span>
    name = <span class="hljs-string">"fuzzydevs"</span>
    context = {<span class="hljs-string">'name'</span>:name}
    <span class="hljs-keyword">return</span> render(request, <span class="hljs-string">"home.html"</span>, context=context)
</code></pre>
<h2 id="heading-templates">Templates</h2>
<p>Templates are HTML files with placeholders for data. Django has its own templating language that resembles Jinja templating language. Django Template Language has many constructs like loops, conditional statements, inheritance, and so on. Templates are the presentation layer of the Django Applications.</p>
<h2 id="heading-url-paths">URL paths</h2>
<p>URL paths in Django are defined as a list of <em>path functions that</em> contains a URL string, a view function that handles the request, and an optional name for the path as arguments.</p>
<pre><code class="lang-python"><span class="hljs-comment"># Example of url path</span>
<span class="hljs-keyword">from</span> django.urls <span class="hljs-keyword">import</span> path
urlpatterns = [
path(<span class="hljs-string">''</span>,views.home, name=<span class="hljs-string">"home"</span>),
path(<span class="hljs-string">'form/'</span>,views.form_handler, name=<span class="hljs-string">"form handler"</span>),
]
</code></pre>
<p>Generally, paths of different Django apps in the project are defined in a file called <code>urls.py</code> in each app and are included in the main project <code>urls.py</code> file.</p>
<h2 id="heading-flow-of-application">Flow of Application</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1670069742203/8zuHVYe72.png" alt /></p>
<p>The request is handled by the Django application and passed on to the appropriate View function as defined in the <strong>urlConf</strong>(where URLs are defined). The View function performs the business logic and interacts with Models as needed and passes the data and template to the <strong>Template engine</strong> which combines the data and template, spits out the HTML document with data in it. The final <strong>HTML document</strong> is returned from the view function as a response to the viewer.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>This is a simplified explanation of how the Django applications work, and how it handles the request and returns a response for the corresponding request. I have also shown how we define models, views and URLs in a Django project. In the next blog, we will learn about Django models in-depth.</p>
<h3 id="heading-follow-for-more-upcoming-django-content"><mark>#</mark><em><mark>Follow</mark></em> <mark>for more upcoming </mark> <em><mark>Django Content</mark></em></h3>
]]></content:encoded></item><item><title><![CDATA[This is how I started my Web dev Journey]]></title><description><![CDATA[Introduction
When I was just exploring different domains of tech, I decided to get started with web development. Web development is one of the most in-demand skills in the Industry. So, I started a course on Udemy.
Foundation

From the course that I ...]]></description><link>https://blog.therishabhdev.com/this-is-how-i-started-my-web-dev-journey</link><guid isPermaLink="true">https://blog.therishabhdev.com/this-is-how-i-started-my-web-dev-journey</guid><category><![CDATA[Experience ]]></category><category><![CDATA[Django]]></category><category><![CDATA[Learning Journey]]></category><category><![CDATA[Web Development]]></category><dc:creator><![CDATA[Rishabh Kumar Bahukhandi]]></dc:creator><pubDate>Sat, 26 Nov 2022 14:55:23 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1669321752807/tkJ8Xa4KU.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>When I was just exploring different domains of tech, I decided to get started with web development. Web development is one of the most in-demand skills in the Industry. So, I started a course on Udemy.</p>
<h2 id="heading-foundation">Foundation</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1669411954735/Al_4tfbib.png" alt="1.png" /></p>
<p>From the course that I was doing, I learned HTML, CSS and javascript. I learned about different HTML tags like image, heading, paragraph, semantic tags and a lot more. In CSS I learned about different properties, pseudo-classes, units, flexbox, grid and mediaquery. I wasn't using Javascript much whenever I was creating webpages.</p>
<h2 id="heading-improving-the-basics">Improving the basics</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1669411969054/xKrixBaaJ.png" alt="2.png" /></p>
<p>To improve my HTML and CSS skills I started implementing designs that I found on the internet. It was challenging in beginning but as I kept pushing forward it started to feel easy. I would say to improve a skill you need to gradually increase the intensity, in this case, the complexity of design to implement.</p>
<h2 id="heading-a-short-break">A short break</h2>
<p>I started to get bored with it and I started to learn some other stuff(ML and AI), it sounds cool, right? So for the next 6 months, I learned nothing about web development. Just tried different technologies like TensorFlow, flutter and so on. Then I realized that I should stick to one thing and try to absorb it completely.</p>
<h2 id="heading-getting-started-with-the-backend">Getting started with the backend</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1669412020247/50U4yH8vj.png" alt="3.png" /></p>
<p>I felt like I should stick to web development and learn the backend. So I chose Spring framework in Java. As I started learning spring, I started to enjoy the learning process. For me working on the backend was exciting, but soon I realized that for building an MVP or for just building a simple website spring was not a good choice. In java, a ton of code has to be written. In the end, I switched from Spring to Django. I don't know if Django was too easy to learn or if I am a good learner but I finished the basics of Django in a week whereas for Spring it took me almost a month to reach the authentication part. Whatever the case may be, I created a Blog in it from scratch though I later learned that there are various projects which make it too easy to build blog applications in Django.</p>
<p>Similarly, I built some other projects to reinforce my learning and also extend it. Since then I have been sticking to Django. The deeper I am going into Django, the more I am loving it.</p>
<p>If you are interested in learning Django you can check out my <a target="_blank" href="https://rishabhdev.hashnode.dev/series/django-projects">Django-project Series</a></p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>I started from the basics and improved by practicing and applying the knowledge I had gained. If I hadn't taken the 'short break', I might have gained more knowledge and experience. Building projects helped me a lot, trying different approaches is a great way to improve development skills. So try building different stuff to keep challenging yourself.</p>
<h4 id="heading-what-do-you-think-are-different-ways-to-test-your-newly-acquired-skill"><strong><em>What do you think are different ways to test your newly acquired skill?</em></strong></h4>
]]></content:encoded></item><item><title><![CDATA[Mistakes that I made when I started learning coding]]></title><description><![CDATA[Introduction
After my 12th Standard board exams, I decided that I would start coding, though few years earlier I learnt some basic Java, but that was all that I knew. The thing was, I was fascinated by the concept of programming computer. So I made u...]]></description><link>https://blog.therishabhdev.com/mistakes-that-i-made-when-i-started-learning-coding</link><guid isPermaLink="true">https://blog.therishabhdev.com/mistakes-that-i-made-when-i-started-learning-coding</guid><category><![CDATA[#codingNewbies]]></category><category><![CDATA[beginnersguide]]></category><dc:creator><![CDATA[Rishabh Kumar Bahukhandi]]></dc:creator><pubDate>Thu, 24 Nov 2022 19:59:44 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1669316944311/GXBjWPqt3.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>After my 12th Standard board exams, I decided that I would start coding, though few years earlier I learnt some basic Java, but that was all that I knew. The thing was, I was fascinated by the concept of programming computer. So I made up my mind to learn python which is one of the most popular language. Just at that time lockdown was declared. So, I had nothing else to do I went all in Python and finished the basics and OOPs in two weeks.</p>
<h2 id="heading-first-mistake">First mistake</h2>
<p><strong><em>I didn't make any project</em></strong>  with whatever I had learnt. But soon I started project based learning and started applying my learnings. Thank god I realized it sooner.</p>
<h2 id="heading-second-mistake">Second Mistake</h2>
<p><strong><em>I didn't stick to a single technology and kept jumping from one tech to another.</em></strong>
After the Python I started learning web development. I started learning HTML, CSS and Javascript. Learnt to build some basic webpages. Then I got bored and went into data science and machine learning stuff. Though most of the stuff went right above my head.</p>
<h2 id="heading-third-mistake">Third Mistake</h2>
<p><strong><em>I was learning all alone</em></strong>. When we learn alone we are not able to know the level of knowledge we have gathered. Since we have no competition/rival we tend to get lazy. I kept on learning alone but soon met some like minded people. It helped me a lot mentally. I started feeling motivated and confident.</p>
<h2 id="heading-fourth-mistake">Fourth Mistake</h2>
<p><strong><em>Getting into cool stuff without learning the basics</em></strong>. Whenever I started something new I jumped directly into the stuff which seemed cool and skipping basics slows down the learning process a lot.</p>
<h2 id="heading-fifth-mistake">Fifth Mistake</h2>
<p><strong><em>Not trying to learn a technology in-depth</em></strong>.
We all tend to learn only the basics of a technology and when we feel it is getting complex and hard we chicken out. And this separates an expert from a normal person. <strong>Just get your hands dirty and try complex things.</strong></p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Finally these were some of the mistakes which I made in the beginning. I had no one to guide me and help me out with this. So, the summary is </p>
<ul>
<li>Build Projects</li>
<li>Stick to a single technology and learn it perfectly, partially learning is of no use.</li>
<li>Find a group with same interest as you or having same goal</li>
<li>Learn the basics before jumping into cool stuff</li>
<li>Learn the technology in-depth, get comfortable with advance stuff</li>
</ul>
<h4 id="heading-what-do-think-are-some-other-mistakes-to-avoid-comment-down">What do think are some other mistakes to avoid? Comment down.</h4>
]]></content:encoded></item></channel></rss>