<?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[Aarav's Blogs]]></title><description><![CDATA[Aarav's Blogs]]></description><link>https://blog.aarav.com.np</link><generator>RSS for Node</generator><lastBuildDate>Sun, 19 Apr 2026 09:59:37 GMT</lastBuildDate><atom:link href="https://blog.aarav.com.np/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Using Media Files in Django]]></title><description><![CDATA[This is must-know Django stuff 👍Let’s walk through media files in Django clearly, from setup → usage → best practices.

1️⃣ What are media files?
Media files are user-uploaded files, like:

Profile photos

Blog featured images

PDFs, documents, etc....]]></description><link>https://blog.aarav.com.np/using-media-files-in-django</link><guid isPermaLink="true">https://blog.aarav.com.np/using-media-files-in-django</guid><dc:creator><![CDATA[Aarav Poudel]]></dc:creator><pubDate>Sun, 08 Feb 2026 02:36:32 GMT</pubDate><content:encoded><![CDATA[<p>This is <em>must-know</em> Django stuff 👍Let’s walk through <strong>media files in Django</strong> clearly, from setup → usage → best practices.</p>
<hr />
<h2 id="heading-1-what-are-media-files">1️⃣ What are media files?</h2>
<p>Media files are <strong>user-uploaded files</strong>, like:</p>
<ul>
<li><p>Profile photos</p>
</li>
<li><p>Blog featured images</p>
</li>
<li><p>PDFs, documents, etc.</p>
</li>
</ul>
<p>👉 Different from <strong>static files</strong> (CSS, JS, images you ship with code).</p>
<hr />
<h2 id="heading-2-basic-settings-very-important">2️⃣ Basic settings (very important)</h2>
<h3 id="heading-in-your-projects-settingspyhttpsettingspy-file-add-these-mediaurl-and-mediaroot">In your project’s <a target="_blank" href="http://settings.py"><code>settings.py</code></a> file.. add these ‘MEDIA_URL’ AND ‘MEDIA_ROOT’</h3>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> os
<span class="hljs-keyword">from</span> pathlib <span class="hljs-keyword">import</span> Path

BASE_DIR = Path(__file__).resolve().parent.parent

MEDIA_URL = <span class="hljs-string">'/media/'</span>
MEDIA_ROOT = BASE_DIR / <span class="hljs-string">'media'</span>
</code></pre>
<ul>
<li><p><code>MEDIA_URL</code> → URL prefix</p>
</li>
<li><p><code>MEDIA_ROOT</code> → physical folder on disk</p>
</li>
</ul>
<p>📁 Result:</p>
<pre><code class="lang-plaintext">project/
│
├── media/
│   └── blog/images/
├── static/
├── app/
└── manage.py
</code></pre>
<hr />
<h2 id="heading-3-model-with-media-field">3️⃣ Model with media field</h2>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">BlogPost</span>(<span class="hljs-params">models.Model</span>):</span>
    title = models.CharField(max_length=<span class="hljs-number">200</span>)
    image = models.ImageField(
        upload_to=<span class="hljs-string">'blog/images/'</span>,
        blank=<span class="hljs-literal">True</span>,
        null=<span class="hljs-literal">True</span>
    )
</code></pre>
<p>📌 Install Pillow (required for images):</p>
<pre><code class="lang-bash">pip install pillow
</code></pre>
<hr />
<h2 id="heading-4-show-media-in-django-admin">4️⃣ Show media in Django admin</h2>
<p>Admin already handles media uploads automatically.</p>
<pre><code class="lang-python"><span class="hljs-meta">@admin.register(BlogPost)</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">BlogPostAdmin</span>(<span class="hljs-params">admin.ModelAdmin</span>):</span>
    list_display = (<span class="hljs-string">'title'</span>, <span class="hljs-string">'image'</span>)
</code></pre>
<hr />
<h2 id="heading-5-serve-media-during-development-crucial">5️⃣ Serve media during development (CRUCIAL)</h2>
<h3 id="heading-urlspyhttpurlspy-project-level"><a target="_blank" href="http://urls.py"><code>urls.py</code></a> (project level)</h3>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> django.conf <span class="hljs-keyword">import</span> settings
<span class="hljs-keyword">from</span> django.conf.urls.static <span class="hljs-keyword">import</span> static

urlpatterns = [
    <span class="hljs-comment"># your urls here</span>
]

<span class="hljs-keyword">if</span> settings.DEBUG:
    urlpatterns += static(
        settings.MEDIA_URL,
        document_root=settings.MEDIA_ROOT
    )
</code></pre>
<p>⚠️ Without this, images <strong>won’t show in templates</strong>.</p>
<hr />
<h2 id="heading-6-using-media-in-templates">6️⃣ Using media in templates</h2>
<pre><code class="lang-html">{% if post.image %}
  <span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"{{ post.image.url }}"</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">"{{ post.title }}"</span>&gt;</span>
{% endif %}
</code></pre>
<p>🧠 <code>.url</code> gives the public URL<br />🧠 <code>.path</code> gives the filesystem path</p>
<hr />
<h2 id="heading-7-upload-via-forms">7️⃣ Upload via forms</h2>
<h3 id="heading-formspyhttpformspy"><a target="_blank" href="http://forms.py"><code>forms.py</code></a></h3>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> django <span class="hljs-keyword">import</span> forms
<span class="hljs-keyword">from</span> .models <span class="hljs-keyword">import</span> BlogPost

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">BlogPostForm</span>(<span class="hljs-params">forms.ModelForm</span>):</span>
    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Meta</span>:</span>
        model = BlogPost
        fields = [<span class="hljs-string">'title'</span>, <span class="hljs-string">'image'</span>]
</code></pre>
<h3 id="heading-templatehtml"><code>template.html</code></h3>
<pre><code class="lang-html"><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 %}
    {{ form.as_p }}
    <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span>&gt;</span>Save<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
</code></pre>
<p>🚨 <code>enctype="multipart/form-data"</code> is mandatory</p>
<hr />
<h2 id="heading-8-handle-media-in-views">8️⃣ Handle media in views</h2>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">create_post</span>(<span class="hljs-params">request</span>):</span>
    <span class="hljs-keyword">if</span> request.method == <span class="hljs-string">'POST'</span>:
        form = BlogPostForm(request.POST, request.FILES)
        <span class="hljs-keyword">if</span> form.is_valid():
            form.save()
    <span class="hljs-keyword">else</span>:
        form = BlogPostForm()
</code></pre>
<hr />
<h2 id="heading-9-deleting-media-files-important">9️⃣ Deleting media files (important!)</h2>
<p>Django <strong>does NOT delete files automatically</strong> when a model is deleted.</p>
<h3 id="heading-auto-delete-using-signals">Auto-delete using signals</h3>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> django.db.models.signals <span class="hljs-keyword">import</span> post_delete
<span class="hljs-keyword">from</span> django.dispatch <span class="hljs-keyword">import</span> receiver

<span class="hljs-meta">@receiver(post_delete, sender=BlogPost)</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">delete_image</span>(<span class="hljs-params">sender, instance, **kwargs</span>):</span>
    <span class="hljs-keyword">if</span> instance.image:
        instance.image.delete(<span class="hljs-literal">False</span>)
</code></pre>
<hr />
<h2 id="heading-file-size-amp-type-validation">🔟 File size &amp; type validation</h2>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">validate_image_size</span>(<span class="hljs-params">file</span>):</span>
    max_size = <span class="hljs-number">2</span> * <span class="hljs-number">1024</span> * <span class="hljs-number">1024</span>  <span class="hljs-comment"># 2MB</span>
    <span class="hljs-keyword">if</span> file.size &gt; max_size:
        <span class="hljs-keyword">raise</span> ValidationError(<span class="hljs-string">"Max file size is 2MB"</span>)

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">BlogPost</span>(<span class="hljs-params">models.Model</span>):</span>
    image = models.ImageField(
        upload_to=<span class="hljs-string">'blog/images/'</span>,
        validators=[validate_image_size]
    )
</code></pre>
<hr />
<h2 id="heading-11-production-setup-important">11️⃣ Production setup (IMPORTANT)</h2>
<p>🚫 <strong>Never serve media using Django in production</strong></p>
<p>Use:</p>
<ul>
<li><p><strong>Nginx</strong></p>
</li>
<li><p><strong>S3 / Cloudflare R2</strong></p>
</li>
<li><p><strong>DigitalOcean Spaces</strong></p>
</li>
</ul>
<p>Example (Nginx):</p>
<pre><code class="lang-nginx"><span class="hljs-attribute">location</span> /media/ {
    <span class="hljs-attribute">alias</span> /path/to/media/;
}
</code></pre>
<hr />
<h2 id="heading-12-best-practices-real-world">12️⃣ Best practices (real-world)</h2>
<p>✔ Separate <code>static/</code> and <code>media/</code><br />✔ Validate file size &amp; type<br />✔ Use unique filenames (UUID)<br />✔ Delete unused files<br />✔ Use cloud storage for scalability</p>
<hr />
]]></content:encoded></item><item><title><![CDATA[Class and Objects in Python Review]]></title><description><![CDATA[Perfect timing to review this before Django 👍Django is very class-heavy, so getting this clear will make everything feel easier.

What is a Class in Python?
A class is a blueprint (template) to create objects.
Think:

Class → Design of a house 🏠

O...]]></description><link>https://blog.aarav.com.np/class-and-objects-in-python-review</link><guid isPermaLink="true">https://blog.aarav.com.np/class-and-objects-in-python-review</guid><category><![CDATA[Classes and Objects]]></category><dc:creator><![CDATA[Aarav Poudel]]></dc:creator><pubDate>Thu, 05 Feb 2026 04:33:51 GMT</pubDate><content:encoded><![CDATA[<p>Perfect timing to review this before Django 👍<br />Django is <strong>very class-heavy</strong>, so getting this clear will make everything feel easier.</p>
<hr />
<h2 id="heading-what-is-a-class-in-python">What is a Class in Python?</h2>
<p>A <strong>class</strong> is a blueprint (template) to create objects.</p>
<p>Think:</p>
<ul>
<li><p><strong>Class</strong> → Design of a house 🏠</p>
</li>
<li><p><strong>Object</strong> → Actual house built from that design</p>
</li>
</ul>
<hr />
<h2 id="heading-what-is-an-object">What is an Object?</h2>
<p>An <strong>object</strong> is an instance of a class.<br />It holds <strong>real data</strong> and can use the class’s <strong>methods</strong>.</p>
<hr />
<h2 id="heading-basic-example-very-important">Basic Example (Very Important)</h2>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Student</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, name, roll</span>):</span>
        self.name = name
        self.roll = roll

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">info</span>(<span class="hljs-params">self</span>):</span>
        print(self.name, self.roll)
</code></pre>
<h3 id="heading-creating-objects">Creating Objects</h3>
<pre><code class="lang-python">s1 = Student(<span class="hljs-string">"Aarav"</span>, <span class="hljs-number">1</span>)
s2 = Student(<span class="hljs-string">"Sita"</span>, <span class="hljs-number">2</span>)

s1.info()
s2.info()
</code></pre>
<h3 id="heading-output">Output</h3>
<pre><code class="lang-plaintext">Aarav 1
Sita 2
</code></pre>
<hr />
<h2 id="heading-key-terms-you-must-know">Key Terms You MUST Know</h2>
<h3 id="heading-1-init-constructor">1. <code>__init__</code> (Constructor)</h3>
<ul>
<li><p>Runs automatically when object is created</p>
</li>
<li><p>Used to initialize data</p>
</li>
</ul>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self</span>):</span>
    <span class="hljs-keyword">pass</span>
</code></pre>
<hr />
<h3 id="heading-2-self">2. <code>self</code></h3>
<ul>
<li><p>Refers to <strong>current object</strong></p>
</li>
<li><p>Without <code>self</code>, Django will break 😄</p>
</li>
</ul>
<p>❌ Wrong:</p>
<pre><code class="lang-python">name = name
</code></pre>
<p>✅ Correct:</p>
<pre><code class="lang-python">self.name = name
</code></pre>
<hr />
<h2 id="heading-class-variables-vs-instance-variables">Class Variables vs Instance Variables</h2>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">College</span>:</span>
    college_name = <span class="hljs-string">"ABC College"</span>   <span class="hljs-comment"># class variable</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, student</span>):</span>
        self.student = student     <span class="hljs-comment"># instance variable</span>
</code></pre>
<pre><code class="lang-python">c1 = College(<span class="hljs-string">"Ram"</span>)
c2 = College(<span class="hljs-string">"Shyam"</span>)

print(c1.college_name)
print(c2.college_name)
</code></pre>
<hr />
<h2 id="heading-methods-in-class">Methods in Class</h2>
<h3 id="heading-instance-method">Instance Method</h3>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">show</span>(<span class="hljs-params">self</span>):</span>
    print(self.name)
</code></pre>
<h3 id="heading-class-method">Class Method</h3>
<pre><code class="lang-python"><span class="hljs-meta">@classmethod</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">college</span>(<span class="hljs-params">cls</span>):</span>
    print(<span class="hljs-string">"ABC College"</span>)
</code></pre>
<h3 id="heading-static-method">Static Method</h3>
<pre><code class="lang-python"><span class="hljs-meta">@staticmethod</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">hello</span>():</span>
    print(<span class="hljs-string">"Hello"</span>)
</code></pre>
<hr />
<h2 id="heading-inheritance-very-important-for-django">Inheritance (VERY IMPORTANT FOR DJANGO)</h2>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">login</span>(<span class="hljs-params">self</span>):</span>
        print(<span class="hljs-string">"User logged in"</span>)

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Admin</span>(<span class="hljs-params">User</span>):</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">delete</span>(<span class="hljs-params">self</span>):</span>
        print(<span class="hljs-string">"Deleted"</span>)
</code></pre>
<pre><code class="lang-python">a = Admin()
a.login()
a.delete()
</code></pre>
<p>➡ Django uses inheritance everywhere (<code>models.Model</code>, <code>views.View</code>)</p>
<hr />
<h2 id="heading-encapsulation-basics">Encapsulation (Basics)</h2>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Bank</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, balance</span>):</span>
        self.__balance = balance  <span class="hljs-comment"># private</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_balance</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">return</span> self.__balance
</code></pre>
<hr />
<h2 id="heading-why-classes-matter-in-django-big-picture">Why Classes Matter in Django (BIG PICTURE)</h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Django Part</td><td>Class Usage</td></tr>
</thead>
<tbody>
<tr>
<td>Models</td><td><code>class Product(models.Model)</code></td></tr>
<tr>
<td>Views</td><td><code>class ProductView(View)</code></td></tr>
<tr>
<td>Forms</td><td><code>class ProductForm(forms.ModelForm)</code></td></tr>
<tr>
<td>Admin</td><td><code>class ProductAdmin(admin.ModelAdmin)</code></td></tr>
</tbody>
</table>
</div><hr />
<h2 id="heading-django-style-preview-example">Django-Style Preview Example</h2>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Product</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, name, price</span>):</span>
        self.name = name
        self.price = price

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">discounted_price</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">return</span> self.price - <span class="hljs-number">10</span>
</code></pre>
<p>➡ This is <strong>exactly how Django Models think</strong>, just with extra magic.</p>
<hr />
<h2 id="heading-quick-practice-tasks-before-django">Quick Practice Tasks (Before Django)</h2>
<h3 id="heading-task-1">Task 1</h3>
<p>Create a class <code>Teacher</code> with:</p>
<ul>
<li><p>name</p>
</li>
<li><p>subject</p>
</li>
<li><p>method <code>details()</code></p>
</li>
</ul>
<hr />
<h3 id="heading-task-2">Task 2</h3>
<p>Create a class <code>Car</code>:</p>
<ul>
<li><p>brand (class variable)</p>
</li>
<li><p>model</p>
</li>
<li><p>method <code>show()</code></p>
</li>
</ul>
<hr />
<h3 id="heading-task-3-django-mindset">Task 3 (Django mindset)</h3>
<p>Create:</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span>:</span>
    username
    email
    method: display()
</code></pre>
<hr />
]]></content:encoded></item><item><title><![CDATA[Setting up Django Project with virtual Environment]]></title><description><![CDATA[I’ll walk you through Django + virtual environment on Linux and Windows, step-by-step, clean and beginner-safe.

1️⃣ Prerequisites (both Linux & Windows)
Make sure Python is installed:
python --version

or
python3 --version

If it prints Python 3.x.x...]]></description><link>https://blog.aarav.com.np/setting-up-django-project-with-virtual-environment</link><guid isPermaLink="true">https://blog.aarav.com.np/setting-up-django-project-with-virtual-environment</guid><category><![CDATA[djangoproject]]></category><category><![CDATA[Django]]></category><dc:creator><![CDATA[Aarav Poudel]]></dc:creator><pubDate>Wed, 04 Feb 2026 03:18:19 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1770174380054/372e8e01-8779-4e11-9883-66d897838a19.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>I’ll walk you through <strong>Django + virtual environment</strong> on <strong>Linux</strong> and <strong>Windows</strong>, step-by-step, clean and beginner-safe.</p>
<hr />
<h2 id="heading-1-prerequisites-both-linux-amp-windows">1️⃣ Prerequisites (both Linux &amp; Windows)</h2>
<p>Make sure Python is installed:</p>
<pre><code class="lang-bash">python --version
</code></pre>
<p>or</p>
<pre><code class="lang-bash">python3 --version
</code></pre>
<p>If it prints <code>Python 3.x.x</code>, you’re good.</p>
<hr />
<h2 id="heading-2-create-a-project-folder">2️⃣ Create a Project Folder</h2>
<pre><code class="lang-bash">mkdir django_project
<span class="hljs-built_in">cd</span> django_project
</code></pre>
<p>This folder will hold:</p>
<ul>
<li><p>virtual environment</p>
</li>
<li><p>Django project code</p>
</li>
</ul>
<hr />
<h1 id="heading-windows-cmd-powershell">🪟 WINDOWS (CMD / PowerShell)</h1>
<h2 id="heading-3-create-virtual-environment">3️⃣ Create Virtual Environment</h2>
<pre><code class="lang-plaintext">python -m venv env
</code></pre>
<hr />
<h2 id="heading-4-activate-virtual-environment">4️⃣ Activate Virtual Environment</h2>
<h3 id="heading-cmd">▶ CMD</h3>
<pre><code class="lang-plaintext">env\Scripts\activate
</code></pre>
<h3 id="heading-powershell">▶ PowerShell</h3>
<pre><code class="lang-powershell">env\Scripts\Activate.ps1
</code></pre>
<p>If PowerShell blocks it, run <strong>once</strong> as admin:</p>
<pre><code class="lang-powershell"><span class="hljs-built_in">Set-ExecutionPolicy</span> RemoteSigned
</code></pre>
<p>Then activate again.</p>
<p>You’ll see:</p>
<pre><code class="lang-text">(env) C:\django_project&gt;
</code></pre>
<hr />
<h2 id="heading-5-upgrade-pip">5️⃣ Upgrade pip</h2>
<pre><code class="lang-plaintext">python -m pip install --upgrade pip
</code></pre>
<hr />
<h2 id="heading-6-install-django">6️⃣ Install Django</h2>
<pre><code class="lang-plaintext">pip install django
</code></pre>
<p>Check:</p>
<pre><code class="lang-plaintext">django-admin --version
</code></pre>
<hr />
<h2 id="heading-7-create-django-project">7️⃣ Create Django Project</h2>
<pre><code class="lang-plaintext">django-admin startproject mysite .
</code></pre>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">here specifying <code>mysite .</code> will create the project in current folder/directory as . represent current directory</div>
</div>

<pre><code class="lang-plaintext">django-admin startproject mysite
cd mysite
</code></pre>
<hr />
<h2 id="heading-8-run-server">8️⃣ Run Server</h2>
<pre><code class="lang-plaintext">python manage.py runserver
</code></pre>
<p>Open browser 👉<br />👉 <a target="_blank" href="http://127.0.0.1:8000/"><strong>http://127.0.0.1:8000/</strong></a></p>
<hr />
<h2 id="heading-9-deactivate-virtual-environment">9️⃣ Deactivate Virtual Environment</h2>
<pre><code class="lang-plaintext">deactivate
</code></pre>
<hr />
<h1 id="heading-linux-ubuntu-debian-arch-etc">🐧 LINUX (Ubuntu, Debian, Arch, etc.)</h1>
<h2 id="heading-create-virtual-environment">Create Virtual Environment</h2>
<pre><code class="lang-bash">python3 -m venv env
</code></pre>
<p>This creates a folder called <code>env</code>.</p>
<hr />
<h2 id="heading-activate-virtual-environment">Activate Virtual Environment</h2>
<pre><code class="lang-bash"><span class="hljs-built_in">source</span> env/bin/activate
</code></pre>
<p>You’ll see something like:</p>
<pre><code class="lang-text">(env) user@machine:~/django_project$
</code></pre>
<p>👉 This means <strong>virtual env is active</strong></p>
<hr />
<h2 id="heading-upgrade-pip-recommended">Upgrade pip (recommended)</h2>
<pre><code class="lang-bash">pip install --upgrade pip
</code></pre>
<hr />
<h2 id="heading-install-django">Install Django</h2>
<pre><code class="lang-bash">pip install django
</code></pre>
<p>Verify:</p>
<pre><code class="lang-bash">django-admin --version
</code></pre>
<hr />
<h2 id="heading-create-django-project">Create Django Project</h2>
<pre><code class="lang-bash">django-admin startproject mysite
<span class="hljs-built_in">cd</span> mysite
</code></pre>
<p>Folder structure:</p>
<pre><code class="lang-text">django_project/
├── venv/
└── mysite/
    ├── manage.py
    └── mysite/
</code></pre>
<hr />
<h2 id="heading-run-development-server">Run Development Server</h2>
<pre><code class="lang-bash">python manage.py runserver
</code></pre>
<p>Open browser 👉<br />👉 <a target="_blank" href="http://127.0.0.1:8000/"><strong>http://127.0.0.1:8000/</strong></a></p>
<p>🎉 Django welcome page = SUCCESS</p>
<hr />
<h2 id="heading-deactivate-virtual-environment">Deactivate Virtual Environment</h2>
<pre><code class="lang-bash">deactivate
🔥 Common Mistakes (Important)
</code></pre>
<p>❌ Forgetting to activate venv<br />❌ Installing Django globally<br />❌ Running <code>runserver</code> outside project folder<br />❌ Using <code>python</code> vs <code>python3</code> incorrectly on Linux</p>
<hr />
<h1 id="heading-pro-tip-best-practice">🧠 Pro Tip (Best Practice)</h1>
<p>Managing Dependency using <code>pip freeze</code></p>
<p><code>pip freeze</code> will output the list of packages with versions installed in the current virtual environment (if activated)</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1770175610052/2a5b0c36-0a57-4a9d-ad8e-4a648ab3b9aa.png" alt class="image--center mx-auto" /></p>
<p>We can then save that list to a file named <code>requirements.txt</code> for future ( so we can reinstall everything in new setup environment)</p>
<pre><code class="lang-bash">pip freeze &gt; requirements.txt
</code></pre>
<p>This will make a file named <code>requirements.txt</code> and save the output of <code>pip freeze</code> that has packages and its versions</p>
<p>Later you can install everything with:</p>
<pre><code class="lang-bash">pip install -r requirements.txt
</code></pre>
]]></content:encoded></item><item><title><![CDATA[Functions in Python]]></title><description><![CDATA[🔹 1. What is a Function in Python?
A function is a reusable block of code that performs a specific task.
Instead of writing the same code again and again, you define once, use many times.
Why functions?

Reduce code repetition

Improve readability

...]]></description><link>https://blog.aarav.com.np/functions-in-python</link><guid isPermaLink="true">https://blog.aarav.com.np/functions-in-python</guid><dc:creator><![CDATA[Aarav Poudel]]></dc:creator><pubDate>Mon, 02 Feb 2026 08:19:21 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1770020152440/d42df507-61dc-4f44-a622-384081bcbfe3.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-1-what-is-a-function-in-python">🔹 1. What is a Function in Python?</h1>
<p>A <strong>function</strong> is a reusable block of code that performs a specific task.</p>
<p>Instead of writing the same code again and again, you <strong>define once, use many times</strong>.</p>
<h3 id="heading-why-functions">Why functions?</h3>
<ul>
<li><p>Reduce code repetition</p>
</li>
<li><p>Improve readability</p>
</li>
<li><p>Make code modular &amp; testable</p>
</li>
<li><p>Easier debugging</p>
</li>
</ul>
<hr />
<h2 id="heading-2-basic-function-no-parameters">🔹 2. Basic Function (No Parameters)</h2>
<h3 id="heading-syntax">Syntax</h3>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">function_name</span>():</span>
    statements
</code></pre>
<h3 id="heading-example">Example</h3>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">greet</span>():</span>
    print(<span class="hljs-string">"Hello, World!"</span>)

greet()
</code></pre>
<p>📌 Output:</p>
<pre><code class="lang-plaintext">Hello, World!
</code></pre>
<hr />
<h3 id="heading-task-1">📝 Task 1</h3>
<p>Create a function <code>welcome()</code> that prints:</p>
<pre><code class="lang-plaintext">Welcome to Python Programming
</code></pre>
<hr />
<h1 id="heading-3-function-with-parameters-arguments">🔹 3. Function with Parameters (Arguments)</h1>
<p>Parameters allow us to <strong>pass data into a function</strong>.</p>
<h3 id="heading-example-1">Example</h3>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">greet</span>(<span class="hljs-params">name</span>):</span>
    print(<span class="hljs-string">"Hello"</span>, name)

greet(<span class="hljs-string">"Aarav"</span>)
greet(<span class="hljs-string">"Python"</span>)
</code></pre>
<p>📌 Output:</p>
<pre><code class="lang-plaintext">Hello Aarav
Hello Python
</code></pre>
<hr />
<h3 id="heading-task-2">📝 Task 2</h3>
<p>Write a function <code>square(n)</code> that prints the square of a number.</p>
<hr />
<h1 id="heading-4-function-with-return-value">🔹 4. Function with Return Value</h1>
<p>Instead of printing, functions can <strong>return values</strong>.</p>
<h3 id="heading-example-2">Example</h3>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">add</span>(<span class="hljs-params">a, b</span>):</span>
    <span class="hljs-keyword">return</span> a + b

result = add(<span class="hljs-number">5</span>, <span class="hljs-number">3</span>)
print(result)
</code></pre>
<p>📌 Output:</p>
<pre><code class="lang-plaintext">8
</code></pre>
<p>👉 <code>return</code> sends data back to the caller.</p>
<hr />
<h3 id="heading-task-3">📝 Task 3</h3>
<p>Create a function <code>is_even(n)</code> that returns <code>True</code> if number is even, else <code>False</code>.</p>
<hr />
<h1 id="heading-5-types-of-arguments-in-python">🔹 5. Types of Arguments in Python</h1>
<p>Python supports <strong>multiple ways to pass arguments</strong>:</p>
<hr />
<h2 id="heading-51-positional-arguments">✅ 5.1 Positional Arguments</h2>
<p>Order matters.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">student</span>(<span class="hljs-params">name, age</span>):</span>
    print(name, age)

student(<span class="hljs-string">"Ram"</span>, <span class="hljs-number">20</span>)
</code></pre>
<p>❌ Wrong order:</p>
<pre><code class="lang-python">student(<span class="hljs-number">20</span>, <span class="hljs-string">"Ram"</span>)  <span class="hljs-comment"># logical error</span>
</code></pre>
<hr />
<h3 id="heading-task-4">📝 Task 4</h3>
<p>Create a function <code>multiply(a, b, c)</code> and call it using positional arguments.</p>
<hr />
<h2 id="heading-52-keyword-arguments">✅ 5.2 Keyword Arguments</h2>
<p>You specify parameter names → order doesn’t matter.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">student</span>(<span class="hljs-params">name, age</span>):</span>
    print(name, age)

student(age=<span class="hljs-number">21</span>, name=<span class="hljs-string">"Sita"</span>)
</code></pre>
<hr />
<h3 id="heading-task-5">📝 Task 5</h3>
<p>Call <code>multiply()</code> using keyword arguments.</p>
<hr />
<h2 id="heading-53-default-arguments">✅ 5.3 Default Arguments</h2>
<p>Provide default values.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">greet</span>(<span class="hljs-params">name=<span class="hljs-string">"User"</span></span>):</span>
    print(<span class="hljs-string">"Hello"</span>, name)

greet()
greet(<span class="hljs-string">"Aarav"</span>)
</code></pre>
<hr />
<h3 id="heading-task-6">📝 Task 6</h3>
<p>Create a function <code>power(base, exp=2)</code> that returns base raised to power.</p>
<hr />
<h1 id="heading-6-args-variable-length-arguments">🔹 6. *args (Variable Length Arguments)</h1>
<p>Sometimes you <strong>don’t know how many arguments</strong> will be passed.</p>
<p>👉 <code>*args</code> stores values as a <strong>tuple</strong>.</p>
<hr />
<h3 id="heading-example-3">Example</h3>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">total</span>(<span class="hljs-params">*args</span>):</span>
    print(args)
    print(sum(args))

total(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>)
total(<span class="hljs-number">5</span>, <span class="hljs-number">10</span>, <span class="hljs-number">15</span>, <span class="hljs-number">20</span>)
</code></pre>
<p>📌 Output:</p>
<pre><code class="lang-plaintext">(1, 2, 3)
6
(5, 10, 15, 20)
50
</code></pre>
<hr />
<h3 id="heading-key-points">Key Points</h3>
<ul>
<li><p><code>args</code> is just a name (convention)</p>
</li>
<li><p><code>*</code> is important</p>
</li>
<li><p>Access like a tuple</p>
</li>
</ul>
<hr />
<h3 id="heading-task-7">📝 Task 7</h3>
<p>Write a function <code>average(*numbers)</code> that returns the average.</p>
<hr />
<h1 id="heading-7-kwargs-keyword-variable-length-arguments">🔹 7. **kwargs (Keyword Variable Length Arguments)</h1>
<p>Used when passing <strong>named arguments</strong> dynamically.</p>
<p>👉 <code>**kwargs</code> stores data as a <strong>dictionary</strong>.</p>
<hr />
<h3 id="heading-example-4">Example</h3>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">student_details</span>(<span class="hljs-params">**kwargs</span>):</span>
    print(kwargs)

student_details(name=<span class="hljs-string">"Aarav"</span>, age=<span class="hljs-number">21</span>, course=<span class="hljs-string">"CS"</span>)
</code></pre>
<p>📌 Output:</p>
<pre><code class="lang-plaintext">{'name': 'Aarav', 'age': 21, 'course': 'CS'}
</code></pre>
<hr />
<h3 id="heading-accessing-values">Accessing values</h3>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">student_details</span>(<span class="hljs-params">**kwargs</span>):</span>
    <span class="hljs-keyword">for</span> key, value <span class="hljs-keyword">in</span> kwargs.items():
        print(key, <span class="hljs-string">":"</span>, value)
</code></pre>
<hr />
<h3 id="heading-task-8">📝 Task 8</h3>
<p>Create a function <code>profile(**info)</code> that prints all key-value pairs.</p>
<hr />
<h1 id="heading-8-combining-arguments-advanced">🔹 8. Combining Arguments (Advanced)</h1>
<h3 id="heading-correct-order">Correct Order</h3>
<pre><code class="lang-plaintext">1. Positional
2. *args
3. Default
4. **kwargs
</code></pre>
<hr />
<h3 id="heading-example-5">Example</h3>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">demo</span>(<span class="hljs-params">a, b, *args, x=<span class="hljs-number">10</span>, **kwargs</span>):</span>
    print(a, b)
    print(args)
    print(x)
    print(kwargs)

demo(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, x=<span class="hljs-number">50</span>, name=<span class="hljs-string">"Ram"</span>, age=<span class="hljs-number">20</span>)
</code></pre>
<hr />
<h3 id="heading-task-9">📝 Task 9</h3>
<p>Create a function <code>bill(customer, *items, discount=0, **details)</code><br />Print customer, items, discount, and details.</p>
<hr />
<h1 id="heading-9-functions-as-objects-advanced-concept">🔹 9. Functions as Objects (Advanced Concept)</h1>
<p>Functions can be:</p>
<ul>
<li><p>Stored in variables</p>
</li>
<li><p>Passed as arguments</p>
</li>
<li><p>Returned from functions</p>
</li>
</ul>
<hr />
<h3 id="heading-example-6">Example</h3>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">add</span>(<span class="hljs-params">a, b</span>):</span>
    <span class="hljs-keyword">return</span> a + b

operation = add
print(operation(<span class="hljs-number">3</span>, <span class="hljs-number">4</span>))
</code></pre>
<hr />
<h3 id="heading-task-10">📝 Task 10</h3>
<p>Write a function <code>apply(func, a, b)</code> that applies any function to two numbers.</p>
<hr />
<h1 id="heading-10-lambda-functions-short-functions">🔹 10. Lambda Functions (Short Functions)</h1>
<p>One-line anonymous functions.</p>
<pre><code class="lang-python">square = <span class="hljs-keyword">lambda</span> x: x * x
print(square(<span class="hljs-number">5</span>))
</code></pre>
<hr />
<h3 id="heading-with-args">With args</h3>
<pre><code class="lang-python">add = <span class="hljs-keyword">lambda</span> *args: sum(args)
print(add(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>))
</code></pre>
<hr />
<h3 id="heading-task-11">📝 Task 11</h3>
<p>Create a lambda to check if a number is divisible by 5.</p>
<hr />
<h1 id="heading-11-real-world-example-mini-project">🔹 11. Real-World Example (Mini Project)</h1>
<h3 id="heading-student-marks-calculator">Student Marks Calculator</h3>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">calculate_marks</span>(<span class="hljs-params">name, *marks, **extra</span>):</span>
    total = sum(marks)
    avg = total / len(marks)

    print(<span class="hljs-string">"Name:"</span>, name)
    print(<span class="hljs-string">"Total:"</span>, total)
    print(<span class="hljs-string">"Average:"</span>, avg)

    <span class="hljs-keyword">if</span> <span class="hljs-string">"grade"</span> <span class="hljs-keyword">in</span> extra:
        print(<span class="hljs-string">"Grade:"</span>, extra[<span class="hljs-string">"grade"</span>])

calculate_marks(
    <span class="hljs-string">"Aarav"</span>,
    <span class="hljs-number">80</span>, <span class="hljs-number">75</span>, <span class="hljs-number">90</span>,
    grade=<span class="hljs-string">"A"</span>,
    remark=<span class="hljs-string">"Excellent"</span>
)
</code></pre>
<hr />
<h1 id="heading-final-practice-assignment-exam-level">✅ Final Practice Assignment (Exam-Level)</h1>
<ol>
<li><p>Write a function using <strong>default arguments</strong></p>
</li>
<li><p>Write a function using *<em>only args</em></p>
</li>
<li><p>Write a function using **only <strong>kwargs</strong></p>
</li>
<li><p>Combine all argument types in one function</p>
</li>
<li><p>Explain difference between <code>print</code> and <code>return</code></p>
</li>
<li><p>Write a real-life example of <code>*args</code> and <code>**kwargs</code></p>
</li>
</ol>
<hr />
]]></content:encoded></item><item><title><![CDATA[Dht with Arduino]]></title><description><![CDATA[#include "DHT.h"
// Define the pin and sensor type
#define DHTPIN 2    // Connect DATA pin of DHT11 to digital pin 2
#define DHTTYPE DHT11   // DHT11 sensor type


// Create DHT object
DHT dht(DHTPIN, DHTTYPE);

void setup() {
  Serial.begin(9600);
 ...]]></description><link>https://blog.aarav.com.np/dht-with-arduino</link><guid isPermaLink="true">https://blog.aarav.com.np/dht-with-arduino</guid><dc:creator><![CDATA[Aarav Poudel]]></dc:creator><pubDate>Mon, 22 Dec 2025 08:57:07 GMT</pubDate><content:encoded><![CDATA[<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">"DHT.h"</span></span>
<span class="hljs-comment">// Define the pin and sensor type</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">define</span> DHTPIN 2    <span class="hljs-comment">// Connect DATA pin of DHT11 to digital pin 2</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">define</span> DHTTYPE DHT11   <span class="hljs-comment">// DHT11 sensor type</span></span>


<span class="hljs-comment">// Create DHT object</span>
<span class="hljs-function">DHT <span class="hljs-title">dht</span><span class="hljs-params">(DHTPIN, DHTTYPE)</span></span>;

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">setup</span><span class="hljs-params">()</span> </span>{
  Serial.begin(<span class="hljs-number">9600</span>);
  Serial.println(<span class="hljs-string">"DHT11 Temperature and Humidity Sensor Readings: "</span>);
  <span class="hljs-comment">// pinMode(relayPin,OUTPUT);</span>
  <span class="hljs-comment">// pinMode(relayPin,HIGH);</span>
  pinMode(<span class="hljs-number">13</span>,OUTPUT);
  dht.begin(); <span class="hljs-comment">// Initialize sensor</span>
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">loop</span><span class="hljs-params">()</span> </span>{
  <span class="hljs-comment">// Wait a few seconds between measurements</span>
  delay(<span class="hljs-number">2000</span>);

  <span class="hljs-comment">// Read humidity (%)</span>
  <span class="hljs-keyword">float</span> h = dht.readHumidity();
  <span class="hljs-comment">// Read temperature (°C)</span>
  <span class="hljs-keyword">float</span> t = dht.readTemperature();



  <span class="hljs-comment">// Check if readings failed</span>
  <span class="hljs-keyword">if</span> (isnan(h) || isnan(t)) {
    Serial.println(<span class="hljs-string">"Failed to read from DHT11 sensor!"</span>);
    <span class="hljs-keyword">return</span>;
  }

  <span class="hljs-keyword">if</span>(h&gt;<span class="hljs-number">66</span>) {
    digitalWrite(<span class="hljs-number">13</span>,HIGH);

  }
<span class="hljs-keyword">else</span>{
  digitalWrite(<span class="hljs-number">13</span>, LOW);
}


  <span class="hljs-comment">// Print results to Serial Monitor</span>
  Serial.print(<span class="hljs-string">"Humidity: "</span>);
  Serial.print(h);
  Serial.print(<span class="hljs-string">" %\t"</span>);
  Serial.print(<span class="hljs-string">"Temperature: "</span>);
  Serial.print(t);
  Serial.println(<span class="hljs-string">" °C"</span>);
}
</code></pre>
]]></content:encoded></item><item><title><![CDATA[Height Measurement Using Ultrasonic sensor]]></title><description><![CDATA[height measurement
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27, 16, 2); // Change 0x27 to 0x3F if not working

#define TRIG 9
#define ECHO 10

// Height of sensor from ground in cm
int sensorHeight = 200;   

void set...]]></description><link>https://blog.aarav.com.np/height-measurement-using-ultrasonic-sensor</link><guid isPermaLink="true">https://blog.aarav.com.np/height-measurement-using-ultrasonic-sensor</guid><dc:creator><![CDATA[Aarav Poudel]]></dc:creator><pubDate>Fri, 05 Dec 2025 05:29:37 GMT</pubDate><content:encoded><![CDATA[<p>height measurement</p>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;Wire.h&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;LiquidCrystal_I2C.h&gt;</span></span>

<span class="hljs-function">LiquidCrystal_I2C <span class="hljs-title">lcd</span><span class="hljs-params">(<span class="hljs-number">0x27</span>, <span class="hljs-number">16</span>, <span class="hljs-number">2</span>)</span></span>; <span class="hljs-comment">// Change 0x27 to 0x3F if not working</span>

<span class="hljs-meta">#<span class="hljs-meta-keyword">define</span> TRIG 9</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">define</span> ECHO 10</span>

<span class="hljs-comment">// Height of sensor from ground in cm</span>
<span class="hljs-keyword">int</span> sensorHeight = <span class="hljs-number">200</span>;   

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">setup</span><span class="hljs-params">()</span> </span>{
  pinMode(TRIG, OUTPUT);
  pinMode(ECHO, INPUT);

  lcd.init();
  lcd.backlight();
  lcd.clear();
  lcd.setCursor(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>);
  lcd.print(<span class="hljs-string">"Height Meter"</span>);
  delay(<span class="hljs-number">1500</span>);
}

<span class="hljs-function"><span class="hljs-keyword">long</span> <span class="hljs-title">getDistance</span><span class="hljs-params">()</span> </span>{
  digitalWrite(TRIG, LOW);
  delayMicroseconds(<span class="hljs-number">2</span>);
  digitalWrite(TRIG, HIGH);
  delayMicroseconds(<span class="hljs-number">10</span>);
  digitalWrite(TRIG, LOW);

  <span class="hljs-keyword">long</span> duration = pulseIn(ECHO, HIGH);
  <span class="hljs-keyword">long</span> distance = duration * <span class="hljs-number">0.034</span> / <span class="hljs-number">2</span>; <span class="hljs-comment">// in cm</span>
  <span class="hljs-keyword">return</span> distance;
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">loop</span><span class="hljs-params">()</span> </span>{
  <span class="hljs-keyword">long</span> distance = getDistance();

  <span class="hljs-comment">// Calculate height </span>
  <span class="hljs-keyword">long</span> height = sensorHeight - distance;

  lcd.clear();
  lcd.setCursor(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>);
  lcd.print(<span class="hljs-string">"Dist: "</span>);
  lcd.print(distance);
  lcd.print(<span class="hljs-string">" cm"</span>);

  lcd.setCursor(<span class="hljs-number">0</span>, <span class="hljs-number">1</span>);
  lcd.print(<span class="hljs-string">"Height:"</span>);
  <span class="hljs-keyword">if</span> (height &gt; <span class="hljs-number">0</span> &amp;&amp; height &lt; <span class="hljs-number">250</span>) {
    lcd.print(height);
    lcd.print(<span class="hljs-string">" cm"</span>);
  } <span class="hljs-keyword">else</span> {
    lcd.print(<span class="hljs-string">"Out of range"</span>);
  }

  delay(<span class="hljs-number">500</span>);
}
</code></pre>
]]></content:encoded></item><item><title><![CDATA[Using 16*2 display]]></title><description><![CDATA[16×2 LCD with I²C backpack (PCF8574) on Arduino/ESP boards.

✅ Hardware Connections
Since it uses I²C, only 4 wires are required:




LCD PinConnect to



VCC5V

GNDGND

SDAESP8266 → D2 (GPIO4) / ESP32 → GPIO21 / Arduino Uno → A4

SCLESP8266 → D1 (GP...]]></description><link>https://blog.aarav.com.np/using-162-display</link><guid isPermaLink="true">https://blog.aarav.com.np/using-162-display</guid><dc:creator><![CDATA[Aarav Poudel]]></dc:creator><pubDate>Fri, 28 Nov 2025 04:45:09 GMT</pubDate><content:encoded><![CDATA[<p><strong>16×2 LCD with I²C backpack (PCF8574)</strong> on Arduino/ESP boards.</p>
<hr />
<h1 id="heading-hardware-connections">✅ <strong>Hardware Connections</strong></h1>
<p>Since it uses I²C, only <strong>4 wires</strong> are required:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>LCD Pin</td><td>Connect to</td></tr>
</thead>
<tbody>
<tr>
<td>VCC</td><td>5V</td></tr>
<tr>
<td>GND</td><td>GND</td></tr>
<tr>
<td>SDA</td><td>ESP8266 → D2 (GPIO4) / ESP32 → GPIO21 / Arduino Uno → A4</td></tr>
<tr>
<td>SCL</td><td>ESP8266 → D1 (GPIO5) / ESP32 → GPIO22 / Arduino Uno → A5</td></tr>
</tbody>
</table>
</div><hr />
<h1 id="heading-install-required-library">✅ <strong>Install Required Library</strong></h1>
<p>Install:</p>
<h3 id="heading-liquidcrystali2c"><strong>LiquidCrystal_I2C</strong></h3>
<p>by Frank de Brabander<br />(Arduino Library Manager)</p>
<hr />
<h1 id="heading-basic-example-code-works-on-arduino-esp8266-esp32">✅ <strong>Basic Example Code (Works on Arduino, ESP8266, ESP32)</strong></h1>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;Wire.h&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;LiquidCrystal_I2C.h&gt;</span></span>

<span class="hljs-comment">// Most common I2C LCD address is 0x27 or 0x3F</span>
<span class="hljs-function">LiquidCrystal_I2C <span class="hljs-title">lcd</span><span class="hljs-params">(<span class="hljs-number">0x27</span>, <span class="hljs-number">16</span>, <span class="hljs-number">2</span>)</span></span>;

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">setup</span><span class="hljs-params">()</span> </span>{
  Wire.begin();          
  lcd.init();            
  lcd.backlight();       

  lcd.setCursor(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>);
  lcd.print(<span class="hljs-string">"Hello World!"</span>);

  lcd.setCursor(<span class="hljs-number">0</span>, <span class="hljs-number">1</span>);
  lcd.print(<span class="hljs-string">"I2C LCD 16x2"</span>);
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">loop</span><span class="hljs-params">()</span> </span>{
}
</code></pre>
<hr />
<h1 id="heading-if-your-lcd-does-not-show-anything">🔍 <strong>If your LCD does not show anything</strong></h1>
<p>Try these:</p>
<h3 id="heading-1-check-i2c-address-using-scanner">1️⃣ <strong>Check I2C address using scanner</strong></h3>
<p>Upload this sketch:</p>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;Wire.h&gt;</span></span>

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">setup</span><span class="hljs-params">()</span> </span>{
  Serial.begin(<span class="hljs-number">115200</span>);
  Wire.begin();
  Serial.println(<span class="hljs-string">"Scanning..."</span>);
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">loop</span><span class="hljs-params">()</span> </span>{
  byte error, address;
  <span class="hljs-keyword">for</span>(address = <span class="hljs-number">1</span>; address &lt; <span class="hljs-number">127</span>; address++ ) {
    Wire.beginTransmission(address);
    error = Wire.endTransmission();
    <span class="hljs-keyword">if</span>(error == <span class="hljs-number">0</span>) {
      Serial.print(<span class="hljs-string">"I2C device found: 0x"</span>);
      Serial.println(address, HEX);
    }
  }
  delay(<span class="hljs-number">2000</span>);
}
</code></pre>
<p>Use the detected address in:</p>
<pre><code class="lang-cpp"><span class="hljs-function">LiquidCrystal_I2C <span class="hljs-title">lcd</span><span class="hljs-params">(<span class="hljs-number">0x27</span>, <span class="hljs-number">16</span>, <span class="hljs-number">2</span>)</span></span>;
</code></pre>
<hr />
<h1 id="heading-adjust-contrast">🛠 <strong>Adjust contrast</strong></h1>
<p>Turn the <strong>blue potentiometer</strong> on the I2C backpack until text becomes visible.</p>
<hr />
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;Wire.h&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;LiquidCrystal_I2C.h&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">"DHT.h"</span></span>

<span class="hljs-comment">// Change these:</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">define</span> DHTPIN 2        <span class="hljs-comment">// DHT data pin (D4 on ESP8266)</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">define</span> DHTTYPE DHT11   <span class="hljs-comment">// or DHT22</span></span>

<span class="hljs-function">DHT <span class="hljs-title">dht</span><span class="hljs-params">(DHTPIN, DHTTYPE)</span></span>;
<span class="hljs-function">LiquidCrystal_I2C <span class="hljs-title">lcd</span><span class="hljs-params">(<span class="hljs-number">0x27</span>, <span class="hljs-number">16</span>, <span class="hljs-number">2</span>)</span></span>;

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">setup</span><span class="hljs-params">()</span> </span>{
  Serial.begin(<span class="hljs-number">115200</span>);

  dht.begin();
  lcd.init();
  lcd.backlight();
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">loop</span><span class="hljs-params">()</span> </span>{
  <span class="hljs-keyword">float</span> h = dht.readHumidity();
  <span class="hljs-keyword">float</span> t = dht.readTemperature(); <span class="hljs-comment">// °C</span>
  <span class="hljs-keyword">float</span> f = dht.readTemperature(<span class="hljs-literal">true</span>); <span class="hljs-comment">// °F</span>

  <span class="hljs-keyword">if</span> (isnan(h) || isnan(t)) {
    lcd.clear();
    lcd.print(<span class="hljs-string">"DHT Error!"</span>);
    delay(<span class="hljs-number">1000</span>);
    <span class="hljs-keyword">return</span>;
  }

  lcd.setCursor(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>);
  lcd.print(<span class="hljs-string">"Temp: "</span>);
  lcd.print(t);
  lcd.print(<span class="hljs-string">" C"</span>);

  lcd.setCursor(<span class="hljs-number">0</span>, <span class="hljs-number">1</span>);
  lcd.print(<span class="hljs-string">"Humidity: "</span>);
  lcd.print(h);
  lcd.print(<span class="hljs-string">"%"</span>);

  delay(<span class="hljs-number">1500</span>);
}
</code></pre>
]]></content:encoded></item><item><title><![CDATA[Smart Door System]]></title><description><![CDATA[#include <Servo.h>
#define TRIG_PIN 9
#define ECHO_PIN 10
#define SERVO_PIN 6
Servo lidServo;
void setup() {
  pinMode(TRIG_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);
  lidServo.attach(SERVO_PIN);
  lidServo.write(90); // Lid closed initially
  Serial...]]></description><link>https://blog.aarav.com.np/smart-door-system</link><guid isPermaLink="true">https://blog.aarav.com.np/smart-door-system</guid><dc:creator><![CDATA[Aarav Poudel]]></dc:creator><pubDate>Fri, 21 Nov 2025 07:01:50 GMT</pubDate><content:encoded><![CDATA[<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;Servo.h&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">define</span> TRIG_PIN 9</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">define</span> ECHO_PIN 10</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">define</span> SERVO_PIN 6</span>
Servo lidServo;
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">setup</span><span class="hljs-params">()</span> </span>{
  pinMode(TRIG_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);
  lidServo.attach(SERVO_PIN);
  lidServo.write(<span class="hljs-number">90</span>); <span class="hljs-comment">// Lid closed initially</span>
  Serial.begin(<span class="hljs-number">9600</span>);
}
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">loop</span><span class="hljs-params">()</span> </span>{
  <span class="hljs-keyword">long</span> duration, distance;
  <span class="hljs-comment">// Send ultrasonic pulse</span>
  digitalWrite(TRIG_PIN, LOW);
  delayMicroseconds(<span class="hljs-number">2</span>);
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(<span class="hljs-number">10</span>);
  digitalWrite(TRIG_PIN, LOW);
  <span class="hljs-comment">// Read echo</span>
  duration = pulseIn(ECHO_PIN, HIGH);
  distance = duration * <span class="hljs-number">0.034</span> / <span class="hljs-number">2</span>; <span class="hljs-comment">// Convert to cm</span>
 Serial.print(distance);
  <span class="hljs-comment">// If hand/trash detected within 20 cm</span>
  <span class="hljs-keyword">if</span> (distance &gt; <span class="hljs-number">0</span> &amp;&amp; distance &lt; <span class="hljs-number">10</span>) {
    lidServo.write(<span class="hljs-number">0</span>);   <span class="hljs-comment">// Open lid</span>
    delay(<span class="hljs-number">3000</span>);          <span class="hljs-comment">// Wait 3 seconds</span>
    lidServo.write(<span class="hljs-number">90</span>);    <span class="hljs-comment">// Close lid</span>
  }
  delay(<span class="hljs-number">200</span>); <span class="hljs-comment">// Small delay to avoid too many triggers</span>
}
</code></pre>
]]></content:encoded></item><item><title><![CDATA[Esp8266 Wifi Bot]]></title><description><![CDATA[Here’s a clear and well-structured documentation for your ESP8266 WiFi Robot Car project that includes setup, features, code explanation, and troubleshooting.

🚗 ESP8266 WiFi Robot Car (AP Mode + Web UI)
This project allows you to control a robotic ...]]></description><link>https://blog.aarav.com.np/esp8266-wifi-bot</link><guid isPermaLink="true">https://blog.aarav.com.np/esp8266-wifi-bot</guid><dc:creator><![CDATA[Aarav Poudel]]></dc:creator><pubDate>Tue, 04 Nov 2025 05:38:40 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1762234702131/4a59ee47-b513-4243-8e15-30318b087ee0.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Here’s a clear and well-structured <strong>documentation</strong> for your ESP8266 WiFi Robot Car project that includes setup, features, code explanation, and troubleshooting.</p>
<hr />
<h1 id="heading-esp8266-wifi-robot-car-ap-mode-web-ui">🚗 ESP8266 WiFi Robot Car (AP Mode + Web UI)</h1>
<p>This project allows you to <strong>control a robotic car using an ESP8266</strong> via a <strong>WiFi Access Point (AP)</strong>.<br />It serves a <strong>web interface</strong> with large directional buttons that send motion commands to the ESP8266.</p>
<hr />
<h2 id="heading-overview">📘 Overview</h2>
<p>When powered, the ESP8266 creates its own WiFi network (<code>ESP8266_Robot_Car</code>).<br />A user connects to this WiFi and opens a webpage (usually at <a target="_blank" href="http://192.168.4.1\).￼The"><code>http://192.168.4.1</code>).<br />The</a> page contains four big buttons:</p>
<ul>
<li><p><strong>↑ Forward</strong></p>
</li>
<li><p><strong>↓ Backward</strong></p>
</li>
<li><p><strong>← Left</strong></p>
</li>
<li><p><strong>→ Right</strong></p>
</li>
</ul>
<p>When a button is <strong>pressed</strong>, a command (<code>F</code>, <code>B</code>, <code>L</code>, or <code>R</code>) is sent to the ESP8266.<br />When the button is <strong>released</strong>, a stop (<code>S</code>) command is sent.</p>
<hr />
<h2 id="heading-hardware-requirements">⚙️ Hardware Requirements</h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Component</td><td>Quantity</td><td>Description</td></tr>
</thead>
<tbody>
<tr>
<td>ESP8266 (NodeMCU / Wemos D1 Mini)</td><td>1</td><td>Main microcontroller with WiFi</td></tr>
<tr>
<td>L298N or L293D Motor Driver</td><td>1</td><td>To control DC motors</td></tr>
<tr>
<td>DC Motors</td><td>2</td><td>For car movement</td></tr>
<tr>
<td>Power Source</td><td>1</td><td>7.4V–12V battery pack</td></tr>
<tr>
<td>Jumper Wires</td><td>—</td><td>For connections</td></tr>
</tbody>
</table>
</div><hr />
<h2 id="heading-wiring-diagram">🪛 Wiring Diagram</h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td>ESP8266 Pin</td><td>Motor Driver Pin</td><td>Description</td></tr>
</thead>
<tbody>
<tr>
<td>D1</td><td>IN1</td><td>Motor A forward</td></tr>
<tr>
<td>D2</td><td>IN2</td><td>Motor A backward</td></tr>
<tr>
<td>D3</td><td>IN3</td><td>Motor B forward</td></tr>
<tr>
<td>D4</td><td>IN4</td><td>Motor B backward</td></tr>
<tr>
<td>5V / Vin</td><td>VCC</td><td>Power to driver</td></tr>
<tr>
<td>GND</td><td>GND</td><td>Common ground</td></tr>
</tbody>
</table>
</div><blockquote>
<p>You can change pin assignments in the code if needed.</p>
</blockquote>
<hr />
<h2 id="heading-software-setup">💻 Software Setup</h2>
<h3 id="heading-1-install-requirements">1. Install Requirements</h3>
<ul>
<li><p>Install <strong>Arduino IDE</strong></p>
</li>
<li><p>Add the <strong>ESP8266 board package</strong><br />  <em>(File → Preferences → Additional Boards Manager URLs)</em></p>
<pre><code class="lang-cpp">  https:<span class="hljs-comment">//arduino.esp8266.com/stable/package_esp8266com_index.json</span>
</code></pre>
</li>
<li><p>Install required libraries:</p>
<ul>
<li><p><code>ESP8266WiFi.h</code></p>
</li>
<li><p><code>ESP8266WebServer.h</code></p>
</li>
</ul>
</li>
</ul>
<h3 id="heading-2-upload-code">2. Upload Code</h3>
<ul>
<li><p>Copy the full sketch provided.</p>
</li>
<li><p>Select your ESP board from <strong>Tools → Board</strong>.</p>
</li>
<li><p>Select the correct <strong>COM port</strong>.</p>
</li>
<li><p>Click <strong>Upload</strong>.</p>
</li>
</ul>
<hr />
<h2 id="heading-connecting-to-the-car">🌐 Connecting to the Car</h2>
<ol>
<li><p>After upload, open the <strong>Serial Monitor</strong> at <code>115200 baud</code>.</p>
</li>
<li><p>You should see something like:</p>
<pre><code class="lang-cpp"> 🚀 Starting ESP8266 Robot Car in AP Mode...
 📶 Access Point Started. IP: <span class="hljs-number">192.168</span><span class="hljs-number">.4</span><span class="hljs-number">.1</span>
 🌐 HTTP Server Started!
</code></pre>
</li>
<li><p>On your phone or laptop:</p>
<ul>
<li><p>Go to <strong>WiFi settings</strong></p>
</li>
<li><p>Connect to <code>ESP8266_Robot_Car</code><br />  Password: <code>12345678</code></p>
</li>
<li><p>Open browser and visit: <a target="_blank" href="http://192.168.4.1"><code>http://192.168.4.1</code></a></p>
</li>
</ul>
</li>
<li><p>You’ll see a control interface with four large buttons.</p>
</li>
</ol>
<hr />
<h2 id="heading-web-interface-features">🧭 Web Interface Features</h2>
<ul>
<li><p><strong>Responsive Layout</strong> – works on mobile and desktop in landscape mode.</p>
</li>
<li><p><strong>Editable IP field</strong> – you can change IP if needed.</p>
</li>
<li><p><strong>LocalStorage support</strong> – remembers the IP address even after reload.</p>
</li>
<li><p><strong>Touch &amp; Mouse Events</strong> – supports both mobile and desktop controls.</p>
</li>
</ul>
<hr />
<h2 id="heading-command-mapping">⚡ Command Mapping</h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Command</td><td>Description</td></tr>
</thead>
<tbody>
<tr>
<td><code>F</code></td><td>Move Forward</td></tr>
<tr>
<td><code>B</code></td><td>Move Backward</td></tr>
<tr>
<td><code>L</code></td><td>Turn Left</td></tr>
<tr>
<td><code>R</code></td><td>Turn Right</td></tr>
<tr>
<td><code>S</code></td><td>Stop</td></tr>
</tbody>
</table>
</div><p>Each command is sent as an HTTP GET request to:</p>
<pre><code class="lang-cpp">http:<span class="hljs-comment">//192.168.4.1/control?state=&lt;COMMAND&gt;</span>
</code></pre>
<p>Example:</p>
<pre><code class="lang-cpp">http:<span class="hljs-comment">//192.168.4.1/control?state=F</span>
</code></pre>
<hr />
<h2 id="heading-debugging-via-serial-monitor">🪵 Debugging via Serial Monitor</h2>
<p>Serial outputs help you see what’s happening:</p>
<pre><code class="lang-cpp">➡️ Received command: F
🚗 Moving Forward
➡️ Received command: S
⏹ Stopping Car
</code></pre>
<p>If you don’t see this, check:</p>
<ul>
<li><p>Power supply to the ESP8266 and motor driver</p>
</li>
<li><p>Correct pin wiring</p>
</li>
<li><p>Serial Monitor baud rate (115200)</p>
</li>
</ul>
<hr />
<h2 id="heading-code-overview">🧩 Code Overview</h2>
<p><strong>Main Components:</strong></p>
<ul>
<li><p><strong>WiFi.softAP()</strong> – Starts ESP8266 in Access Point mode</p>
</li>
<li><p><strong>ESP8266WebServer server(80)</strong> – Runs HTTP server on port 80</p>
</li>
<li><p><strong>server.on("/", handleRoot)</strong> – Serves the control webpage</p>
</li>
<li><p><strong>server.on("/control", handleControl)</strong> – Handles motion commands</p>
</li>
<li><p><strong>Motor Functions:</strong></p>
<ul>
<li><code>forward()</code>, <code>backward()</code>, <code>left()</code>, <code>right()</code>, <code>stopCar()</code></li>
</ul>
</li>
</ul>
<p><strong>Flow:</strong></p>
<ol>
<li><p>User connects to AP</p>
</li>
<li><p>Loads control page</p>
</li>
<li><p>Presses button → JavaScript sends HTTP request</p>
</li>
<li><p>ESP8266 receives request and activates motor pins</p>
</li>
</ol>
<hr />
<h2 id="heading-troubleshooting">🧠 Troubleshooting</h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Issue</td><td>Possible Cause</td><td>Solution</td></tr>
</thead>
<tbody>
<tr>
<td>Page not loading</td><td>Wrong IP or disconnected WiFi</td><td>Reconnect to <code>ESP8266_Robot_Car</code> and try <code>192.168.4.1</code></td></tr>
<tr>
<td>Buttons not working</td><td>Wrong pin mapping</td><td>Check motor pin assignments</td></tr>
<tr>
<td>Car not stopping</td><td>No <code>S</code> command</td><td>Ensure button release is detected</td></tr>
<tr>
<td>No serial output</td><td>Wrong baud rate</td><td>Set Serial Monitor to <code>115200</code> baud</td></tr>
</tbody>
</table>
</div><hr />
<h2 id="heading-future-improvements">🧩 Future Improvements</h2>
<ul>
<li><p>Add <strong>Station Mode (STA)</strong> support to control from existing WiFi network.</p>
</li>
<li><p>Add <strong>Speed Control (PWM)</strong> for smooth movement.</p>
</li>
<li><p>Add <strong>Camera streaming</strong> support.</p>
</li>
<li><p>Use <strong>OTA updates</strong> for easy firmware upgrades.</p>
</li>
</ul>
<hr />
<h2 id="heading-summary">🏁 Summary</h2>
<p>✅ Standalone WiFi-controlled robot car<br />✅ Easy-to-use web UI hosted directly on ESP8266<br />✅ Real-time control using touch or mouse<br />✅ Fully customizable and expandable</p>
<h2 id="heading-code">Code</h2>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;ESP8266WiFi.h&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;ESP8266WebServer.h&gt;</span></span>

<span class="hljs-comment">// Motor pin definitions (change as per your wiring)</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">define</span> IN1 D1</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">define</span> IN2 D2</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">define</span> IN3 D3</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">define</span> IN4 D4</span>

<span class="hljs-function">ESP8266WebServer <span class="hljs-title">server</span><span class="hljs-params">(<span class="hljs-number">80</span>)</span></span>;

<span class="hljs-comment">// HTML Page (embedded)</span>
<span class="hljs-keyword">const</span> <span class="hljs-keyword">char</span> MAIN_page[] PROGMEM = <span class="hljs-string">R"rawliteral(
&lt;!DOCTYPE html&gt;
&lt;html lang="en"&gt;
&lt;head&gt;
  &lt;meta charset="UTF-8" /&gt;
  &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt;
  &lt;title&gt;ESP8266 WiFi Robot Car&lt;/title&gt;
  &lt;style&gt;
    body {
      margin: 0;
      background: #f4f6fb;
      font-family: Arial, sans-serif;
      display: flex;
      flex-direction: row;
      justify-content: space-around;
      align-items: center;
      height: 100vh;
      overflow: hidden;
    }

    .panel {
      display: flex;
      flex-direction: column;
      justify-content: center;
      gap: 20px;
    }

    .arrow-btn {
      width: 120px;
      height: 120px;
      border: none;
      border-radius: 12px;
      background: #dbeafe;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 48px;
      color: #1e3a8a;
      transition: 0.2s;
    }

    .arrow-btn:active {
      background: #93c5fd;
      transform: scale(0.95);
    }

    .arrow-btn.active{
        background: #93c5fd;
        transform: scale(0.95);
    }

    .center-panel {
      display: flex;
      flex-direction: column;
      align-items: center;
      gap: 15px;
    }

    .info-bar {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      background: #0ea5e9;
      color: white;
      text-align: center;
      padding: 8px;
      font-size: 18px;
      font-weight: 500;
      display: flex;
      justify-content: center;
      align-items: center;
      gap: 10px;
    }

    .status {
      font-size: 14px;
      opacity: 0.85;
    }

    #editIp {
      background: none;
      border: none;
      color: white;
      font-size: 16px;
      cursor: pointer;
    }

    #ipInput {
      background: rgba(255, 255, 255, 0.2);
      border: none;
      border-radius: 5px;
      padding: 2px 6px;
      color: white;
      width: 120px;
      text-align: center;
    }

    #saveBtn {
      background: #0284c7;
      border: none;
      color: white;
      border-radius: 5px;
      padding: 2px 8px;
      cursor: pointer;
      margin-left: 4px;
    }
  &lt;/style&gt;
&lt;/head&gt;
&lt;body&gt;
  &lt;div class="info-bar"&gt;
    🤖 ESP8266 WiFi Robot Car
    &lt;span class="status"&gt;
      &lt;input id="ipInput" value="192.168.4.1"&gt;
    &lt;/span&gt;
    &lt;button id="saveBtn"&gt;💾&lt;/button&gt;
  &lt;/div&gt;

  &lt;div class="panel"&gt;
    &lt;button class="arrow-btn" id="forward"&gt;⬆️&lt;/button&gt;
    &lt;button class="arrow-btn" id="backward"&gt;⬇️&lt;/button&gt;
  &lt;/div&gt;

  &lt;div class="center-panel"&gt;
    &lt;button class="arrow-btn" id="stop"&gt;🅿️&lt;/button&gt;
  &lt;/div&gt;

  &lt;div class="panel"&gt;
    &lt;button class="arrow-btn" id="left"&gt;⬅️&lt;/button&gt;
    &lt;button class="arrow-btn" id="right"&gt;➡️&lt;/button&gt;
  &lt;/div&gt;

  &lt;script&gt;
    // Load saved IP from localStorage or set default
    let baseIP = localStorage.getItem("robot_ip") || "192.168.4.1";
    const ipInput = document.getElementById("ipInput");
    const saveBtn = document.getElementById("saveBtn");
    ipInput.value = baseIP;

    // Save new IP to localStorage
    saveBtn.addEventListener("click", () =&gt; {
      baseIP = ipInput.value.trim();
      if (baseIP) {
        localStorage.setItem("robot_ip", baseIP);
        alert(`✅ IP saved: ${baseIP}`);
      }
    });

    function sendState(state) {
      const url = `http://${baseIP}/control?state=${state}`;
      fetch(url).catch(err =&gt; console.log("Request failed:", err));
    }

    function addControlEvents(id, code) {
      const btn = document.getElementById(id);
      const press = () =&gt; sendState(code);
      const release = () =&gt; sendState("S");

      btn.addEventListener("mousedown", press);
      btn.addEventListener("mouseup", release);
      btn.addEventListener("mouseleave", release);

      // Mobile/touch support
      btn.addEventListener("touchstart", e =&gt; { e.preventDefault(); btn.classList.add("active"); press(); });
      btn.addEventListener("touchend", e =&gt; { e.preventDefault(); btn.classList.remove("active"); release(); });
    }

    addControlEvents("forward", "F");
    addControlEvents("backward", "B");
    addControlEvents("left", "L");
    addControlEvents("right", "R");

    // Stop button
    document.getElementById("stop").addEventListener("click", () =&gt;{ sendState("S")});
  &lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
)rawliteral"</span>;

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">setup</span><span class="hljs-params">()</span> </span>{
  Serial.begin(<span class="hljs-number">115200</span>);
  Serial.println();
  Serial.println(<span class="hljs-string">"🚀 Starting ESP8266 Robot Car in AP Mode..."</span>);

  <span class="hljs-comment">// Setup motor pins</span>
  pinMode(IN1, OUTPUT);
  pinMode(IN2, OUTPUT);
  pinMode(IN3, OUTPUT);
  pinMode(IN4, OUTPUT);
  stopCar();

  <span class="hljs-comment">// Start Access Point</span>
  WiFi.softAP(<span class="hljs-string">"ESP8266_Robot_Car"</span>, <span class="hljs-string">"12345678"</span>);
  Serial.print(<span class="hljs-string">"📶 Access Point Started. IP: "</span>);
  Serial.println(WiFi.softAPIP());

  <span class="hljs-comment">// Route handlers</span>
  server.on(<span class="hljs-string">"/"</span>, handleRoot);
  server.on(<span class="hljs-string">"/control"</span>, handleControl);
  server.begin();
  Serial.println(<span class="hljs-string">"🌐 HTTP Server Started!"</span>);
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">loop</span><span class="hljs-params">()</span> </span>{
  server.handleClient();
}

<span class="hljs-comment">// Serve the control UI</span>
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">handleRoot</span><span class="hljs-params">()</span> </span>{
  Serial.println(<span class="hljs-string">"📄 Client requested index page"</span>);
  server.send(<span class="hljs-number">200</span>, <span class="hljs-string">"text/html"</span>, MAIN_page);
}

<span class="hljs-comment">// Handle motor control requests</span>
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">handleControl</span><span class="hljs-params">()</span> </span>{
  <span class="hljs-keyword">if</span> (!server.hasArg(<span class="hljs-string">"state"</span>)) {
    Serial.println(<span class="hljs-string">"⚠️ No state argument received!"</span>);
    server.send(<span class="hljs-number">400</span>, <span class="hljs-string">"text/plain"</span>, <span class="hljs-string">"Missing state parameter"</span>);
    <span class="hljs-keyword">return</span>;
  }

  String state = server.arg(<span class="hljs-string">"state"</span>);
  Serial.print(<span class="hljs-string">"➡️ Received command: "</span>);
  Serial.println(state);

  <span class="hljs-keyword">if</span> (state == <span class="hljs-string">"F"</span>) forward();
  <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (state == <span class="hljs-string">"B"</span>) backward();
  <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (state == <span class="hljs-string">"L"</span>) left();
  <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (state == <span class="hljs-string">"R"</span>) right();
  <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (state == <span class="hljs-string">"S"</span>) stopCar();
  <span class="hljs-keyword">else</span> Serial.println(<span class="hljs-string">"❌ Invalid state command!"</span>);

  server.send(<span class="hljs-number">200</span>, <span class="hljs-string">"text/plain"</span>, <span class="hljs-string">"OK"</span>);
}

<span class="hljs-comment">// Motor Control Functions</span>
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">forward</span><span class="hljs-params">()</span> </span>{
  Serial.println(<span class="hljs-string">"🚗 Moving Forward"</span>);
  digitalWrite(IN1, HIGH);
  digitalWrite(IN2, LOW);
  digitalWrite(IN3, HIGH);
  digitalWrite(IN4, LOW);
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">backward</span><span class="hljs-params">()</span> </span>{
  Serial.println(<span class="hljs-string">"🚗 Moving Backward"</span>);
  digitalWrite(IN1, LOW);
  digitalWrite(IN2, HIGH);
  digitalWrite(IN3, LOW);
  digitalWrite(IN4, HIGH);
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">left</span><span class="hljs-params">()</span> </span>{
  Serial.println(<span class="hljs-string">"↩️ Turning Left"</span>);
  digitalWrite(IN1, LOW);
  digitalWrite(IN2, HIGH);
  digitalWrite(IN3, HIGH);
  digitalWrite(IN4, LOW);
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">right</span><span class="hljs-params">()</span> </span>{
  Serial.println(<span class="hljs-string">"↪️ Turning Right"</span>);
  digitalWrite(IN1, HIGH);
  digitalWrite(IN2, LOW);
  digitalWrite(IN3, LOW);
  digitalWrite(IN4, HIGH);
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">stopCar</span><span class="hljs-params">()</span> </span>{
  Serial.println(<span class="hljs-string">"⏹ Stopping Car"</span>);
  digitalWrite(IN1, LOW);
  digitalWrite(IN2, LOW);
  digitalWrite(IN3, LOW);
  digitalWrite(IN4, LOW);
}
</code></pre>
]]></content:encoded></item><item><title><![CDATA[Grade 11 Web Technology Ic]]></title><description><![CDATA[🌐 Unit 6: Web Technology

6.2 Web Browsers and Search Engines
🌍 Web Browser
A web browser is an application software that allows users to access, view, and interact with web pages on the internet.
🔹 Common Web Browsers

Google Chrome

Mozilla Fire...]]></description><link>https://blog.aarav.com.np/grade-11-web-technology-ic</link><guid isPermaLink="true">https://blog.aarav.com.np/grade-11-web-technology-ic</guid><category><![CDATA[grade11]]></category><category><![CDATA[Computer Science]]></category><dc:creator><![CDATA[Aarav Poudel]]></dc:creator><pubDate>Sat, 11 Oct 2025 16:25:43 GMT</pubDate><content:encoded><![CDATA[<hr />
<h1 id="heading-unit-6-web-technology">🌐 <strong>Unit 6: Web Technology</strong></h1>
<hr />
<h2 id="heading-62-web-browsers-and-search-engines"><strong>6.2 Web Browsers and Search Engines</strong></h2>
<h3 id="heading-web-browser">🌍 <strong>Web Browser</strong></h3>
<p>A <strong>web browser</strong> is an application software that allows users to access, view, and interact with web pages on the internet.</p>
<h3 id="heading-common-web-browsers">🔹 <strong>Common Web Browsers</strong></h3>
<ul>
<li><p>Google Chrome</p>
</li>
<li><p>Mozilla Firefox</p>
</li>
<li><p>Safari</p>
</li>
<li><p>Microsoft Edge</p>
</li>
<li><p>Opera</p>
</li>
</ul>
<h3 id="heading-functions-of-a-web-browser">🧠 <strong>Functions of a Web Browser</strong></h3>
<ol>
<li><p>Accepts website addresses (URLs).</p>
</li>
<li><p>Requests web pages from servers using HTTP/HTTPS.</p>
</li>
<li><p>Interprets HTML, CSS, and JavaScript code.</p>
</li>
<li><p>Displays the final formatted web page to the user.</p>
</li>
</ol>
<h3 id="heading-example">📖 <strong>Example</strong></h3>
<p>When you type <a target="_blank" href="https://www.wikipedia.org"><code>https://www.wikipedia.org</code></a>:</p>
<ul>
<li><p>The browser sends a request to the Wikipedia server.</p>
</li>
<li><p>The server sends back an HTML file.</p>
</li>
<li><p>The browser displays the formatted page.</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1760199641039/b05d32b9-82ad-4728-9c0e-79ad61f1fde1.webp" alt class="image--center mx-auto" /></p>
<hr />
<h3 id="heading-search-engine">🔍 <strong>Search Engine</strong></h3>
<p>A <strong>search engine</strong> is a web-based tool that helps users find information across the internet.</p>
<h3 id="heading-popular-search-engines">🔹 <strong>Popular Search Engines</strong></h3>
<ul>
<li><p>Google</p>
</li>
<li><p>Bing</p>
</li>
<li><p>Yahoo</p>
</li>
<li><p>DuckDuckGo</p>
</li>
<li><p>Baidu</p>
</li>
</ul>
<h3 id="heading-how-search-engines-work">⚙️ <strong>How Search Engines Work</strong></h3>
<ol>
<li><p><strong>Crawling:</strong> Automatically scanning websites for new content.</p>
</li>
<li><p><strong>Indexing:</strong> Storing information from websites in a large database.</p>
</li>
<li><p><strong>Ranking:</strong> Showing the most relevant results when users search.</p>
</li>
</ol>
<h3 id="heading-example-1">🧩 <strong>Example</strong></h3>
<p>When you search “HTML tutorial”:</p>
<ul>
<li><p>The search engine looks through its index.</p>
</li>
<li><p>It shows the most relevant web pages related to HTML tutorials.</p>
</li>
</ul>
<hr />
<h2 id="heading-63-overview-of-various-internet-amp-web-technologies"><strong>6.3 Overview of Various Internet &amp; Web Technologies</strong></h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Technology</td><td>Purpose</td><td>Example</td></tr>
</thead>
<tbody>
<tr>
<td><strong>HTML (HyperText Markup Language)</strong></td><td>Defines structure of web pages</td><td><code>&lt;h1&gt;Welcome&lt;/h1&gt;</code></td></tr>
<tr>
<td><strong>CSS (Cascading Style Sheets)</strong></td><td>Adds design and layout to web pages</td><td><code>color: blue; background: yellow;</code></td></tr>
<tr>
<td><strong>JavaScript</strong></td><td>Adds interactivity and dynamic content</td><td>Form validation, animations</td></tr>
<tr>
<td><strong>PHP / Python / Node.js</strong></td><td>Server-side programming</td><td>Login, database connection</td></tr>
<tr>
<td><strong>MySQL / MongoDB</strong></td><td>Database systems to store data</td><td>User accounts, product data</td></tr>
<tr>
<td><strong>HTTP / HTTPS</strong></td><td>Communication protocol between browser and server</td><td>Request/response process</td></tr>
<tr>
<td><strong>API (Application Programming Interface)</strong></td><td>Enables data exchange between systems</td><td>Google Maps API</td></tr>
<tr>
<td><strong>CMS (Content Management System)</strong></td><td>Allows easy web content creation</td><td>WordPress, Joomla</td></tr>
</tbody>
</table>
</div><hr />
<h2 id="heading-64-content-management-system-cms"><strong>6.4 Content Management System (CMS)</strong></h2>
<h3 id="heading-definition">📘 <strong>Definition</strong></h3>
<p>A <strong>CMS</strong> is a software that helps users create, edit, and manage website content <strong>without needing to code</strong>.</p>
<h3 id="heading-popular-cms-examples">🔹 <strong>Popular CMS Examples</strong></h3>
<ul>
<li><p><strong>WordPress</strong> (most popular)</p>
</li>
<li><p><strong>Joomla</strong></p>
</li>
<li><p><strong>Drupal</strong></p>
</li>
<li><p><strong>Wix</strong></p>
</li>
</ul>
<h3 id="heading-key-features">⚙️ <strong>Key Features</strong></h3>
<ol>
<li><p>Easy content creation using text editors</p>
</li>
<li><p>User management (Admin, Editor, Viewer)</p>
</li>
<li><p>Themes and templates for design</p>
</li>
<li><p>Plugins for extra functionality</p>
</li>
<li><p>Media management (images, videos, audio)</p>
</li>
</ol>
<h3 id="heading-example-2">🧠 <strong>Example</strong></h3>
<p>A blogger can publish posts using <strong>WordPress dashboard</strong> without writing HTML manually.</p>
<hr />
<h2 id="heading-64-html-the-language-of-the-web"><strong>6.4 HTML: The Language of the Web</strong></h2>
<h3 id="heading-641-objectives"><strong>6.4.1 Objectives</strong></h3>
<ul>
<li><p>Understand HTML syntax and structure.</p>
</li>
<li><p>Create and format simple web pages.</p>
</li>
<li><p>Use tags and attributes properly.</p>
</li>
<li><p>Add headings, paragraphs, lists, and links.</p>
</li>
</ul>
<hr />
<h3 id="heading-642-structure-of-html"><strong>6.4.2 Structure of HTML</strong></h3>
<p>Every HTML document has three main parts:</p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</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">title</span>&gt;</span>My First Web Page<span class="hljs-tag">&lt;/<span class="hljs-name">title</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">h1</span>&gt;</span>Welcome to HTML<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>This is my first paragraph.<span class="hljs-tag">&lt;/<span class="hljs-name">p</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>
<h4 id="heading-explanation">🧱 Explanation:</h4>
<ul>
<li><p><code>&lt;!DOCTYPE html&gt;</code> → Defines document type.</p>
</li>
<li><p><code>&lt;html&gt;</code> → Root element of the web page.</p>
</li>
<li><p><code>&lt;head&gt;</code> → Contains metadata, title, and links to CSS/JS.</p>
</li>
<li><p><code>&lt;title&gt;</code> → Title shown in browser tab.</p>
</li>
<li><p><code>&lt;body&gt;</code> → Visible page content.</p>
</li>
</ul>
<hr />
<h3 id="heading-643-publishing-and-hosting"><strong>6.4.3 Publishing and Hosting</strong></h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Term</td><td>Description</td></tr>
</thead>
<tbody>
<tr>
<td><strong>Publishing</strong></td><td>Uploading your website to the internet so others can access it.</td></tr>
<tr>
<td><strong>Hosting</strong></td><td>A service that stores your website files on a web server.</td></tr>
</tbody>
</table>
</div><h4 id="heading-examples-of-hosting-services">🧩 <strong>Examples of Hosting Services:</strong></h4>
<ul>
<li><p>GitHub Pages</p>
</li>
<li><p>Netlify</p>
</li>
<li><p>Hostinger</p>
</li>
<li><p>InfinityFree</p>
</li>
</ul>
<h4 id="heading-steps-to-publish-a-website">🧠 <strong>Steps to Publish a Website</strong></h4>
<ol>
<li><p>Design your web pages in HTML/CSS.</p>
</li>
<li><p>Buy a <strong>domain name</strong> (like <a target="_blank" href="http://example.com"><code>example.com</code></a>).</p>
</li>
<li><p>Choose a <strong>hosting service</strong>.</p>
</li>
<li><p>Upload your files (using FTP or control panel).</p>
</li>
<li><p>Access it online through the domain.</p>
</li>
</ol>
<hr />
<h3 id="heading-644-html-tags-vs-attributes"><strong>6.4.4 HTML Tags vs Attributes</strong></h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Tags</strong></td><td><strong>Attributes</strong></td></tr>
</thead>
<tbody>
<tr>
<td>Define elements or structure in HTML</td><td>Provide extra information about a tag</td></tr>
<tr>
<td>Always enclosed in <code>&lt; &gt;</code></td><td>Written inside opening tag</td></tr>
<tr>
<td>Example: <code>&lt;p&gt;</code></td><td>Example: <code>&lt;img src="photo.jpg" alt="image"&gt;</code></td></tr>
</tbody>
</table>
</div><h4 id="heading-example-3">🧠 Example:</h4>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"logo.png"</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">"Company Logo"</span> <span class="hljs-attr">width</span>=<span class="hljs-string">"100"</span> <span class="hljs-attr">height</span>=<span class="hljs-string">"80"</span>&gt;</span>
</code></pre>
<ul>
<li><p><strong>Tag:</strong> <code>&lt;img&gt;</code></p>
</li>
<li><p><strong>Attributes:</strong> <code>src</code>, <code>alt</code>, <code>width</code>, <code>height</code></p>
</li>
</ul>
<hr />
<h3 id="heading-645-basic-tags-of-html"><strong>6.4.5 Basic Tags of HTML</strong></h3>
<h4 id="heading-example-4">📘 Example:</h4>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">html</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">title</span>&gt;</span>Basic Tags Example<span class="hljs-tag">&lt;/<span class="hljs-name">title</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> <span class="hljs-attr">bgcolor</span>=<span class="hljs-string">"lightblue"</span> <span class="hljs-attr">text</span>=<span class="hljs-string">"black"</span> <span class="hljs-attr">background</span>=<span class="hljs-string">"bg.jpg"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Welcome<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>This is my first HTML page!<span class="hljs-tag">&lt;/<span class="hljs-name">p</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>
<h3 id="heading-explanation-1">🧩 <strong>Explanation</strong></h3>
<ul>
<li><p><code>bgcolor</code> → sets background color.</p>
</li>
<li><p><code>text</code> → sets text color.</p>
</li>
<li><p><code>background</code> → sets an image as background.</p>
</li>
</ul>
<hr />
<h3 id="heading-adding-background-sound-old-html-feature">🎵 <strong>Adding Background Sound (Old HTML Feature)</strong></h3>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">bgsound</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"music.mp3"</span> <span class="hljs-attr">loop</span>=<span class="hljs-string">"infinite"</span>&gt;</span>
</code></pre>
<blockquote>
<p>⚠️ <em>Note: Not supported in modern browsers; use HTML5</em> <code>&lt;audio&gt;</code> tag instead.</p>
</blockquote>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">audio</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"music.mp3"</span> <span class="hljs-attr">autoplay</span> <span class="hljs-attr">loop</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">audio</span>&gt;</span>
</code></pre>
<hr />
<h3 id="heading-646-heading-tag-h1-to-h6"><strong>6.4.6 Heading Tag (H1 to H6)</strong></h3>
<p>Headings define the titles and subheadings of a page.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">align</span>=<span class="hljs-string">"center"</span>&gt;</span>Main Heading<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Sub Heading<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">h3</span>&gt;</span>Minor Heading<span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">h4</span>&gt;</span> Normal Heading 4<span class="hljs-tag">&lt;/<span class="hljs-name">h4</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">h5</span>&gt;</span> Smaller Heading 5<span class="hljs-tag">&lt;/<span class="hljs-name">h5</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">h6</span>&gt;</span> Smallest Heading<span class="hljs-tag">&lt;/<span class="hljs-name">h6</span>&gt;</span>
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1760198757329/88f73185-3e70-4fbe-be40-8e0874721bc4.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-details">🔹 <strong>Details:</strong></h3>
<ul>
<li><p><code>&lt;h1&gt;</code> is the <strong>largest</strong> heading.</p>
</li>
<li><p><code>&lt;h6&gt;</code> is the <strong>smallest</strong> heading.</p>
</li>
<li><p><code>align</code> attribute can be: <code>left</code>, <code>center</code>, <code>right</code>. (its left by default)</p>
</li>
</ul>
<hr />
<h3 id="heading-647-font-tag-and-attributes"><strong>6.4.7 FONT Tag and Attributes</strong></h3>
<p>The <code>&lt;font&gt;</code> tag defines the appearance of text.<br />(Deprecated in HTML5 — replaced by CSS — but still taught for understanding.)</p>
<h4 id="heading-example-5">🧩 <strong>Example:</strong></h4>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">font</span> <span class="hljs-attr">size</span>=<span class="hljs-string">"5"</span> <span class="hljs-attr">color</span>=<span class="hljs-string">"red"</span> <span class="hljs-attr">face</span>=<span class="hljs-string">"Arial"</span>&gt;</span>This is large red text.<span class="hljs-tag">&lt;/<span class="hljs-name">font</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">basefont</span> <span class="hljs-attr">size</span>=<span class="hljs-string">"3"</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">small</span>&gt;</span>Small text<span class="hljs-tag">&lt;/<span class="hljs-name">small</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">big</span>&gt;</span>Big text<span class="hljs-tag">&lt;/<span class="hljs-name">big</span>&gt;</span>
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1760198495183/ded8104b-1aa7-40bc-a307-ecc2383cd394.png" alt class="image--center mx-auto" /></p>
<h4 id="heading-attributes">🔹 <strong>Attributes:</strong></h4>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Attribute</td><td>Description</td><td>Example</td></tr>
</thead>
<tbody>
<tr>
<td><strong>size</strong></td><td>Text size (1–7)</td><td><code>&lt;font size="4"&gt;Text&lt;/font&gt;</code></td></tr>
<tr>
<td><strong>color</strong></td><td>Text color</td><td><code>&lt;font color="blue"&gt;Text&lt;/font&gt;</code></td></tr>
<tr>
<td><strong>face</strong></td><td>Font type</td><td><code>&lt;font face="Verdana"&gt;Text&lt;/font&gt;</code></td></tr>
<tr>
<td><strong>basefont</strong></td><td>Defines default text size</td><td><code>&lt;basefont size="3"&gt;</code></td></tr>
<tr>
<td><strong>small/big</strong></td><td>Makes text smaller or bigger</td><td><code>&lt;small&gt;small&lt;/small&gt;</code> <code>&lt;big&gt;big&lt;/big&gt;</code></td></tr>
</tbody>
</table>
</div><hr />
<p>✅ <strong>Summary of Key Points</strong></p>
<ul>
<li><p>Web browsers display HTML pages; search engines help find them.</p>
</li>
<li><p>Internet technologies include HTML, CSS, JavaScript, and backend tools.</p>
</li>
<li><p>CMS simplifies web management without coding.</p>
</li>
<li><p>HTML provides structure using tags and attributes.</p>
</li>
<li><p>Basic tags define headings, paragraphs, and background.</p>
</li>
<li><p><code>&lt;font&gt;</code> tag adjusts text appearance (use CSS instead in modern web).</p>
</li>
</ul>
<hr />
<h2 id="heading-648-paragraph-formatting"><strong>6.4.8 Paragraph Formatting (</strong><code>&lt;p&gt;</code>)</h2>
<h3 id="heading-definition-1">📘 <strong>Definition</strong></h3>
<p>The <code>&lt;p&gt;</code> tag is used to define <strong>paragraphs</strong> of text in HTML.<br />Browsers automatically add <strong>a blank line (margin)</strong> before and after each paragraph.</p>
<h3 id="heading-example-6">🧩 <strong>Example</strong></h3>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>This is the first paragraph.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>This is the second paragraph. It will appear below the first one.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1760198906137/a2219763-dd1b-4c7f-bf85-5210217f9972.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-attributes-1">🔹 <strong>Attributes</strong></h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Attribute</td><td>Description</td><td>Example</td></tr>
</thead>
<tbody>
<tr>
<td><code>align</code></td><td>Aligns text within paragraph</td><td><code>&lt;p align="center"&gt;Centered text&lt;/p&gt;</code></td></tr>
</tbody>
</table>
</div><h3 id="heading-note">💡 <strong>Note:</strong></h3>
<p>Avoid using multiple <code>&lt;br&gt;</code> for spacing — use <code>&lt;p&gt;</code> tags instead for proper formatting.</p>
<hr />
<h2 id="heading-649-break-line"><strong>6.4.9 Break Line (</strong><code>&lt;br&gt;</code>)</h2>
<h3 id="heading-definition-2">📘 <strong>Definition</strong></h3>
<p>The <code>&lt;br&gt;</code> tag inserts a <strong>line break</strong> (new line) without starting a new paragraph.</p>
<h3 id="heading-example-7">🧩 <strong>Example</strong></h3>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Hello<span class="hljs-tag">&lt;<span class="hljs-name">br</span>&gt;</span>World!<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Line 1<span class="hljs-tag">&lt;<span class="hljs-name">br</span>&gt;</span>Line 2<span class="hljs-tag">&lt;<span class="hljs-name">br</span>&gt;</span>Line 3<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<blockquote>
<p>💡 <code>&lt;br&gt;</code> is an <strong>empty tag</strong>, meaning it has <strong>no closing tag</strong>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1760198447485/195afe13-67f9-4710-b474-8f6ba851748f.png" alt class="image--center mx-auto" /></p>
</blockquote>
<hr />
<h2 id="heading-6410-comment-in-html"><strong>6.4.10 Comment in HTML</strong></h2>
<h3 id="heading-definition-3">📘 <strong>Definition</strong></h3>
<p>Comments are used to <strong>add notes or explanations</strong> inside HTML code.<br />They are <strong>not displayed</strong> in the web page output.</p>
<h3 id="heading-syntax">🧩 <strong>Syntax</strong></h3>
<pre><code class="lang-html"><span class="hljs-comment">&lt;!-- This is a comment --&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>This will be displayed.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-comment">&lt;!-- &lt;p&gt;This will not be displayed.&lt;/p&gt; --&gt;</span>
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1760198407933/b1edbed3-9e40-4941-8e1e-d4072c85679e.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-use">💡 <strong>Use:</strong></h3>
<ul>
<li><p>To explain sections of code</p>
</li>
<li><p>To temporarily hide code during testing</p>
</li>
</ul>
<hr />
<h2 id="heading-6411-formatting-text"><strong>6.4.11 Formatting Text</strong></h2>
<p>HTML provides various tags for <strong>text formatting</strong>, making it bold, italic, underlined, etc.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Tag</strong></td><td><strong>Meaning / Function</strong></td><td><strong>Example</strong></td></tr>
</thead>
<tbody>
<tr>
<td><code>&lt;b&gt;</code></td><td>Bold text</td><td><code>&lt;b&gt;Bold&lt;/b&gt;</code></td></tr>
<tr>
<td><code>&lt;i&gt;</code></td><td>Italic text</td><td><code>&lt;i&gt;Italic&lt;/i&gt;</code></td></tr>
<tr>
<td><code>&lt;u&gt;</code></td><td>Underlined text</td><td><code>&lt;u&gt;Underlined&lt;/u&gt;</code></td></tr>
<tr>
<td><code>&lt;mark&gt;</code></td><td>Highlighted text</td><td><code>&lt;mark&gt;Important&lt;/mark&gt;</code></td></tr>
<tr>
<td><code>&lt;sup&gt;</code></td><td>Superscript (above)</td><td><code>x&lt;sup&gt;2&lt;/sup&gt;</code></td></tr>
<tr>
<td><code>&lt;sub&gt;</code></td><td>Subscript (below)</td><td><code>H&lt;sub&gt;2&lt;/sub&gt;O</code></td></tr>
<tr>
<td><code>&lt;em&gt;</code></td><td>Emphasized (italic by default)</td><td><code>&lt;em&gt;Emphasized&lt;/em&gt;</code></td></tr>
<tr>
<td><code>&lt;blockquote&gt;</code></td><td>Quotation block</td><td><code>&lt;blockquote&gt;Quote text&lt;/blockquote&gt;</code></td></tr>
<tr>
<td><code>&lt;pre&gt;</code></td><td>Preformatted text (keeps spaces and lines)</td><td><code>&lt;pre&gt;Line 1 Line 2&lt;/pre&gt;</code></td></tr>
</tbody>
</table>
</div><h3 id="heading-example-8">🧩 <strong>Example</strong></h3>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>This is <span class="hljs-tag">&lt;<span class="hljs-name">b</span>&gt;</span>bold<span class="hljs-tag">&lt;/<span class="hljs-name">b</span>&gt;</span> and <span class="hljs-tag">&lt;<span class="hljs-name">i</span>&gt;</span>italic<span class="hljs-tag">&lt;/<span class="hljs-name">i</span>&gt;</span> text.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>H<span class="hljs-tag">&lt;<span class="hljs-name">sub</span>&gt;</span>2<span class="hljs-tag">&lt;/<span class="hljs-name">sub</span>&gt;</span>O is the formula for water.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">blockquote</span>&gt;</span>"The best way to predict the future is to create it."<span class="hljs-tag">&lt;/<span class="hljs-name">blockquote</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">pre</span>&gt;</span>
This text
   keeps its spacing
and line breaks.
<span class="hljs-tag">&lt;/<span class="hljs-name">pre</span>&gt;</span>
</code></pre>
<hr />
<p>OUTPUT:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1760198353267/860e739e-972e-4854-87c5-377cbaa550dc.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-6412-ordered-list"><strong>6.4.12 Ordered List (</strong><code>&lt;ol&gt;</code>)</h2>
<h3 id="heading-definition-4">📘 <strong>Definition</strong></h3>
<p>An <strong>ordered list</strong> displays items in a specific order — numbered, lettered, or Roman numerals.</p>
<h3 id="heading-example-9">🧩 <strong>Example</strong></h3>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">ol</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>HTML<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>CSS<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>JavaScript<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">ol</span>&gt;</span>
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1760198951671/ccb13e1a-c6cc-4c0b-ada5-0a626840d342.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-attributes-of">🔹 <strong>Attributes of</strong> <code>&lt;ol&gt;</code></h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Attribute</td><td>Description</td><td>Example</td></tr>
</thead>
<tbody>
<tr>
<td><code>type</code></td><td>Defines numbering type</td><td><code>&lt;ol type="A"&gt;</code></td></tr>
<tr>
<td><code>start</code></td><td>Starting number or letter</td><td><code>&lt;ol start="5"&gt;</code></td></tr>
<tr>
<td><code>value</code></td><td>Specifies value of a particular list item</td><td><code>&lt;li value="10"&gt;Item&lt;/li&gt;</code></td></tr>
</tbody>
</table>
</div><h3 id="heading-list-type-options">🔸 <strong>List Type Options</strong></h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Type</td><td>Result Example</td></tr>
</thead>
<tbody>
<tr>
<td><code>1</code></td><td>1, 2, 3</td></tr>
<tr>
<td><code>A</code></td><td>A, B, C</td></tr>
<tr>
<td><code>a</code></td><td>a, b, c</td></tr>
<tr>
<td><code>I</code></td><td>I, II, III</td></tr>
<tr>
<td><code>i</code></td><td>i, ii, iii</td></tr>
</tbody>
</table>
</div><h3 id="heading-example-10">🧩 <strong>Example</strong></h3>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">ol</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"I"</span> <span class="hljs-attr">start</span>=<span class="hljs-string">"3"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>Introduction<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>Body<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>Conclusion<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">ol</span>&gt;</span>
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1760198980144/0f7d8957-848f-4140-a766-b84064fdd6f7.png" alt class="image--center mx-auto" /></p>
<hr />
<h2 id="heading-6413-unordered-list-and-definition-list"><strong>6.4.13 Unordered List (</strong><code>&lt;ul&gt;</code>) and Definition List (<code>&lt;dl&gt;</code>)</h2>
<h3 id="heading-unordered-list">📘 <strong>Unordered List</strong></h3>
<p>Displays items <strong>without order</strong>, usually with <strong>bullet points</strong>.</p>
<h3 id="heading-example-11">🧩 <strong>Example</strong></h3>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">ul</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"circle"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>Apple<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>Banana<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>Cherry<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span>
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1760199004318/f2ddd612-073d-48db-8518-dfda717944ac.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-bullet-types">🔹 <strong>Bullet Types</strong></h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Type</td><td>Symbol</td></tr>
</thead>
<tbody>
<tr>
<td><code>disc</code></td><td>●</td></tr>
<tr>
<td><code>circle</code></td><td>○</td></tr>
<tr>
<td><code>square</code></td><td>■</td></tr>
</tbody>
</table>
</div><hr />
<h3 id="heading-definition-list">📘 <strong>Definition List</strong></h3>
<p>Used for <strong>terms and their definitions</strong> (like in dictionaries).</p>
<h3 id="heading-example-12">🧩 <strong>Example</strong></h3>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">dl</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">dt</span>&gt;</span>HTML<span class="hljs-tag">&lt;/<span class="hljs-name">dt</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">dd</span>&gt;</span>HyperText Markup Language<span class="hljs-tag">&lt;/<span class="hljs-name">dd</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">dt</span>&gt;</span>CSS<span class="hljs-tag">&lt;/<span class="hljs-name">dt</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">dd</span>&gt;</span>Cascading Style Sheets<span class="hljs-tag">&lt;/<span class="hljs-name">dd</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">dl</span>&gt;</span>
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1760199036845/3adf0ac1-c844-4446-9633-da5ace6e7737.png" alt class="image--center mx-auto" /></p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Tag</td><td>Meaning</td></tr>
</thead>
<tbody>
<tr>
<td><code>&lt;dl&gt;</code></td><td>Definition List container</td></tr>
<tr>
<td><code>&lt;dt&gt;</code></td><td>Definition Term</td></tr>
<tr>
<td><code>&lt;dd&gt;</code></td><td>Definition Description</td></tr>
</tbody>
</table>
</div><hr />
<h2 id="heading-6414-address-tag"><strong>6.4.14 ADDRESS Tag</strong></h2>
<h3 id="heading-definition-5">📘 <strong>Definition</strong></h3>
<p>The <code>&lt;address&gt;</code> tag defines <strong>contact information</strong> for the author or owner of a web page.</p>
<h3 id="heading-example-13">🧩 <strong>Example</strong></h3>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">address</span>&gt;</span>
Written by <span class="hljs-tag">&lt;<span class="hljs-name">b</span>&gt;</span>Aarav Poudel<span class="hljs-tag">&lt;/<span class="hljs-name">b</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">br</span>&gt;</span>
Visit us at: <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"https://www.example.com"</span>&gt;</span>www.example.com<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">br</span>&gt;</span>
Email: <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"mailto:info@example.com"</span>&gt;</span>info@example.com<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">br</span>&gt;</span>
Location: Dharan, Sunsari, Nepal
<span class="hljs-tag">&lt;/<span class="hljs-name">address</span>&gt;</span>
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1760199067122/cde41131-5c35-4176-98ed-9dffd31ee503.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-displayed-in-italic-font-by-default">💡 <strong>Displayed in italic font by default.</strong></h3>
<hr />
<h2 id="heading-creating-links-anchor-tag"><strong>Creating Links (Anchor Tag</strong> <code>&lt;a&gt;</code>)</h2>
<h3 id="heading-definition-6">📘 <strong>Definition</strong></h3>
<p>The <code>&lt;a&gt;</code> tag (anchor tag) creates <strong>hyperlinks</strong> that connect to other pages or sections.</p>
<h3 id="heading-syntax-1">🔹 <strong>Syntax</strong></h3>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"URL"</span>&gt;</span>Link Text<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
</code></pre>
<hr />
<h3 id="heading-1-link-to-other-html-documents">🧩 <strong>1. Link to Other HTML Documents</strong></h3>
<p>This will open the html document named about.html</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"about.html"</span>&gt;</span>About Us<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
</code></pre>
<hr />
<h3 id="heading-2-link-to-other-websites">🧩 <strong>2. Link to Other Websites</strong></h3>
<p>This will open the Website of google. (“https://www.google.com”)</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"https://www.google.com"</span>&gt;</span>Visit Google<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
</code></pre>
<hr />
<h3 id="heading-3-open-link-in-new-tab">🧩 <strong>3. Open Link in New Tab</strong></h3>
<p>This will open the link in a new tab</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"https://example.com"</span> <span class="hljs-attr">target</span>=<span class="hljs-string">"_blank"</span>&gt;</span>Open in New Tab<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
</code></pre>
<hr />
<h3 id="heading-4-link-to-a-specific-section-on-the-same-page">🧩 <strong>4. Link to a Specific Section on the Same Page</strong></h3>
<p>when we click “Go to Contact Section , the window will move to show the html element that had id=”contact” attribute i.e Contact Us</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"#contact"</span>&gt;</span>Go to Contact Section<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">h2</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"contact"</span>&gt;</span>Contact Us<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Here are our contact details.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<hr />
<h3 id="heading-5-email-link">🧩 <strong>5. Email Link</strong></h3>
<p>On clicking Send Email , it will open the Gmail, or other Email Client Application to allow us to send email on the given address.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"mailto:info@example.com"</span>&gt;</span>Send Email<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
</code></pre>
<hr />
<h3 id="heading-6-telephone-link">🧩 <strong>6. Telephone Link</strong></h3>
<p>It will open a dialer on mobile phone to allow us to call the given phone number</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"tel:+9779812345678"</span>&gt;</span>Call Us<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
</code></pre>
<hr />
<p>✅ <strong>Summary:</strong></p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Concept</td><td>Description</td><td>Example</td></tr>
</thead>
<tbody>
<tr>
<td>Paragraph</td><td>Creates text block</td><td><code>&lt;p&gt;Text&lt;/p&gt;</code></td></tr>
<tr>
<td>Break line</td><td>New line</td><td><code>&lt;br&gt;</code></td></tr>
<tr>
<td>Comment</td><td>Hidden note</td><td><code>&lt;!-- note --&gt;</code></td></tr>
<tr>
<td>Formatting</td><td>Style text</td><td><code>&lt;b&gt;, &lt;i&gt;, &lt;u&gt;</code> etc.</td></tr>
<tr>
<td>Ordered List</td><td>Numbered list</td><td><code>&lt;ol&gt;&lt;li&gt;&lt;/li&gt;&lt;/ol&gt;</code></td></tr>
<tr>
<td>Unordered List</td><td>Bulleted list</td><td><code>&lt;ul&gt;&lt;li&gt;&lt;/li&gt;&lt;/ul&gt;</code></td></tr>
<tr>
<td>Definition List</td><td>Terms &amp; definitions</td><td><code>&lt;dl&gt;&lt;dt&gt;&lt;/dt&gt;&lt;dd&gt;&lt;/dd&gt;&lt;/dl&gt;</code></td></tr>
<tr>
<td>Address</td><td>Author’s info</td><td><code>&lt;address&gt;...&lt;/address&gt;</code></td></tr>
<tr>
<td>Link</td><td>Creates hyperlink</td><td><code>&lt;a href="..."&gt;Link&lt;/a&gt;</code></td></tr>
</tbody>
</table>
</div><hr />
]]></content:encoded></item><item><title><![CDATA[🔧 Creating and Understanding a systemd Service File on Raspberry Pi]]></title><description><![CDATA[A systemd service file is used in Linux (including Raspberry Pi OS) to define how a service (like a Python script or web server) should be started, stopped, restarted, and managed.
Here’s the basic structure of a .service file:
[Unit]
Description=You...]]></description><link>https://blog.aarav.com.np/creating-and-understanding-a-systemd-service-file-on-raspberry-pi</link><guid isPermaLink="true">https://blog.aarav.com.np/creating-and-understanding-a-systemd-service-file-on-raspberry-pi</guid><dc:creator><![CDATA[Aarav Poudel]]></dc:creator><pubDate>Sun, 22 Jun 2025 00:58:32 GMT</pubDate><content:encoded><![CDATA[<p>A <strong>systemd service file</strong> is used in Linux (including Raspberry Pi OS) to define how a service (like a Python script or web server) should be started, stopped, restarted, and managed.</p>
<p>Here’s the <strong>basic structure</strong> of a <code>.service</code> file:</p>
<pre><code class="lang-ini"><span class="hljs-section">[Unit]</span>
<span class="hljs-attr">Description</span>=Your Service Description
<span class="hljs-attr">After</span>=network.target

<span class="hljs-section">[Service]</span>
<span class="hljs-attr">ExecStart</span>=/usr/bin/python3 /path/to/your/script.py
<span class="hljs-attr">WorkingDirectory</span>=/path/to/your/
<span class="hljs-attr">StandardOutput</span>=inherit
<span class="hljs-attr">StandardError</span>=inherit
<span class="hljs-attr">Restart</span>=always
<span class="hljs-attr">User</span>=pi

<span class="hljs-section">[Install]</span>
<span class="hljs-attr">WantedBy</span>=multi-user.target
</code></pre>
<hr />
<h3 id="heading-section-breakdown">🔍 Section Breakdown</h3>
<h4 id="heading-unit"><code>[Unit]</code></h4>
<ul>
<li><p><code>Description=</code>: Human-readable description of the service.</p>
</li>
<li><p><code>After=</code>: Specifies service start order. Commonly set to <a target="_blank" href="http://network.target"><code>network.target</code></a> if the service depends on networking.</p>
</li>
</ul>
<h4 id="heading-service"><code>[Service]</code></h4>
<ul>
<li><p><code>ExecStart=</code>: The full command to run your service. Use full paths!</p>
</li>
<li><p><code>WorkingDirectory=</code>: Directory where the script will be run.</p>
</li>
<li><p><code>StandardOutput=</code> and <code>StandardError=</code>: Where logs are directed. <code>inherit</code> passes it to the system journal.</p>
</li>
<li><p><code>Restart=</code>: Automatically restart the service if it crashes. Use <code>always</code> or <code>on-failure</code>.</p>
</li>
<li><p><code>User=</code>: Specifies the user under which the service will run (commonly <code>pi</code> on Raspberry Pi).</p>
</li>
</ul>
<h4 id="heading-install"><code>[Install]</code></h4>
<ul>
<li><code>WantedBy=</code><a target="_blank" href="http://multi-user.target"><code>multi-user.target</code></a>: Tells systemd to start the service at boot in the typical multi-user (non-graphical) mode.</li>
</ul>
<hr />
<h3 id="heading-example-blink-led-python-script-service">Example: Blink LED Python Script Service</h3>
<p>Let's say you have a script: <code>/home/pi/</code><a target="_blank" href="http://blink.py"><code>blink.py</code></a></p>
<pre><code class="lang-ini"><span class="hljs-section">[Unit]</span>
<span class="hljs-attr">Description</span>=Blink LED <span class="hljs-literal">on</span> Raspberry Pi
<span class="hljs-attr">After</span>=network.target

<span class="hljs-section">[Service]</span>
<span class="hljs-attr">ExecStart</span>=/usr/bin/python3 /home/pi/blink.py
<span class="hljs-attr">WorkingDirectory</span>=/home/pi/
<span class="hljs-attr">StandardOutput</span>=inherit
<span class="hljs-attr">StandardError</span>=inherit
<span class="hljs-attr">Restart</span>=always
<span class="hljs-attr">User</span>=pi

<span class="hljs-section">[Install]</span>
<span class="hljs-attr">WantedBy</span>=multi-user.target
</code></pre>
<p>Save this file as <code>/etc/systemd/system/blink.service</code></p>
<hr />
<h3 id="heading-to-use-it">To Use It:</h3>
<pre><code class="lang-bash">sudo systemctl daemon-reload           <span class="hljs-comment"># Reload systemd manager configuration</span>
sudo systemctl <span class="hljs-built_in">enable</span> blink.service    <span class="hljs-comment"># Enable on boot</span>
sudo systemctl start blink.service     <span class="hljs-comment"># Start the service</span>
sudo systemctl status blink.service    <span class="hljs-comment"># Check its status</span>
</code></pre>
<p>To create a <strong>Linux systemd service file</strong> that runs your <a target="_blank" href="http://blink.py"><code>blink.py</code></a> Python script on a Raspberry Pi (e.g., at boot), follow these steps:</p>
<hr />
<h3 id="heading-1-sample-blinkpyhttpblinkpy-script">✅ 1. <strong>Sample</strong> <a target="_blank" href="http://blink.py"><code>blink.py</code></a> script</h3>
<p>Make sure your script is executable and working:</p>
<pre><code class="lang-python"><span class="hljs-comment"># blink.py</span>
<span class="hljs-keyword">import</span> RPi.GPIO <span class="hljs-keyword">as</span> GPIO
<span class="hljs-keyword">import</span> time

GPIO.setmode(GPIO.BCM)
GPIO.setup(<span class="hljs-number">17</span>, GPIO.OUT)

<span class="hljs-keyword">try</span>:
    <span class="hljs-keyword">while</span> <span class="hljs-literal">True</span>:
        GPIO.output(<span class="hljs-number">17</span>, GPIO.HIGH)
        time.sleep(<span class="hljs-number">1</span>)
        GPIO.output(<span class="hljs-number">17</span>, GPIO.LOW)
        time.sleep(<span class="hljs-number">1</span>)
<span class="hljs-keyword">except</span> KeyboardInterrupt:
    <span class="hljs-keyword">pass</span>
<span class="hljs-keyword">finally</span>:
    GPIO.cleanup()
</code></pre>
<p>Save this file at <code>/home/pi/</code><a target="_blank" href="http://blink.py"><code>blink.py</code></a> (or wherever you'd like).</p>
<hr />
<h3 id="heading-2-make-it-executable">✅ 2. <strong>Make it executable</strong></h3>
<pre><code class="lang-bash">chmod +x /home/pi/blink.py
</code></pre>
<hr />
<h3 id="heading-3-create-a-systemd-service-file">✅ 3. <strong>Create a systemd service file</strong></h3>
<p>Create a new service file:</p>
<pre><code class="lang-bash">sudo nano /etc/systemd/system/blink.service
</code></pre>
<p>Paste the following content:</p>
<pre><code class="lang-ini"><span class="hljs-section">[Unit]</span>
<span class="hljs-attr">Description</span>=Blink LED using Python script
<span class="hljs-attr">After</span>=multi-user.target

<span class="hljs-section">[Service]</span>
<span class="hljs-attr">ExecStart</span>=/usr/bin/python3 /home/pi/blink.py
<span class="hljs-attr">WorkingDirectory</span>=/home/pi
<span class="hljs-attr">StandardOutput</span>=inherit
<span class="hljs-attr">StandardError</span>=inherit
<span class="hljs-attr">Restart</span>=always
<span class="hljs-attr">User</span>=pi

<span class="hljs-section">[Install]</span>
<span class="hljs-attr">WantedBy</span>=multi-user.target
</code></pre>
<blockquote>
<p><strong>Note:</strong> If you're using a virtual environment, replace <code>/usr/bin/python3</code> with the path to your virtual environment's Python binary.</p>
</blockquote>
<hr />
<h3 id="heading-4-enable-and-start-the-service">✅ 4. <strong>Enable and start the service</strong></h3>
<pre><code class="lang-bash">
sudo systemctl daemon-reload
sudo systemctl <span class="hljs-built_in">enable</span> blink.service
sudo systemctl start blink.service
</code></pre>
<hr />
<h3 id="heading-5-check-status">✅ 5. <strong>Check status</strong></h3>
<pre><code class="lang-bash">sudo systemctl status blink.service
</code></pre>
<hr />
<h3 id="heading-6-logs-optional">✅ 6. <strong>Logs (optional)</strong></h3>
<p>If your script prints something or crashes:</p>
<pre><code class="lang-bash">journalctl -u blink.service -f
</code></pre>
<hr />
<p>To <strong>disable</strong> or <strong>stop</strong> your <code>blink.service</code> on Raspberry Pi (or any Linux system using <code>systemd</code>):</p>
<hr />
<h3 id="heading-to-stop-the-service-immediately">🛑 To <strong>stop</strong> the service (immediately):</h3>
<pre><code class="lang-bash">sudo systemctl stop blink.service
</code></pre>
<blockquote>
<p>This halts the running service but <strong>does not prevent it from starting at boot</strong>.</p>
</blockquote>
<hr />
<h3 id="heading-to-disable-the-service-prevent-it-from-starting-at-boot">🚫 To <strong>disable</strong> the service (prevent it from starting at boot):</h3>
<pre><code class="lang-bash">sudo systemctl <span class="hljs-built_in">disable</span> blink.service
</code></pre>
<blockquote>
<p>You can combine both:</p>
</blockquote>
<pre><code class="lang-bash">sudo systemctl stop blink.service
sudo systemctl <span class="hljs-built_in">disable</span> blink.service
</code></pre>
<hr />
<h3 id="heading-to-re-enable-later">✅ To <strong>re-enable</strong> later:</h3>
<pre><code class="lang-bash">sudo systemctl <span class="hljs-built_in">enable</span> blink.service
sudo systemctl start blink.service
</code></pre>
]]></content:encoded></item><item><title><![CDATA[Logging DHT11 temperature and humidity readings to ThingSpeak using Python's requests module.]]></title><description><![CDATA[Here's a complete guide to logging DHT11 temperature and humidity readings to ThingSpeak using Python's requests module. This will assume you're using a Raspberry Pi with a DHT sensor (like DHT11 or DHT22) connected.

🔧 What You Need

Raspberry Pi w...]]></description><link>https://blog.aarav.com.np/logging-dht11-temperature-and-humidity-readings-to-thingspeak-using-pythons-requests-module</link><guid isPermaLink="true">https://blog.aarav.com.np/logging-dht11-temperature-and-humidity-readings-to-thingspeak-using-pythons-requests-module</guid><dc:creator><![CDATA[Aarav Poudel]]></dc:creator><pubDate>Sun, 22 Jun 2025 00:31:28 GMT</pubDate><content:encoded><![CDATA[<p>Here's a complete guide to <strong>logging DHT11 temperature and humidity readings to ThingSpeak</strong> using Python's <code>requests</code> module. This will assume you're using a Raspberry Pi with a DHT sensor (like DHT11 or DHT22) connected.</p>
<hr />
<h2 id="heading-what-you-need">🔧 What You Need</h2>
<ul>
<li><p>Raspberry Pi with internet access</p>
</li>
<li><p>DHT11 or DHT22 sensor</p>
</li>
<li><p>Python installed (<code>requests</code>, <code>Adafruit_DHT</code>)</p>
</li>
<li><p>ThingSpeak account with a channel and <strong>Write API Key</strong></p>
</li>
</ul>
<hr />
<h2 id="heading-step-by-step-implementation">✅ Step-by-Step Implementation</h2>
<h3 id="heading-1-install-required-libraries-on-environment">1. <strong>Install Required Libraries on environment</strong></h3>
<pre><code class="lang-bash">pip install requests
pip install Adafruit_DHT
</code></pre>
<hr />
<h3 id="heading-2-thingspeak-setup">2. <strong>ThingSpeak Setup</strong></h3>
<ul>
<li><p>Go to <a target="_blank" href="https://thingspeak.com/">ThingSpeak</a></p>
</li>
<li><p>Create a channel</p>
</li>
<li><p>Enable <code>field1</code> (Temperature) and <code>field2</code> (Humidity)</p>
</li>
<li><p>Copy the <strong>Write API Key</strong> (found in API Keys tab)</p>
</li>
</ul>
<hr />
<h3 id="heading-3-python-script-to-read-and-upload">3. <strong>Python Script to Read and Upload</strong></h3>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> Adafruit_DHT
<span class="hljs-keyword">import</span> requests
<span class="hljs-keyword">import</span> time

<span class="hljs-comment"># Sensor details</span>
DHT_SENSOR = Adafruit_DHT.DHT11
DHT_PIN = <span class="hljs-number">4</span>  <span class="hljs-comment"># GPIO4 (change if needed)</span>

<span class="hljs-comment"># ThingSpeak API details</span>
THINGSPEAK_WRITE_API = <span class="hljs-string">"YOUR_WRITE_API_KEY_HERE"</span>
THINGSPEAK_URL = <span class="hljs-string">"https://api.thingspeak.com/update"</span>

<span class="hljs-comment"># Logging loop</span>
<span class="hljs-keyword">while</span> <span class="hljs-literal">True</span>:
    humidity, temperature = Adafruit_DHT.read_retry(DHT_SENSOR, DHT_PIN)

    <span class="hljs-keyword">if</span> humidity <span class="hljs-keyword">is</span> <span class="hljs-keyword">not</span> <span class="hljs-literal">None</span> <span class="hljs-keyword">and</span> temperature <span class="hljs-keyword">is</span> <span class="hljs-keyword">not</span> <span class="hljs-literal">None</span>:
        print(<span class="hljs-string">f"Temp=<span class="hljs-subst">{temperature:<span class="hljs-number">.1</span>f}</span>C  Humidity=<span class="hljs-subst">{humidity:<span class="hljs-number">.1</span>f}</span>%"</span>)

        <span class="hljs-comment"># Send data to ThingSpeak</span>
        payload = {
            <span class="hljs-string">'api_key'</span>: THINGSPEAK_WRITE_API,
            <span class="hljs-string">'field1'</span>: temperature,
            <span class="hljs-string">'field2'</span>: humidity
        }

        <span class="hljs-keyword">try</span>:
            response = requests.get(THINGSPEAK_URL, params=payload)
            <span class="hljs-keyword">if</span> response.status_code == <span class="hljs-number">200</span>:
                print(<span class="hljs-string">"Data sent to ThingSpeak."</span>)
            <span class="hljs-keyword">else</span>:
                print(<span class="hljs-string">"Failed to send data, HTTP:"</span>, response.status_code)
        <span class="hljs-keyword">except</span> Exception <span class="hljs-keyword">as</span> e:
            print(<span class="hljs-string">"Request failed:"</span>, e)
    <span class="hljs-keyword">else</span>:
        print(<span class="hljs-string">"Failed to retrieve data from DHT sensor"</span>)

    <span class="hljs-comment"># Wait 15 seconds (ThingSpeak limit)</span>
    time.sleep(<span class="hljs-number">15</span>)
</code></pre>
<hr />
<h2 id="heading-notes">📝 Notes</h2>
<ul>
<li><p>Replace <code>YOUR_WRITE_API_KEY_HERE</code> with your actual ThingSpeak Write API Key.</p>
</li>
<li><p>ThingSpeak accepts <strong>1 update every 15 seconds</strong> on free plans.</p>
</li>
<li><p>You can run this script using:</p>
</li>
</ul>
<pre><code class="lang-bash">python3 thingspeak_logger.py
</code></pre>
<hr />
<p>Would you like this to run as a <strong>background service</strong> (systemd) on boot?</p>
]]></content:encoded></item><item><title><![CDATA[Room Monitor using Flask Server and DHT Sensor]]></title><description><![CDATA[📁 Project Structure
room_monitor/
├── app.py
├── templates/
│   └── index.html

app.py
from flask import Flask, render_template
import Adafruit_DHT

app = Flask(__name__)

DHT_SENSOR = Adafruit_DHT.DHT11  # or DHT22
DHT_PIN = 4  # GPIO4

@app.route(...]]></description><link>https://blog.aarav.com.np/room-monitor-using-flask-server-and-dht-sensor</link><guid isPermaLink="true">https://blog.aarav.com.np/room-monitor-using-flask-server-and-dht-sensor</guid><dc:creator><![CDATA[Aarav Poudel]]></dc:creator><pubDate>Fri, 20 Jun 2025 01:02:58 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1750381427018/9a40406c-b376-4a92-ab04-2a70c0fe2d0d.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-project-structure">📁 Project Structure</h2>
<pre><code class="lang-python">room_monitor/
├── app.py
├── templates/
│   └── index.html
</code></pre>
<p><strong>app.py</strong></p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> flask <span class="hljs-keyword">import</span> Flask, render_template
<span class="hljs-keyword">import</span> Adafruit_DHT

app = Flask(__name__)

DHT_SENSOR = Adafruit_DHT.DHT11  <span class="hljs-comment"># or DHT22</span>
DHT_PIN = <span class="hljs-number">4</span>  <span class="hljs-comment"># GPIO4</span>

<span class="hljs-meta">@app.route('/')</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">index</span>():</span>
    humidity, temperature = Adafruit_DHT.read_retry(DHT_SENSOR, DHT_PIN)
    <span class="hljs-keyword">if</span> humidity <span class="hljs-keyword">is</span> <span class="hljs-keyword">not</span> <span class="hljs-literal">None</span> <span class="hljs-keyword">and</span> temperature <span class="hljs-keyword">is</span> <span class="hljs-keyword">not</span> <span class="hljs-literal">None</span>:
        status = <span class="hljs-string">"Success"</span>
    <span class="hljs-keyword">else</span>:
        status = <span class="hljs-string">"Sensor error"</span>
        temperature = humidity = <span class="hljs-literal">None</span>
    <span class="hljs-keyword">return</span> render_template(<span class="hljs-string">'index.html'</span>, temperature=temperature, humidity=humidity, status=status)

<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    app.run(host=<span class="hljs-string">'0.0.0.0'</span>, port=<span class="hljs-number">5000</span>)
</code></pre>
<p><strong>index.html</strong></p>
<pre><code class="lang-xml"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<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">title</span>&gt;</span>Room Monitor<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">style</span>&gt;</span><span class="css">
        <span class="hljs-selector-tag">body</span> {
            <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span>;
            <span class="hljs-attribute">padding</span>: <span class="hljs-number">0</span>;
            <span class="hljs-attribute">font-family</span>: <span class="hljs-string">'Roboto'</span>, sans-serif;
            <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#f0f2f5</span>;
            <span class="hljs-attribute">display</span>: flex;
            <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">100vh</span>;
        }

        <span class="hljs-selector-class">.card</span> {
            <span class="hljs-attribute">background</span>: <span class="hljs-number">#fff</span>;
            <span class="hljs-attribute">padding</span>: <span class="hljs-number">30px</span> <span class="hljs-number">40px</span>;
            <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">20px</span>;
            <span class="hljs-attribute">box-shadow</span>: <span class="hljs-number">0</span> <span class="hljs-number">10px</span> <span class="hljs-number">25px</span> <span class="hljs-built_in">rgba</span>(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0.1</span>);
            <span class="hljs-attribute">text-align</span>: center;
            <span class="hljs-attribute">max-width</span>: <span class="hljs-number">350px</span>;
            <span class="hljs-attribute">width</span>: <span class="hljs-number">100%</span>;
        }

        <span class="hljs-selector-tag">h1</span> {
            <span class="hljs-attribute">color</span>: <span class="hljs-number">#222</span>;
            <span class="hljs-attribute">margin-bottom</span>: <span class="hljs-number">25px</span>;
            <span class="hljs-attribute">font-size</span>: <span class="hljs-number">28px</span>;
        }

        <span class="hljs-selector-tag">p</span> {
            <span class="hljs-attribute">font-size</span>: <span class="hljs-number">20px</span>;
            <span class="hljs-attribute">margin</span>: <span class="hljs-number">15px</span> <span class="hljs-number">0</span>;
            <span class="hljs-attribute">color</span>: <span class="hljs-number">#333</span>;
        }

        <span class="hljs-selector-class">.status</span> {
            <span class="hljs-attribute">font-weight</span>: bold;
            <span class="hljs-attribute">margin-top</span>: <span class="hljs-number">20px</span>;
            <span class="hljs-attribute">font-size</span>: <span class="hljs-number">16px</span>;
            <span class="hljs-attribute">color</span>: green;
        }

        <span class="hljs-selector-tag">button</span> {
            <span class="hljs-attribute">margin-top</span>: <span class="hljs-number">20px</span>;
            <span class="hljs-attribute">padding</span>: <span class="hljs-number">10px</span> <span class="hljs-number">25px</span>;
            <span class="hljs-attribute">font-size</span>: <span class="hljs-number">16px</span>;
            <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#007BFF</span>;
            <span class="hljs-attribute">border</span>: none;
            <span class="hljs-attribute">color</span>: white;
            <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">8px</span>;
            <span class="hljs-attribute">cursor</span>: pointer;
            <span class="hljs-attribute">transition</span>: background-color <span class="hljs-number">0.3s</span>;
        }

        <span class="hljs-selector-tag">button</span><span class="hljs-selector-pseudo">:hover</span> {
            <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#0056b3</span>;
        }
    </span><span class="hljs-tag">&lt;/<span class="hljs-name">style</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">"card"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>🌡️ Room Monitor<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">strong</span>&gt;</span>Temperature:<span class="hljs-tag">&lt;/<span class="hljs-name">strong</span>&gt;</span> {{ temperature }} <span class="hljs-symbol">&amp;deg;</span>C<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">strong</span>&gt;</span>Humidity:<span class="hljs-tag">&lt;/<span class="hljs-name">strong</span>&gt;</span> {{ humidity }} %<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"status"</span>&gt;</span>{{ status }}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"location.reload()"</span>&gt;</span>🔄 Refresh<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <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>
<p>To auto-reload the page every 5 seconds using JavaScript, you can add a simple <code>&lt;script&gt;</code> tag before the closing <code>&lt;/body&gt;</code> tag. Here's your updated HTML with the auto-reload functionality:</p>
<pre><code class="lang-javascript">&lt;script&gt;
        <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
            location.reload();
        }, <span class="hljs-number">5000</span>); <span class="hljs-comment">// Reload every 5 seconds</span>
&lt;/script&gt;
</code></pre>
<p><strong>index.html with auto reload</strong></p>
<pre><code class="lang-python">&lt;!DOCTYPE html&gt;
&lt;html lang=<span class="hljs-string">"en"</span>&gt;
&lt;head&gt;
    &lt;meta charset=<span class="hljs-string">"UTF-8"</span>&gt;
    &lt;title&gt;Room Monitor&lt;/title&gt;

    &lt;style&gt;
        body {
            margin: <span class="hljs-number">0</span>;
            padding: <span class="hljs-number">0</span>;
            font-family: <span class="hljs-string">'Roboto'</span>, sans-serif;
            background-color: <span class="hljs-comment">#f0f2f5;</span>
            display: flex;
            justify-content: center;
            align-items: center;
            height: <span class="hljs-number">100</span>vh;
        }

        .card {
            background: <span class="hljs-comment">#fff;</span>
            padding: <span class="hljs-number">30</span>px <span class="hljs-number">40</span>px;
            border-radius: <span class="hljs-number">20</span>px;
            box-shadow: <span class="hljs-number">0</span> <span class="hljs-number">10</span>px <span class="hljs-number">25</span>px rgba(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0.1</span>);
            text-align: center;
            max-width: <span class="hljs-number">350</span>px;
            width: <span class="hljs-number">100</span>%;
        }

        h1 {
            color: <span class="hljs-comment">#222;</span>
            margin-bottom: <span class="hljs-number">25</span>px;
            font-size: <span class="hljs-number">28</span>px;
        }

        p {
            font-size: <span class="hljs-number">20</span>px;
            margin: <span class="hljs-number">15</span>px <span class="hljs-number">0</span>;
            color: <span class="hljs-comment">#333;</span>
        }

        .status {
            font-weight: bold;
            margin-top: <span class="hljs-number">20</span>px;
            font-size: <span class="hljs-number">16</span>px;
            color: green;
        }

        button {
            margin-top: <span class="hljs-number">20</span>px;
            padding: <span class="hljs-number">10</span>px <span class="hljs-number">25</span>px;
            font-size: <span class="hljs-number">16</span>px;
            background-color: <span class="hljs-comment">#007BFF;</span>
            border: none;
            color: white;
            border-radius: <span class="hljs-number">8</span>px;
            cursor: pointer;
            transition: background-color <span class="hljs-number">0.3</span>s;
        }

        button:hover {
            background-color: <span class="hljs-comment">#0056b3;</span>
        }
    &lt;/style&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;div <span class="hljs-class"><span class="hljs-keyword">class</span>="<span class="hljs-title">card</span>"&gt;
        &lt;<span class="hljs-title">h1</span>&gt;🌡️ <span class="hljs-title">Room</span> <span class="hljs-title">Monitor</span>&lt;/<span class="hljs-title">h1</span>&gt;
        &lt;<span class="hljs-title">p</span>&gt;&lt;<span class="hljs-title">strong</span>&gt;<span class="hljs-title">Temperature</span>:</span>&lt;/strong&gt; {{ temperature }} &amp;deg;C&lt;/p&gt;
        &lt;p&gt;&lt;strong&gt;Humidity:&lt;/strong&gt; {{ humidity }} %&lt;/p&gt;
        &lt;p <span class="hljs-class"><span class="hljs-keyword">class</span>="<span class="hljs-title">status</span>"&gt;{{ <span class="hljs-title">status</span> }}&lt;/<span class="hljs-title">p</span>&gt;
        &lt;<span class="hljs-title">button</span> <span class="hljs-title">onclick</span>="<span class="hljs-title">location</span>.<span class="hljs-title">reload</span>()"&gt;🔄 <span class="hljs-title">Refresh</span>&lt;/<span class="hljs-title">button</span>&gt;
    &lt;/<span class="hljs-title">div</span>&gt;

    &lt;<span class="hljs-title">script</span>&gt;
        <span class="hljs-title">setTimeout</span>(<span class="hljs-params">function(<span class="hljs-params"></span>) {
            location.reload(<span class="hljs-params"></span>);
        }, <span class="hljs-number">5000</span></span>); // <span class="hljs-title">Reload</span> <span class="hljs-title">every</span> 5 <span class="hljs-title">seconds</span>
    &lt;/<span class="hljs-title">script</span>&gt;
&lt;/<span class="hljs-title">body</span>&gt;
&lt;/<span class="hljs-title">html</span>&gt;</span>
</code></pre>
]]></content:encoded></item><item><title><![CDATA[🌡️ Understanding the DHT Sensor]]></title><description><![CDATA[A Guide to Temperature and Humidity Sensing for Beginners

The DHT sensor is one of the most popular and affordable sensors used for measuring temperature and humidity in DIY electronics, weather stations, automation systems, and educational projects...]]></description><link>https://blog.aarav.com.np/understanding-the-dht-sensor</link><guid isPermaLink="true">https://blog.aarav.com.np/understanding-the-dht-sensor</guid><dc:creator><![CDATA[Aarav Poudel]]></dc:creator><pubDate>Thu, 19 Jun 2025 19:01:38 GMT</pubDate><content:encoded><![CDATA[<h3 id="heading-a-guide-to-temperature-and-humidity-sensing-for-beginners">A Guide to Temperature and Humidity Sensing for Beginners</h3>
<hr />
<p>The <strong>DHT sensor</strong> is one of the most popular and affordable sensors used for measuring <strong>temperature and humidity</strong> in DIY electronics, weather stations, automation systems, and educational projects. This article explores the basic working, technical specifications, common errors, and best practices for using DHT sensors.</p>
<hr />
<h2 id="heading-what-is-a-dht-sensor">🔍 What is a DHT Sensor?</h2>
<p>DHT stands for <strong>Digital Humidity and Temperature</strong> sensor. It integrates two sensors:</p>
<ul>
<li><p>A <strong>capacitive humidity sensor</strong> to measure relative humidity (%RH)</p>
</li>
<li><p>A <strong>thermistor</strong> to measure temperature (°C)</p>
</li>
</ul>
<p>These values are processed internally and sent out through a <strong>single-wire digital signal</strong>, making it easy to interface with microcontrollers like Raspberry Pi, Arduino, or ESP8266.</p>
<hr />
<h2 id="heading-types-of-dht-sensors">🔧 Types of DHT Sensors</h2>
<p>There are two common models:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Feature</td><td><strong>DHT11</strong></td><td><strong>DHT22 (AM2302)</strong></td></tr>
</thead>
<tbody>
<tr>
<td><strong>Temperature Range</strong></td><td>0 – 50°C</td><td>-40 – 80°C</td></tr>
<tr>
<td><strong>Humidity Range</strong></td><td>20 – 80% RH</td><td>0 – 100% RH</td></tr>
<tr>
<td><strong>Temp Accuracy</strong></td><td>±2°C</td><td>±0.5°C</td></tr>
<tr>
<td><strong>Humidity Accuracy</strong></td><td>±5% RH</td><td>±2–5% RH</td></tr>
<tr>
<td><strong>Sampling Rate</strong></td><td>1 Hz (1 read/sec)</td><td>0.5 Hz (1 read every 2 sec)</td></tr>
<tr>
<td><strong>Power Supply</strong></td><td>3.3V – 5.5V</td><td>3.3V – 6V</td></tr>
<tr>
<td><strong>Signal Type</strong></td><td>Digital</td><td>Digital</td></tr>
<tr>
<td><strong>Use Case</strong></td><td>Basic projects</td><td>Precise applications</td></tr>
</tbody>
</table>
</div><blockquote>
<p>🔹 Use DHT11 for hobby projects.<br />🔹 Use DHT22 for accurate, wide-range sensing.</p>
</blockquote>
<hr />
<h2 id="heading-pinout-and-circuit-connection">📦 Pinout and Circuit Connection</h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Pin</td><td>Function</td></tr>
</thead>
<tbody>
<tr>
<td>1</td><td>VCC (3.3V–5V)</td></tr>
<tr>
<td>2</td><td>DATA (digital)</td></tr>
<tr>
<td>3</td><td>NC (No connection)</td></tr>
<tr>
<td>4</td><td>GND</td></tr>
</tbody>
</table>
</div><p><strong>Wiring Tips:</strong></p>
<ul>
<li><p>Connect a <strong>4.7k–10kΩ pull-up resistor</strong> between VCC and DATA.</p>
</li>
<li><p>Some modules come with the resistor built-in.</p>
</li>
</ul>
<hr />
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1750359655508/e8aaff43-6a8d-4256-a327-e33b7fc8ed6e.webp" alt class="image--center mx-auto" /></p>
<h2 id="heading-how-the-dht-sensor-works">🧠 How the DHT Sensor Works</h2>
<p>The sensor samples temperature and humidity internally and then sends a <strong>40-bit data packet</strong> over a single data pin. The packet format is:</p>
<pre><code class="lang-javascript"><span class="hljs-number">8</span> bits Humidity Int | <span class="hljs-number">8</span> bits Humidity Dec
<span class="hljs-number">8</span> bits Temp Int     | <span class="hljs-number">8</span> bits Temp Dec
<span class="hljs-number">8</span> bits Checksum
</code></pre>
<p>For example:</p>
<pre><code class="lang-javascript">Data: <span class="hljs-number">00110010</span> <span class="hljs-number">00000000</span> <span class="hljs-number">00011100</span> <span class="hljs-number">00000000</span> <span class="hljs-number">01000110</span>
→ <span class="hljs-number">50</span>% RH, <span class="hljs-number">28</span>°C, checksum = <span class="hljs-number">0x46</span>
</code></pre>
<p>The <strong>checksum</strong> ensures the reading is valid.</p>
<hr />
<h2 id="heading-python-example-with-raspberry-pi">⚙️ Python Example with Raspberry Pi</h2>
<p>Install the library:</p>
<pre><code class="lang-bash">pip install Adafruit_DHT
</code></pre>
<p>Python code:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> Adafruit_DHT
<span class="hljs-keyword">import</span> time

sensor = Adafruit_DHT.DHT11  <span class="hljs-comment"># or DHT11</span>
pin = <span class="hljs-number">4</span>  <span class="hljs-comment"># GPIO4</span>

<span class="hljs-keyword">while</span> <span class="hljs-literal">True</span>:
    humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
    <span class="hljs-keyword">if</span> humidity <span class="hljs-keyword">is</span> <span class="hljs-keyword">not</span> <span class="hljs-literal">None</span> <span class="hljs-keyword">and</span> temperature <span class="hljs-keyword">is</span> <span class="hljs-keyword">not</span> <span class="hljs-literal">None</span>:
        print(<span class="hljs-string">f"Temp: <span class="hljs-subst">{temperature:<span class="hljs-number">.1</span>f}</span>°C  Humidity: <span class="hljs-subst">{humidity:<span class="hljs-number">.1</span>f}</span>%"</span>)
    <span class="hljs-keyword">else</span>:
        print(<span class="hljs-string">"❌ Error: Failed to read from DHT sensor"</span>)
    time.sleep(<span class="hljs-number">2</span>)
</code></pre>
<hr />
<h2 id="heading-common-errors-and-troubleshooting">❌ Common Errors and Troubleshooting</h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Error</td><td>Cause</td><td>Solution</td></tr>
</thead>
<tbody>
<tr>
<td><code>NoneType</code> or <code>Failed to read</code></td><td>Bad wiring or GPIO misconfiguration</td><td>Double-check connections and GPIO number</td></tr>
<tr>
<td>Fluctuating or incorrect readings</td><td>Noise or unstable power</td><td>Use decoupling capacitors or better power supply</td></tr>
<tr>
<td>Same value repeating constantly</td><td>Reading too fast</td><td>Wait at least 1–2 seconds between reads</td></tr>
<tr>
<td>CRC checksum mismatch</td><td>Interference or loose wires</td><td>Shorten wires; check resistor</td></tr>
<tr>
<td>0% RH or -40°C from DHT22</td><td>Damaged sensor or wrong voltage</td><td>Try using 3.3V or replace the sensor</td></tr>
</tbody>
</table>
</div><hr />
<h2 id="heading-best-practices">🧰 Best Practices</h2>
<p>✅ Use a <strong>pull-up resistor (4.7k–10kΩ)</strong> on the data line<br />✅ Wait <strong>1–2 seconds between readings</strong><br />✅ Keep wires <strong>short</strong> to minimize signal issues<br />✅ Place sensor away from heat sources for accuracy<br />✅ Use <strong>error checking</strong> in code for reliability<br />✅ Test sensor with tools like Arduino IDE or Python CLI before embedding in large codebases</p>
<hr />
<h2 id="heading-real-world-applications">🧪 Real-World Applications</h2>
<ul>
<li><p>Weather stations</p>
</li>
<li><p>Room temperature/humidity monitoring</p>
</li>
<li><p>Smart farming and greenhouses</p>
</li>
<li><p>HVAC control systems</p>
</li>
<li><p>Data logging systems</p>
</li>
</ul>
<hr />
<h2 id="heading-conclusion">📌 Conclusion</h2>
<p>The DHT11 and DHT22 are excellent entry-level sensors for temperature and humidity measurement. While DHT11 is ideal for beginners and non-critical applications, DHT22 is recommended when better precision and a wider range are required.</p>
<p>By understanding their specifications, common errors, and usage techniques, you can confidently integrate DHT sensors into your Raspberry Pi, Arduino, or IoT projects.</p>
<hr />
]]></content:encoded></item><item><title><![CDATA[Sending Email Alert When Temperature Exceeds in Raspberry Pi]]></title><description><![CDATA[send an email when the temperature reaches 32°C or above using a DHT sensor with Raspberry Pi:

🔥 Sending Email Alert When Temperature Exceeds 32°C Using Raspberry Pi and DHT11/DHT22
Monitoring temperature is one of the most common use cases for Ras...]]></description><link>https://blog.aarav.com.np/sending-email-alert-when-temperature-exceeds-in-raspberry-pi</link><guid isPermaLink="true">https://blog.aarav.com.np/sending-email-alert-when-temperature-exceeds-in-raspberry-pi</guid><dc:creator><![CDATA[Aarav Poudel]]></dc:creator><pubDate>Thu, 19 Jun 2025 18:50:01 GMT</pubDate><content:encoded><![CDATA[<p><strong>send an email when the temperature reaches 32°C or above using a DHT sensor with Raspberry Pi</strong>:</p>
<hr />
<h1 id="heading-sending-email-alert-when-temperature-exceeds-32c-using-raspberry-pi-and-dht11dht22">🔥 Sending Email Alert When Temperature Exceeds 32°C Using Raspberry Pi and DHT11/DHT22</h1>
<p>Monitoring temperature is one of the most common use cases for Raspberry Pi-based IoT systems. In this tutorial, we will show you how to use a <strong>DHT11 or DHT22</strong> sensor with Raspberry Pi to read temperature and send an <strong>email alert</strong> when it reaches <strong>32°C or above</strong>.</p>
<hr />
<h2 id="heading-requirements">🧰 Requirements</h2>
<ul>
<li><p>Raspberry Pi (any model with GPIO, e.g., Pi 3/4/Zero W)</p>
</li>
<li><p>DHT11 or DHT22 sensor</p>
</li>
<li><p>Jumper wires</p>
</li>
<li><p>Python 3</p>
</li>
<li><p>Internet connection (for sending emails)</p>
</li>
<li><p>Gmail account (or any SMTP-compatible email)</p>
</li>
</ul>
<hr />
<h2 id="heading-wiring-the-dht-sensor">🔌 Wiring the DHT Sensor</h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td>DHT Pin</td><td>Connect to</td></tr>
</thead>
<tbody>
<tr>
<td>VCC</td><td>3.3V</td></tr>
<tr>
<td>Data</td><td>GPIO4 (BCM 4)</td></tr>
<tr>
<td>GND</td><td>GND</td></tr>
</tbody>
</table>
</div><blockquote>
<p>⚠️ Use a 10kΩ resistor between VCC and DATA for DHT22 (optional but recommended for stable readings).</p>
</blockquote>
<hr />
<h2 id="heading-installing-dependencies">🐍 Installing Dependencies</h2>
<ol>
<li><p><strong>Update packages</strong>:</p>
<pre><code class="lang-bash"> sudo apt update
 sudo apt install python3-pip
</code></pre>
</li>
<li><p><strong>Install Adafruit DHT library</strong>:</p>
<pre><code class="lang-bash"> pip3 install Adafruit_DHT
</code></pre>
</li>
</ol>
<hr />
<h2 id="heading-enable-gmail-for-app-access">📧 Enable Gmail for App Access</h2>
<p>If using Gmail:</p>
<ol>
<li><p>Go to <a target="_blank" href="https://myaccount.google.com/security">Google Account Security</a></p>
</li>
<li><p>Turn <strong>"2-Step Verification"</strong> ON.</p>
</li>
<li><p>Generate an <strong>App Password</strong>.</p>
</li>
<li><p>Save that password — it replaces your usual password in code.</p>
</li>
</ol>
<hr />
<h2 id="heading-python-script-to-monitor-temperature-and-send-email">💻 Python Script to Monitor Temperature and Send Email</h2>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> Adafruit_DHT
<span class="hljs-keyword">import</span> smtplib
<span class="hljs-keyword">from</span> email.mime.text <span class="hljs-keyword">import</span> MIMEText
<span class="hljs-keyword">import</span> time

<span class="hljs-comment"># Constants</span>
DHT_SENSOR = Adafruit_DHT.DHT11  <span class="hljs-comment"># Use DHT22 if needed</span>
DHT_PIN = <span class="hljs-number">4</span>                      <span class="hljs-comment"># GPIO4</span>
ALERT_TEMP = <span class="hljs-number">32.0</span>                <span class="hljs-comment"># Temperature threshold</span>

<span class="hljs-comment"># Email config</span>
SMTP_SERVER = <span class="hljs-string">"smtp.gmail.com"</span>
SMTP_PORT = <span class="hljs-number">587</span>
EMAIL_FROM = <span class="hljs-string">"your_email@gmail.com"</span>
EMAIL_TO = <span class="hljs-string">"receiver_email@gmail.com"</span>
EMAIL_SUBJECT = <span class="hljs-string">"Temperature Alert!"</span>
EMAIL_PASSWORD = <span class="hljs-string">"your_app_password"</span>  <span class="hljs-comment"># Use App Password for Gmail</span>

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">send_email</span>(<span class="hljs-params">temp</span>):</span>
    body = <span class="hljs-string">f"Warning! The temperature has reached <span class="hljs-subst">{temp:<span class="hljs-number">.1</span>f}</span>°C."</span>
    msg = MIMEText(body)
    msg[<span class="hljs-string">"Subject"</span>] = EMAIL_SUBJECT
    msg[<span class="hljs-string">"From"</span>] = EMAIL_FROM
    msg[<span class="hljs-string">"To"</span>] = EMAIL_TO

    <span class="hljs-keyword">try</span>:
        <span class="hljs-keyword">with</span> smtplib.SMTP(SMTP_SERVER, SMTP_PORT) <span class="hljs-keyword">as</span> server:
            server.starttls()
            server.login(EMAIL_FROM, EMAIL_PASSWORD)
            server.sendmail(EMAIL_FROM, EMAIL_TO, msg.as_string())
        print(<span class="hljs-string">"Email sent!"</span>)
    <span class="hljs-keyword">except</span> Exception <span class="hljs-keyword">as</span> e:
        print(<span class="hljs-string">"Failed to send email:"</span>, e)

<span class="hljs-comment"># Main loop</span>
<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">"__main__"</span>:
    alert_sent = <span class="hljs-literal">False</span>
    <span class="hljs-keyword">try</span>:
        <span class="hljs-keyword">while</span> <span class="hljs-literal">True</span>:
            humidity, temperature = Adafruit_DHT.read_retry(DHT_SENSOR, DHT_PIN)
            <span class="hljs-keyword">if</span> temperature:
                print(<span class="hljs-string">f"Temp=<span class="hljs-subst">{temperature:<span class="hljs-number">.1</span>f}</span>°C Humidity=<span class="hljs-subst">{humidity:<span class="hljs-number">.1</span>f}</span>%"</span>)
                <span class="hljs-keyword">if</span> temperature &gt;= ALERT_TEMP <span class="hljs-keyword">and</span> <span class="hljs-keyword">not</span> alert_sent:
                    send_email(temperature)
                    alert_sent = <span class="hljs-literal">True</span>
                <span class="hljs-keyword">elif</span> temperature &lt; ALERT_TEMP:
                    alert_sent = <span class="hljs-literal">False</span>
            <span class="hljs-keyword">else</span>:
                print(<span class="hljs-string">"Sensor failure. Check wiring."</span>)
            time.sleep(<span class="hljs-number">10</span>)
    <span class="hljs-keyword">except</span> KeyboardInterrupt:
        print(<span class="hljs-string">"Stopped."</span>)
</code></pre>
<hr />
<h2 id="heading-how-it-works">🧪 How It Works</h2>
<ul>
<li><p>The script checks temperature every 10 seconds.</p>
</li>
<li><p>If the temperature reaches <strong>32°C or above</strong>, an email is sent.</p>
</li>
<li><p>A flag (<code>alert_sent</code>) ensures only one email is sent until the temperature drops below 32 again.</p>
</li>
</ul>
<hr />
]]></content:encoded></item><item><title><![CDATA[Rpi Basics]]></title><description><![CDATA[🐧 Day 2: Linux & Terminal Basics on Raspberry Pi

🎯 Learning Objectives
By the end of today, learners will:

Navigate the Linux filesystem using the terminal.

Use essential Linux commands for managing files and directories.

Install and remove sof...]]></description><link>https://blog.aarav.com.np/rpi-basics</link><guid isPermaLink="true">https://blog.aarav.com.np/rpi-basics</guid><dc:creator><![CDATA[Aarav Poudel]]></dc:creator><pubDate>Thu, 19 Jun 2025 03:02:54 GMT</pubDate><content:encoded><![CDATA[<hr />
<h2 id="heading-day-2-linux-amp-terminal-basics-on-raspberry-pi">🐧 <strong>Day 2: Linux &amp; Terminal Basics on Raspberry Pi</strong></h2>
<hr />
<h3 id="heading-learning-objectives">🎯 <strong>Learning Objectives</strong></h3>
<p>By the end of today, learners will:</p>
<ul>
<li><p>Navigate the Linux filesystem using the terminal.</p>
</li>
<li><p>Use essential Linux commands for managing files and directories.</p>
</li>
<li><p>Install and remove software using <code>apt</code>.</p>
</li>
<li><p>Understand file permissions and user roles.</p>
</li>
<li><p>Enable and use SSH &amp; VNC to remotely access the Raspberry Pi.</p>
</li>
</ul>
<hr />
<p><code>ssh pi1@raspberry1.local</code></p>
<h3 id="heading-topics-amp-content">🧠 <strong>Topics &amp; Content</strong></h3>
<hr />
<h3 id="heading-1-linux-filesystem-structure">🗂️ 1. <strong>Linux Filesystem Structure</strong></h3>
<p>Explain the hierarchy using a tree:</p>
<pre><code class="lang-javascript">/
├── bin        # Essential binary programs
├── boot       # Boot loader files
├── dev        # Device files
├── etc        # System configuration files
├── home       # User home directories
│   └── pi     # Home directory <span class="hljs-keyword">for</span> user <span class="hljs-string">'pi'</span>
├── lib        # System libraries
├── media      # Mounted drives (USB, SD)
├── opt        # Optional application software
├── tmp        # Temporary files
├── usr        # User programs and data
└── <span class="hljs-keyword">var</span>        # Variable data (e.g., logs)
</code></pre>
<blockquote>
<p>✅ Tip: Your working directory is usually <code>/home/pi</code><br />Use <code>pwd</code> to check where you are.</p>
</blockquote>
<hr />
<h3 id="heading-2-basic-linux-commands">💻 2. <strong>Basic Linux Commands</strong></h3>
<p>Practice the following:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Command</td><td>Description</td></tr>
</thead>
<tbody>
<tr>
<td><code>pwd</code></td><td>Print current directory</td></tr>
<tr>
<td><code>ls</code></td><td>List contents</td></tr>
<tr>
<td><code>cd foldername</code></td><td>Change directory</td></tr>
<tr>
<td><code>cd ..</code></td><td>Go to parent directory</td></tr>
<tr>
<td><code>mkdir name</code></td><td>Create new folder</td></tr>
<tr>
<td><code>rm file</code></td><td>Delete file</td></tr>
<tr>
<td><code>rm -r folder</code></td><td>Delete folder recursively</td></tr>
<tr>
<td><code>nano file.txt</code></td><td>Open file in editor</td></tr>
<tr>
<td></td><td></td></tr>
<tr>
<td><code>top</code></td><td>Show system processes</td></tr>
<tr>
<td></td></tr>
</tbody>
</table>
</div><p><strong>Practice Task:</strong></p>
<pre><code class="lang-bash"><span class="hljs-built_in">cd</span> ~
mkdir day2
<span class="hljs-built_in">cd</span> day2
nano hello.txt
</code></pre>
<hr />
<h3 id="heading-3-package-management-with-apt">📦 3. <strong>Package Management with APT</strong></h3>
<p>APT (Advanced Package Tool) is used for installing and managing software.</p>
<ul>
<li><p>Update package list:</p>
<pre><code class="lang-bash">  sudo apt update
</code></pre>
</li>
<li><p>Upgrade installed packages:</p>
<pre><code class="lang-bash">  dsudo apt upgrade -y
</code></pre>
</li>
<li><p>Install a package:</p>
<pre><code class="lang-bash">  sudo apt install cowsay
  cowsay <span class="hljs-string">"Linux is fun!"</span>
</code></pre>
</li>
<li><p>Remove a package:</p>
<pre><code class="lang-bash">  sudo apt remove cowsay
</code></pre>
</li>
</ul>
<blockquote>
<p>🔍 Explore: Try installing <code>neofetch</code>, <code>htop</code>, or <code>python3-pip</code></p>
</blockquote>
<hr />
<h3 id="heading-4-file-permissions-and-users">🔐 4. <strong>File Permissions and Users</strong></h3>
<p>Use <code>ls -l</code> to check permissions:</p>
<pre><code class="lang-bash">-rw-r--r-- 1 pi pi  1234 Jun 14  hello.txt
</code></pre>
<p><strong>Breakdown:</strong></p>
<ul>
<li><p><code>rw-</code> → owner can read/write</p>
</li>
<li><p><code>r--</code> → group can read</p>
</li>
<li><p><code>r--</code> → others can read</p>
</li>
</ul>
<p><strong>Change permissions:</strong></p>
<pre><code class="lang-bash">chmod 755 myscript.sh
</code></pre>
<p><strong>Change ownership:</strong></p>
<pre><code class="lang-bash">sudo chown pi:pi myfile
</code></pre>
<p><strong>User management:</strong></p>
<pre><code class="lang-bash">whoami
sudo adduser student
</code></pre>
<hr />
<h3 id="heading-5-remote-access-ssh-and-vnc">🔗 5. <strong>Remote Access: SSH and VNC</strong></h3>
<ul>
<li><p><strong>SSH</strong> (for terminal access over network)</p>
</li>
<li><p><strong>VNC</strong> (for GUI desktop access)</p>
</li>
</ul>
<h4 id="heading-enable-ssh-amp-vnc">✅ Enable SSH &amp; VNC:</h4>
<pre><code class="lang-bash">sudo raspi-config
<span class="hljs-comment"># Go to "Interface Options" &gt; Enable SSH and VNC</span>
</code></pre>
<p>Alternatively:</p>
<pre><code class="lang-bash">sudo systemctl <span class="hljs-built_in">enable</span> ssh
sudo systemctl start ssh
</code></pre>
<h4 id="heading-install-vnc-viewer-on-pcmac">🖥️ Install VNC Viewer on PC/Mac:</h4>
<ul>
<li><p>Download: <a target="_blank" href="https://www.realvnc.com/en/connect/download/viewer">https://www.realvnc.com/en/connect/download/viewer</a></p>
</li>
<li><p>Enter Raspberry Pi’s IP (e.g., <code>192.168.1.42</code>) and login</p>
</li>
</ul>
<p>To check IP:</p>
<pre><code class="lang-bash">hostname -I
</code></pre>
<hr />
<h3 id="heading-activities">🛠️ <strong>Activities</strong></h3>
<ol>
<li><strong>Create and Navigate Folders</strong></li>
</ol>
<pre><code class="lang-bash">mkdir ~/projects/day2
<span class="hljs-built_in">cd</span> ~/projects/day2
</code></pre>
<ol start="2">
<li><strong>Edit and View Files</strong></li>
</ol>
<pre><code class="lang-bash">nano notes.txt
cat notes.txt
</code></pre>
<ol start="3">
<li><strong>Install Software</strong></li>
</ol>
<pre><code class="lang-bash">sudo apt install figlet
figlet <span class="hljs-string">"Hello Pi"</span>
</code></pre>
<ol start="4">
<li><strong>Enable SSH &amp; VNC and connect from another device</strong></li>
</ol>
<hr />
<h3 id="heading-homework">📋 <strong>Homework</strong></h3>
<ul>
<li><p>Try installing any fun terminal program (<code>cmatrix</code>, <code>sl</code>, etc.)</p>
</li>
<li><p>Create a bash script named <code>myinfo.sh</code> that displays:</p>
<ul>
<li><p>Current user (<code>whoami</code>)</p>
</li>
<li><p>Date/time (<code>date</code>)</p>
</li>
<li><p>IP address (<code>hostname -I</code>)</p>
</li>
</ul>
</li>
</ul>
<hr />
<h3 id="heading-summary">✅ <strong>Summary</strong></h3>
<ul>
<li><p>Terminal is your gateway to full control in Linux.</p>
</li>
<li><p>You can move, create, and edit files efficiently.</p>
</li>
<li><p>With <code>apt</code>, you can install nearly anything.</p>
</li>
<li><p>SSH and VNC let you work remotely from any device.</p>
</li>
</ul>
<h1 id="heading-led-blinking-with-raspberry-pi">LED Blinking with Raspberry Pi</h1>
<p>To make an LED blink on a <strong>Raspberry Pi</strong>, you'll need:</p>
<hr />
<h3 id="heading-hardware-requirements">🧰 <strong>Hardware Requirements</strong></h3>
<ul>
<li><p>Raspberry Pi (any model with GPIO)</p>
</li>
<li><p>1x LED</p>
</li>
<li><p>1x 330Ω resistor</p>
</li>
<li><p>Breadboard and jumper wires</p>
</li>
</ul>
<hr />
<h3 id="heading-wiring">⚙️ <strong>Wiring</strong></h3>
<p>Connect like this:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>LED Pin</td><td>Connects to</td></tr>
</thead>
<tbody>
<tr>
<td>Anode (+)</td><td>GPIO pin (e.g., GPIO 17) via resistor</td></tr>
<tr>
<td>Cathode (–)</td><td>GND on Raspberry Pi</td></tr>
</tbody>
</table>
</div><p>📌 <strong>Example:</strong></p>
<ul>
<li><p><strong>GPIO 17</strong> → Resistor → <strong>LED anode</strong></p>
</li>
<li><p><strong>LED cathode</strong> → <strong>GND</strong></p>
</li>
</ul>
<hr />
<h3 id="heading-python-code-to-blink-led">💻 <strong>Python Code to Blink LED</strong></h3>
<p>You can use the <code>gpiozero</code> or <code>RPi.GPIO</code> library.</p>
<h4 id="heading-using-gpiozero-simpler">✅ Using <code>gpiozero</code> (simpler):</h4>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> gpiozero <span class="hljs-keyword">import</span> LED
<span class="hljs-keyword">from</span> time <span class="hljs-keyword">import</span> sleep

led = LED(<span class="hljs-number">17</span>)  <span class="hljs-comment"># GPIO pin 17</span>

<span class="hljs-keyword">while</span> <span class="hljs-literal">True</span>:
    led.on()
    sleep(<span class="hljs-number">1</span>)
    led.off()
    sleep(<span class="hljs-number">1</span>)
</code></pre>
<h4 id="heading-using-rpigpio">✅ Using <code>RPi.GPIO</code>:</h4>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> RPi.GPIO <span class="hljs-keyword">as</span> GPIO
<span class="hljs-keyword">import</span> time

LED_PIN = <span class="hljs-number">17</span>

GPIO.setmode(GPIO.BCM)
GPIO.setup(LED_PIN, GPIO.OUT)

<span class="hljs-keyword">try</span>:
    <span class="hljs-keyword">while</span> <span class="hljs-literal">True</span>:
        GPIO.output(LED_PIN, GPIO.HIGH)
        time.sleep(<span class="hljs-number">1</span>)
        GPIO.output(LED_PIN, GPIO.LOW)
        time.sleep(<span class="hljs-number">1</span>)
<span class="hljs-keyword">except</span> KeyboardInterrupt:
    GPIO.cleanup()
</code></pre>
<hr />
<h3 id="heading-to-run-the-script">▶️ <strong>To Run the Script</strong></h3>
<ol>
<li><p>Save it as <a target="_blank" href="http://blink.py"><code>blink.py</code></a></p>
</li>
<li><p>Open terminal and run:</p>
</li>
</ol>
<pre><code class="lang-bash">python3 blink.py
</code></pre>
<hr />
<p>Let me know if you want to:</p>
<ul>
<li><p>Control the LED via a <strong>web interface</strong></p>
</li>
<li><p>Blink with <strong>different patterns</strong></p>
</li>
<li><p>Use a <strong>button</strong> to control it</p>
</li>
</ul>
<hr />
<h2 id="heading-ledhtml">LED.html</h2>
<pre><code class="lang-javascript">&lt;!DOCTYPE html&gt;
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">html</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">title</span>&gt;</span>LED Control<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">style</span>&gt;</span><span class="css">
        <span class="hljs-selector-tag">body</span> {
            <span class="hljs-attribute">font-family</span>: Arial, sans-serif;
            <span class="hljs-attribute">text-align</span>: center;
            <span class="hljs-attribute">padding-top</span>: <span class="hljs-number">50px</span>;
        }
        <span class="hljs-selector-tag">button</span> {
            <span class="hljs-attribute">padding</span>: <span class="hljs-number">15px</span> <span class="hljs-number">30px</span>;
            <span class="hljs-attribute">font-size</span>: <span class="hljs-number">18px</span>;
            <span class="hljs-attribute">margin</span>: <span class="hljs-number">10px</span>;
            <span class="hljs-attribute">cursor</span>: pointer;
            <span class="hljs-attribute">border</span>: none;
            <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">8px</span>;
        }
        <span class="hljs-selector-class">.on</span> {
            <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#4CAF50</span>;
            <span class="hljs-attribute">color</span>: white;
        }
        <span class="hljs-selector-class">.off</span> {
            <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#f44336</span>;
            <span class="hljs-attribute">color</span>: white;
        }
    </span><span class="hljs-tag">&lt;/<span class="hljs-name">style</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">h1</span>&gt;</span>LED Control<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Current LED status: <span class="hljs-tag">&lt;<span class="hljs-name">strong</span>&gt;</span>{{ 'ON' if status else 'OFF' }}<span class="hljs-tag">&lt;/<span class="hljs-name">strong</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"/on"</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"on"</span>&gt;</span>Turn ON<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"/off"</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"off"</span>&gt;</span>Turn OFF<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">a</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></span>
</code></pre>
<p>flask_led.py</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">from</span> flask <span class="hljs-keyword">import</span> Flask, render_template
<span class="hljs-keyword">import</span> RPi.GPIO <span class="hljs-keyword">as</span> GPIO

app = Flask(__name__)

# GPIO setup
LED_PIN = <span class="hljs-number">17</span>
GPIO.setmode(GPIO.BCM)
GPIO.setup(LED_PIN, GPIO.OUT)
GPIO.output(LED_PIN, GPIO.LOW)

def is_led_on():
    <span class="hljs-keyword">return</span> GPIO.input(LED_PIN) == GPIO.HIGH

@app.route(<span class="hljs-string">'/'</span>)
def index():
    <span class="hljs-keyword">return</span> render_template(<span class="hljs-string">'led.html'</span>, status=is_led_on())

@app.route(<span class="hljs-string">'/on'</span>)
def turn_on():
    GPIO.output(LED_PIN, GPIO.HIGH)
    <span class="hljs-keyword">return</span> render_template(<span class="hljs-string">'led.html'</span>, status=is_led_on())

@app.route(<span class="hljs-string">'/off'</span>)
def turn_off():
    GPIO.output(LED_PIN, GPIO.LOW)
    <span class="hljs-keyword">return</span> render_template(<span class="hljs-string">'led.html'</span>, status=is_led_on())

@app.route(<span class="hljs-string">'/cleanup'</span>)
def cleanup():
    GPIO.cleanup()
    <span class="hljs-keyword">return</span> <span class="hljs-string">"GPIO Cleaned up!"</span>

<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">"__main__"</span>:
    <span class="hljs-keyword">try</span>:
        app.run(host=<span class="hljs-string">"0.0.0.0"</span>, port=<span class="hljs-number">5000</span>, debug=True)
    <span class="hljs-attr">finally</span>:
        GPIO.cleanup()
</code></pre>
]]></content:encoded></item><item><title><![CDATA[Using MediaFiles in Django]]></title><description><![CDATA[Using media files in Django involves handling user-uploaded content such as images, videos, and other files. Here’s a step-by-step guide to setting up and using media files in a Django project.
Scenario: Handling Media Files in Django
Step 1: Configu...]]></description><link>https://blog.aarav.com.np/using-mediafiles-in-django</link><guid isPermaLink="true">https://blog.aarav.com.np/using-mediafiles-in-django</guid><category><![CDATA[Django]]></category><dc:creator><![CDATA[Aarav Poudel]]></dc:creator><pubDate>Sat, 27 Jul 2024 17:50:31 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1722102575687/326019d9-f0b1-40d6-ad27-762ede5d0f10.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Using media files in Django involves handling user-uploaded content such as images, videos, and other files. Here’s a step-by-step guide to setting up and using media files in a Django project.</p>
<h3 id="heading-scenario-handling-media-files-in-django">Scenario: Handling Media Files in Django</h3>
<h4 id="heading-step-1-configure-settings">Step 1: Configure Settings</h4>
<ol>
<li><p><strong>Open your</strong><a target="_blank" href="http://settings.py"><code>settings.py</code></a> file and add the following lines:</p>
<pre><code class="lang-python"> <span class="hljs-comment"># settings.py</span>
 MEDIA_URL = <span class="hljs-string">'/media/'</span> 
 MEDIA_ROOT = BASE_DIR / <span class="hljs-string">"media"</span>
</code></pre>
</li>
</ol>
<h4 id="heading-step-2-create-media-directory">Step 2: Create Media Directory</h4>
<ol>
<li><p><strong>In your project root, create a</strong><code>media</code> directory:</p>
<pre><code class="lang-bash"> my_project/
 ├── my_app/
 ├── media/ <span class="hljs-comment"># THIS ONE</span>
 ├── static/
 ├── manage.py
 └── settings.py
</code></pre>
</li>
</ol>
<h4 id="heading-step-3-create-a-model-to-handle-media-files">Step 3: Create a Model to Handle Media Files</h4>
<ol>
<li><p><strong>Define a model that includes a</strong><code>FileField</code> or <code>ImageField</code> in <code>my_app/</code><a target="_blank" href="http://models.py"><code>models.py</code></a>:</p>
<pre><code class="lang-python"> <span class="hljs-comment"># my_app/models.py</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">UserProfile</span>(<span class="hljs-params">models.Model</span>):</span>
     username = models.CharField(max_length=<span class="hljs-number">100</span>)
     profile_picture = models.ImageField(upload_to=<span class="hljs-string">'profile_pictures/'</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.username
</code></pre>
</li>
</ol>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">If you try to use ImageField in models , it will show error saying pillow is not installed to solve this simply install pillow library by running following code in terminal</div>
</div>

<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">Here upload to is the path where image will be uploaded in the media folder i.e(media/profile_pictures/uploaded_img.jpg)</div>
</div>

<pre><code class="lang-bash">pip install pillow
</code></pre>
<h4 id="heading-step-4-configure-urls">Step 4: Configure URLs</h4>
<ol>
<li><p><strong>Add a URL pattern to serve media files during development in</strong><code>my_project/</code><a target="_blank" href="http://urls.py"><code>urls.py</code></a>:</p>
<pre><code class="lang-python"> <span class="hljs-comment"># my_project/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-keyword">from</span> django.conf <span class="hljs-keyword">import</span> settings
 <span class="hljs-keyword">from</span> django.conf.urls.static <span class="hljs-keyword">import</span> static 

 urlpatterns = [
     path(<span class="hljs-string">'admin/'</span>, admin.site.urls),
     path(<span class="hljs-string">''</span>, include(<span class="hljs-string">'my_app.urls'</span>)),
 ]

 <span class="hljs-keyword">if</span> settings.DEBUG:
     urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
</code></pre>
</li>
</ol>
<h4 id="heading-step-5-create-a-form-to-upload-media-files">Step 5: Create a Form to Upload Media Files</h4>
<ol>
<li><p><strong>Create a form for uploading media files in</strong><code>my_app/</code><a target="_blank" href="http://forms.py"><code>forms.py</code></a>:</p>
<pre><code class="lang-python"> <span class="hljs-comment"># my_app/forms.py</span>
 <span class="hljs-keyword">from</span> django <span class="hljs-keyword">import</span> forms
 <span class="hljs-keyword">from</span> .models <span class="hljs-keyword">import</span> UserProfile

 <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserProfileForm</span>(<span class="hljs-params">forms.ModelForm</span>):</span>
     <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Meta</span>:</span>
         model = UserProfile
         fields = [<span class="hljs-string">'username'</span>, <span class="hljs-string">'profile_picture'</span>]
</code></pre>
</li>
</ol>
<h4 id="heading-step-6-create-a-view-to-handle-the-form">Step 6: Create a View to Handle the Form</h4>
<ol>
<li><p><strong>Create a view to handle file uploads in</strong><code>my_app/</code><a target="_blank" href="http://views.py"><code>views.py</code></a>:</p>
<pre><code class="lang-python"> <span class="hljs-comment"># my_app/views.py</span>
 <span class="hljs-keyword">from</span> django.shortcuts <span class="hljs-keyword">import</span> render, redirect
 <span class="hljs-keyword">from</span> .forms <span class="hljs-keyword">import</span> UserProfileForm

 <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">upload_profile</span>(<span class="hljs-params">request</span>):</span>
     <span class="hljs-keyword">if</span> request.method == <span class="hljs-string">'POST'</span>:
         form = UserProfileForm(request.POST, request.FILES)
         <span class="hljs-keyword">if</span> form.is_valid():
             form.save()
             <span class="hljs-keyword">return</span> redirect(<span class="hljs-string">'profile_list'</span>)
     <span class="hljs-keyword">else</span>:
         form = UserProfileForm()
     <span class="hljs-keyword">return</span> render(request, <span class="hljs-string">'my_app/upload_profile.html'</span>, {<span class="hljs-string">'form'</span>: form})

 <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">profile_list</span>(<span class="hljs-params">request</span>):</span>
     profiles = UserProfile.objects.all()
     <span class="hljs-keyword">return</span> render(request, <span class="hljs-string">'my_app/profile_list.html'</span>, {<span class="hljs-string">'profiles'</span>: profiles})
</code></pre>
</li>
</ol>
<h4 id="heading-step-7-create-templates">Step 7: Create Templates</h4>
<ol>
<li><p><strong>Create the template for uploading files (</strong><code>my_app/templates/my_app/upload_profile.html</code>):</p>
<pre><code class="lang-html"> <span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
 <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">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>Upload Profile<span class="hljs-tag">&lt;/<span class="hljs-name">title</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">h1</span>&gt;</span>Upload Profile<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
     <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 %}
         {{ form.as_p }}
         <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span>&gt;</span>Upload<span class="hljs-tag">&lt;/<span class="hljs-name">button</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">body</span>&gt;</span>
 <span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
</li>
<li><p><strong>Create the template for displaying the list of profiles (</strong><code>my_app/templates/my_app/profile_list.html</code>):</p>
<pre><code class="lang-html"> <span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
 <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">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>Profile List<span class="hljs-tag">&lt;/<span class="hljs-name">title</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">h1</span>&gt;</span>Profile List<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
     <span class="hljs-tag">&lt;<span class="hljs-name">ul</span>&gt;</span>
         {% for profile in profiles %}
         <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>
             <span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"{{ profile.profile_picture.url }}"</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">"{{ profile.username }}"</span> <span class="hljs-attr">width</span>=<span class="hljs-string">"100"</span>&gt;</span>
             {{ profile.username }}
         <span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
         {% endfor %}
     <span class="hljs-tag">&lt;/<span class="hljs-name">ul</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>
</li>
</ol>
<h4 id="heading-step-8-create-urls-for-the-views">Step 8: Create URLs for the Views</h4>
<ol>
<li><p><strong>Define URLs for the views in</strong><code>my_app/</code><a target="_blank" href="http://urls.py"><code>urls.py</code></a>:</p>
<pre><code class="lang-python"> <span class="hljs-comment"># my_app/urls.py</span>
 <span class="hljs-keyword">from</span> django.urls <span class="hljs-keyword">import</span> path
 <span class="hljs-keyword">from</span> .views <span class="hljs-keyword">import</span> upload_profile, profile_list

 urlpatterns = [
     path(<span class="hljs-string">'upload/'</span>, upload_profile, name=<span class="hljs-string">'upload_profile'</span>),
     path(<span class="hljs-string">''</span>, profile_list, name=<span class="hljs-string">'profile_list'</span>),
 ]
</code></pre>
</li>
</ol>
<h4 id="heading-step-9-run-the-development-server">Step 9: Run the Development Server</h4>
<ol>
<li><p><strong>Run the development server:</strong></p>
<pre><code class="lang-bash"> python manage.py runserver
</code></pre>
</li>
<li><p><strong>Open a web browser and navigate to</strong><a target="_blank" href="http://127.0.0.1:8000/upload/"><code>http://127.0.0.1:8000/upload/</code></a> to upload a profile picture.</p>
</li>
<li><p><strong>Navigate to</strong><a target="_blank" href="http://127.0.0.1:8000/"><code>http://127.0.0.1:8000/</code></a> to see the list of profiles with their uploaded pictures.</p>
</li>
</ol>
<p>This setup allows you to handle media files in your Django project, including uploading files, saving them to the file system, and displaying them on your website.</p>
]]></content:encoded></item><item><title><![CDATA[Handling Static files in Django]]></title><description><![CDATA[Static files in Django refer to files that do not change and are served directly to the user. These files include things like CSS stylesheets, JavaScript files, images, fonts, and other resources that are used to enhance the look and functionality of...]]></description><link>https://blog.aarav.com.np/handling-static-files-in-django</link><guid isPermaLink="true">https://blog.aarav.com.np/handling-static-files-in-django</guid><category><![CDATA[Django]]></category><dc:creator><![CDATA[Aarav Poudel]]></dc:creator><pubDate>Sat, 27 Jul 2024 17:22:59 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1722103445448/311d6355-e63c-4cd0-b634-40b494bddc82.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Static files in Django refer to files that do not change and are served directly to the user. These files include things like CSS stylesheets, JavaScript files, images, fonts, and other resources that are used to enhance the look and functionality of a web application. Unlike media files, which are user-uploaded and can vary, static files are usually the same for all users and are served in their original form.</p>
<h3 id="heading-scenario-building-a-simple-webpage-with-static-files">Scenario: Building a Simple Webpage with Static Files</h3>
<h4 id="heading-link-to-themetemplatehttpsfiletransferiodata-packagejfadazimlink"><a target="_blank" href="https://filetransfer.io/data-package/jFAdaZim#link">Link to theme(template)</a></h4>
<p><a target="_blank" href="https://filetransfer.io/data-package/2J1nga6Z#link">Link to project</a></p>
<p>Step 1: Create a New Django Project and App</p>
<p>Make a folder</p>
<pre><code class="lang-bash">mkdir my_project
</code></pre>
<p>Go to that folder</p>
<pre><code class="lang-bash"><span class="hljs-built_in">cd</span> my_project
</code></pre>
<p>Make virtual environment</p>
<pre><code class="lang-bash">python -m venv envname
</code></pre>
<p>Activate the environment and install django</p>
<p>IN WINDOWS</p>
<pre><code class="lang-bash">.\envname\Scripts\activate
</code></pre>
<p>In Unix/Linux Systems</p>
<pre><code class="lang-bash"><span class="hljs-built_in">source</span> envname/bin/activate
</code></pre>
<p>Install django</p>
<pre><code class="lang-bash">pip install django
</code></pre>
<ol>
<li><p><strong>Create a new Django project:</strong></p>
<pre><code class="lang-bash"> django-admin startproject my_project .
</code></pre>
</li>
<li><p><strong>Create a new app within the project:</strong></p>
<pre><code class="lang-bash"> python manage.py startapp my_app
</code></pre>
</li>
<li><p><strong>Add the new app to</strong><code>INSTALLED_APPS</code> in <a target="_blank" href="http://settings.py"><code>settings.py</code></a>:</p>
<pre><code class="lang-python"> <span class="hljs-comment"># settings.py</span>
 INSTALLED_APPS = [
     ...
     <span class="hljs-string">'my_app'</span>,
 ]
</code></pre>
</li>
</ol>
<h4 id="heading-step-2-create-static-files-directory-and-files">Step 2: Create Static Files Directory and Files</h4>
<ol>
<li><p><strong>Create a</strong><code>static</code> directory in the project root:</p>
<pre><code class="lang-bash"> |-- my_project/
 ├── my_app/
 ├── static/
 │   ├── css/
 │   │   └── style.css
 │   ├── js/
 │   │   └── script.js
 │   └── images/
 │       └── logo.png
 ├── manage.py
 └── db.sqlite3
</code></pre>
</li>
<li><p><strong>Create CSS file (static/css/style.css):</strong></p>
<pre><code class="lang-css"> <span class="hljs-comment">/* static/css/style.css */</span>
 <span class="hljs-selector-tag">body</span> {
     <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#f0f0f0</span>;
     <span class="hljs-attribute">font-family</span>: Arial, sans-serif;
 }

 <span class="hljs-selector-tag">h1</span> {
     <span class="hljs-attribute">color</span>: <span class="hljs-number">#333</span>;
 }
</code></pre>
</li>
<li><p><strong>Create JavaScript file (static/js/script.js):</strong></p>
<pre><code class="lang-javascript"> <span class="hljs-comment">// static/js/script.js</span>
 <span class="hljs-built_in">document</span>.addEventListener(<span class="hljs-string">'DOMContentLoaded'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
     <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"HELLO DJANGO FORM JS"</span>);
 });
</code></pre>
</li>
<li><p><strong>Add an image (static/images/logo.png):</strong></p>
<p> (Add any logo image you have.)</p>
</li>
</ol>
<h4 id="heading-step-3-configure-settings">Step 3: Configure Settings</h4>
<ol>
<li><p><strong>Configure</strong><a target="_blank" href="http://settings.py"><code>settings.py</code></a> for static files:</p>
<pre><code class="lang-python"> <span class="hljs-comment"># settings.py</span>
 STATIC_URL = <span class="hljs-string">'/static/'</span>
 STATICFILES_DIRS = [
     BASE_DIR / <span class="hljs-string">"static"</span>,
 ]
</code></pre>
</li>
<li><p>Configure <code>settings.py</code> for template folder</p>
<pre><code class="lang-bash"> TEMPLATES = [
     {
         <span class="hljs-string">'BACKEND'</span>: <span class="hljs-string">'django.template.backends.django.DjangoTemplates'</span>,
         <span class="hljs-comment">#update here</span>
         <span class="hljs-string">'DIRS'</span>: [BASE_DIR/<span class="hljs-string">"templates"</span>],
         <span class="hljs-string">'APP_DIRS'</span>: True,
         <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>,
             ],
         },
     },
 ]
</code></pre>
</li>
</ol>
<h4 id="heading-ia"> </h4>
<p>Step 4: Create a Template</p>
<ol>
<li><p><strong>Create a template directory in the app:</strong></p>
<pre><code class="lang-bash"> my_project/
 ├── templates/
 │   └── index.html
</code></pre>
</li>
<li><p><strong>Create the HTML template (templates/index.html):</strong></p>
<pre><code class="lang-html"> {% load static %}
 <span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
 <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">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>Static Files Example<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">rel</span>=<span class="hljs-string">"stylesheet"</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text/css"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"{% static 'css/style.css' %}"</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">h1</span>&gt;</span>Hello, Django!<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
     <span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"{% static 'images/logo.png' %}"</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">"Logo"</span>&gt;</span>
     <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text/javascript"</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"{% static 'js/script.js' %}"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</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>
</li>
</ol>
<h4 id="heading-step-5-create-a-view-and-url">Step 5: Create a View and URL</h4>
<ol>
<li><p><strong>Create a view in</strong><code>my_app/</code><a target="_blank" href="http://views.py"><code>views.py</code></a>:</p>
<pre><code class="lang-python"> <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">index</span>(<span class="hljs-params">request</span>):</span>
     <span class="hljs-keyword">return</span> render(request, <span class="hljs-string">'index.html'</span>)
</code></pre>
</li>
<li><p><strong>Create a URL pattern in</strong><code>my_app/</code><a target="_blank" href="http://urls.py"><code>urls.py</code></a>:</p>
<pre><code class="lang-python"> <span class="hljs-keyword">from</span> django.urls <span class="hljs-keyword">import</span> path
 <span class="hljs-keyword">from</span> .views <span class="hljs-keyword">import</span> index

 urlpatterns = [
     path(<span class="hljs-string">''</span>, index, name=<span class="hljs-string">'index'</span>),
 ]
</code></pre>
</li>
<li><p><strong>Include the app's URLs in the project's</strong><a target="_blank" href="http://urls.py"><code>urls.py</code></a>:</p>
<pre><code class="lang-python"> <span class="hljs-comment"># my_project/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

 urlpatterns = [
     path(<span class="hljs-string">'admin/'</span>, admin.site.urls),
     path(<span class="hljs-string">''</span>, include(<span class="hljs-string">'my_app.urls'</span>)),
 ]
</code></pre>
</li>
</ol>
<h4 id="heading-step-6-run-the-development-server">Step 6: Run the Development Server</h4>
<ol>
<li><p><strong>Run the development server:</strong></p>
<pre><code class="lang-bash"> python manage.py runserver
</code></pre>
</li>
<li><p><strong>Open a web browser and navigate to</strong><a target="_blank" href="http://127.0.0.1:8000/"><code>http://127.0.0.1:8000/</code></a>.</p>
</li>
</ol>
<p>You should see a styled page with an Console message saying "Hello, Django from JS" and an image displayed. The CSS file is applied for styling, the JavaScript file for the alert, and the image file is displayed from the static directory.</p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">Open Inspect and Console to see JS output message</div>
</div>]]></content:encoded></item><item><title><![CDATA[Django Models]]></title><description><![CDATA[Making a Django App
python manage.py startapp app_name

Regularly used Django model fields:

CharField: Used for storing short to medium-length strings.

TextField: Suitable for storing longer text content.

IntegerField: Stores integer values, commo...]]></description><link>https://blog.aarav.com.np/django-models</link><guid isPermaLink="true">https://blog.aarav.com.np/django-models</guid><category><![CDATA[Django]]></category><category><![CDATA[#DjangoBasics #PythonWebDevelopment #WebFramework #MVCArchitecture #WebAppDevelopment #DjangoProject #DjangoApp #DjangoDevelopmentServer #PythonProgramming #OpenSourceWebFramework #WebDev #TechArticles]]></category><dc:creator><![CDATA[Aarav Poudel]]></dc:creator><pubDate>Thu, 25 Jul 2024 17:54:27 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1711902835568/19c4d7ac-9153-41d8-beb1-23b2b26f9d4a.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-making-a-django-app">Making a Django App</h2>
<pre><code class="lang-bash">python manage.py startapp app_name
</code></pre>
<h3 id="heading-regularly-used-django-model-fields">Regularly used Django model fields:</h3>
<ol>
<li><p><code>CharField</code>: Used for storing short to medium-length strings.</p>
</li>
<li><p><code>TextField</code>: Suitable for storing longer text content.</p>
</li>
<li><p><code>IntegerField</code>: Stores integer values, commonly used for numeric data.</p>
</li>
<li><p><code>FloatField</code>: Similar to IntegerField but for floating-point numbers.</p>
</li>
<li><p><code>BooleanField</code>: Represents a true/false field.</p>
</li>
<li><p><code>DateField</code>: Used for storing dates.</p>
</li>
<li><p><code>TimeField</code>: Stores time information.</p>
</li>
<li><p><code>DateTimeField</code>: Combines date and time in a single field.</p>
</li>
<li><p><code>EmailField</code>: Specifically designed for storing email addresses.</p>
</li>
<li><p><code>ImageField</code>: Used to store image files.</p>
</li>
<li><p><code>FileField</code>: General-purpose file field.</p>
</li>
<li><p><code>ForeignKey</code>: Establishes a many-to-one relationship between two models.</p>
</li>
<li><p><code>ManyToManyField</code>: Represents a many-to-many relationship.</p>
</li>
<li><p><code>DecimalField</code>: Used for storing decimal numbers with fixed precision.</p>
</li>
<li><p><code>URLField</code>: Stores URLs.</p>
</li>
</ol>
<p>These are just some of the commonly used fields in Django models. Each field type is designed for specific data types and use cases in your application.</p>
<h3 id="heading-person-model-example">Person Model Example</h3>
<pre><code class="lang-python"><span class="hljs-comment"># models.py</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">255</span>)
    address = models.CharField(max_length=<span class="hljs-number">255</span>)
    blood_group = models.CharField(max_length=<span class="hljs-number">5</span>)
    age = models.IntegerField()
    gender = models.CharField(max_length=<span class="hljs-number">10</span>)
    phone = models.CharField(max_length=<span class="hljs-number">15</span>)
    email = models.EmailField()
</code></pre>
<ol>
<li><p><strong>Making Migrations</strong>:</p>
<p> Django's <code>makemigrations</code> command analyzes your models and creates migration files that represent the changes you've made. Run the following command in your terminal:</p>
<pre><code class="lang-bash"> python manage.py makemigrations
</code></pre>
<p> If your app is called <code>myapp</code>, you can specify it as follows:</p>
<pre><code class="lang-bash"> python manage.py makemigrations myapp
</code></pre>
<p> This command will create migration files based on the changes detected in your models. These migration files are stored in the <code>migrations</code> directory within your app.</p>
</li>
<li><p><strong>Reviewing Migration Files</strong>:</p>
<p> After running <code>makemigrations</code>, you can review the generated migration files in the <code>migrations</code> directory. These files contain Python code that Django will use to apply changes to your database schema.</p>
</li>
<li><p><strong>Applying Migrations</strong>:</p>
<p> Once you're satisfied with the migration files, you can apply them to your database using the <code>migrate</code> command:</p>
<pre><code class="lang-bash"> python manage.py migrate
</code></pre>
<p> If your app is called <code>myapp</code>, you can specify it as follows:</p>
<pre><code class="lang-bash"> python manage.py migrate myapp
</code></pre>
<p> This command executes the migration files and updates your database schema accordingly.</p>
</li>
<li><p><strong>Verifying Changes</strong>:</p>
<p> After migrating, you can verify that the changes have been applied by accessing your database management tool (e.g., phpMyAdmin, pgAdmin) or by using Django's admin interface to view the <code>Person</code> model.</p>
<p> While using SQlite database , we can view the database using <strong>SQLiteViewer</strong> Extension in VsCode</p>
</li>
</ol>
<h3 id="heading-registering-to-django-admin">Registering to Django admin</h3>
<p>Registering a model to Django's admin interface allows you to manage that model's data through a web-based UI provided by Django. To register the <code>Person</code> model from your example to the Django admin, you need to follow these steps:</p>
<p><strong>Create a Superuser</strong>:</p>
<p>Before accessing the admin interface, make sure you have a superuser account. If you haven't created one yet, run the following command and follow the prompts:</p>
<pre><code class="lang-bash">python manage.py createsuperuser
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1711901416297/27e04a44-2d02-432d-b7be-8f6889d71d71.png" alt class="image--center mx-auto" /></p>
<blockquote>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">you wont see passwords while typing</div>
</div>

</blockquote>
<ol>
<li><p><strong>Register the Model in</strong><a target="_blank" href="http://admin.py"><code>admin.py</code></a>:</p>
<p> In your app's <a target="_blank" href="http://admin.py"><code>admin.py</code></a> file, you need to import the model and then register it with the admin site. If you haven't already created an <a target="_blank" href="http://admin.py"><code>admin.py</code></a> file in your app, create one. Then, register your model as follows:</p>
<pre><code class="lang-python"> <span class="hljs-comment"># 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> Person

 admin.site.register(Person)
</code></pre>
<p> This code imports the <code>Person</code> model and registers it with the admin site.</p>
</li>
<li><p><strong>Accessing the Admin Interface</strong>:</p>
<p> Start your Django development server if it's not already running:</p>
<pre><code class="lang-bash"> python manage.py runserver
</code></pre>
<p> Then, open your web browser and navigate to <a target="_blank" href="http://localhost:8000/admin"><code>http://localhost:8000/admin</code></a> (replace <a target="_blank" href="http://localhost:8000"><code>localhost:8000</code></a> with your server address if it's different). Log in using the superuser credentials you created earlier.</p>
</li>
<li><p><strong>Manage</strong><code>Person</code><strong>Objects</strong>:</p>
<p> Once logged in, you should see the Django admin interface. You'll find the <code>Person</code> model listed there. Click on it to access the <code>Person</code> objects. You can add, edit, or delete <code>Person</code> objects through this interface.</p>
</li>
</ol>
<p>That's it! You've now registered the <code>Person</code> model to Django's admin interface, allowing you to manage <code>Person</code> objects conveniently through a web-based UI. You can repeat these steps to register other models as needed.</p>
<p><strong>Some examples of Django models that you can create for practice:</strong></p>
<ol>
<li><p><strong>Blog Post Model</strong>:</p>
<pre><code class="lang-python"> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Post</span>(<span class="hljs-params">models.Model</span>):</span>
     title = models.CharField(max_length=<span class="hljs-number">100</span>)
     content = models.TextField()
     author = models.ForeignKey(User, on_delete=models.CASCADE)
     created_at = models.DateTimeField(auto_now_add=<span class="hljs-literal">True</span>)
     updated_at = models.DateTimeField(auto_now=<span class="hljs-literal">True</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.title
</code></pre>
</li>
<li><p><strong>Product Model for an E-commerce Site</strong>:</p>
<pre><code class="lang-python"> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Product</span>(<span class="hljs-params">models.Model</span>):</span>
     name = models.CharField(max_length=<span class="hljs-number">255</span>)
     description = models.TextField()
     price = models.DecimalField(max_digits=<span class="hljs-number">10</span>, decimal_places=<span class="hljs-number">2</span>)
     quantity = models.IntegerField()
     category = models.ForeignKey(<span class="hljs-string">'Category'</span>, on_delete=models.CASCADE)

     <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
</code></pre>
<p> Here <code>Category</code> is another Model and <code>Product</code> has ManytoOne(ForeignKey) relation to <code>Category</code></p>
<pre><code class="lang-python"> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Category</span>(<span class="hljs-params">models.Model</span>):</span>
     name = models.CharField(max_length=<span class="hljs-number">255</span>)
     description = models.TextField()

     <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
</code></pre>
</li>
<li><p><strong>Customer Model for CRM</strong>:</p>
<pre><code class="lang-python"> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Customer</span>(<span class="hljs-params">models.Model</span>):</span>
     name = models.CharField(max_length=<span class="hljs-number">255</span>)
     email = models.EmailField()
     phone = models.CharField(max_length=<span class="hljs-number">15</span>)
     address = models.TextField()
     company = models.CharField(max_length=<span class="hljs-number">255</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
</code></pre>
</li>
<li><p><strong>Todo List Item Model</strong>:</p>
<pre><code class="lang-python"> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">TodoItem</span>(<span class="hljs-params">models.Model</span>):</span>
     title = models.CharField(max_length=<span class="hljs-number">255</span>)
     description = models.TextField(blank=<span class="hljs-literal">True</span>)
     completed = models.BooleanField(default=<span class="hljs-literal">False</span>)
     due_date = models.DateField(null=<span class="hljs-literal">True</span>, blank=<span class="hljs-literal">True</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.title
</code></pre>
</li>
<li><p><strong>Event Model for Calendar Application</strong>:</p>
<pre><code class="lang-python"> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Event</span>(<span class="hljs-params">models.Model</span>):</span>
     title = models.CharField(max_length=<span class="hljs-number">255</span>)
     description = models.TextField(blank=<span class="hljs-literal">True</span>)
     location = models.CharField(max_length=<span class="hljs-number">255</span>)
     start_time = models.DateTimeField()
     end_time = models.DateTimeField()

     <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.title
</code></pre>
</li>
</ol>
<p>These are just a few examples to get started. Depending on the requirements of your application, you can create various models to represent different types of data and relationships between them.</p>
<h2 id="heading-orm-queries">ORM Queries</h2>
<p>In Django, the ORM (Object-Relational Mapping) allows you to interact with your database using Python code instead of raw SQL queries. Given the model example with a <code>Person</code> class in the Django app, let's explore some common ORM queries.</p>
<h3 id="heading-1-query-all-persons">1. <strong>Query all persons:</strong></h3>
<pre><code class="lang-python">all_persons = Person.objects.all()
</code></pre>
<h3 id="heading-2-query-a-specific-person-by-primary-key">2. <strong>Query a specific person by primary key:</strong></h3>
<pre><code class="lang-python">person = Person.objects.get(pk=<span class="hljs-number">1</span>)
</code></pre>
<h3 id="heading-3-filter-persons-based-on-conditions">3. <strong>Filter persons based on conditions:</strong></h3>
<pre><code class="lang-python"><span class="hljs-comment"># Persons older than 25</span>
persons_over_25 = Person.objects.filter(age__gt=<span class="hljs-number">25</span>)

<span class="hljs-comment"># Persons with a specific blood group</span>
persons_with_blood_group = Person.objects.filter(blood_group=<span class="hljs-string">'A+'</span>)
</code></pre>
<h3 id="heading-4-ordering-persons">4. <strong>Ordering persons:</strong></h3>
<pre><code class="lang-python"><span class="hljs-comment"># Order persons by age in descending order</span>
ordered_persons = Person.objects.order_by(<span class="hljs-string">'-age'</span>)
</code></pre>
<h3 id="heading-5-counting-records">5. <strong>Counting records:</strong></h3>
<pre><code class="lang-python"><span class="hljs-comment"># Count all persons</span>
total_persons = Person.objects.count()
</code></pre>
<h3 id="heading-6-updating-records">6. <strong>Updating records:</strong></h3>
<pre><code class="lang-python"><span class="hljs-comment"># Update a person's phone number</span>
person = Person.objects.get(pk=<span class="hljs-number">1</span>)
person.phone = <span class="hljs-string">'1234567890'</span>
person.save()
</code></pre>
<h3 id="heading-7-deleting-records">7. <strong>Deleting records:</strong></h3>
<pre><code class="lang-python"><span class="hljs-comment"># Delete a person by primary key</span>
Person.objects.filter(pk=<span class="hljs-number">1</span>).delete()
</code></pre>
<p>Certainly! Let's explore some additional Django ORM queries and concepts with the <code>Person</code> model:</p>
<h3 id="heading-8-creating-new-records">8. <strong>Creating new records:</strong></h3>
<pre><code class="lang-python"><span class="hljs-comment"># Create a new person</span>
new_person = Person.objects.create(
    name=<span class="hljs-string">'John Doe'</span>,
    blood_group=<span class="hljs-string">'O+'</span>,
    age=<span class="hljs-number">30</span>,
    gender=<span class="hljs-string">'Male'</span>,
    phone=<span class="hljs-string">'9876543210'</span>,
    email=<span class="hljs-string">'john.doe@example.com'</span>
)
</code></pre>
<h3 id="heading-9-chaining-queries">9. <strong>Chaining queries:</strong></h3>
<pre><code class="lang-python"><span class="hljs-comment"># Chain multiple queries</span>
filtered_persons = Person.objects.filter(age__gt=<span class="hljs-number">25</span>).exclude(gender=<span class="hljs-string">'Female'</span>)
</code></pre>
<h3 id="heading-10-using-or-conditions">10. <strong>Using OR conditions:</strong></h3>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> django.db.models <span class="hljs-keyword">import</span> Q

<span class="hljs-comment"># Persons older than 25 OR with blood group 'AB+'</span>
persons_with_condition = Person.objects.filter(Q(age__gt=<span class="hljs-number">25</span>) | Q(blood_group=<span class="hljs-string">'AB+'</span>))
</code></pre>
<h3 id="heading-11-aggregation-functions">11. <strong>Aggregation functions:</strong></h3>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> django.db.models <span class="hljs-keyword">import</span> Avg, Sum, Max, Min

<span class="hljs-comment"># Calculate average age</span>
average_age = Person.objects.aggregate(Avg(<span class="hljs-string">'age'</span>))

<span class="hljs-comment"># Sum of ages</span>
total_age = Person.objects.aggregate(Sum(<span class="hljs-string">'age'</span>))

<span class="hljs-comment"># Maximum age</span>
oldest_person = Person.objects.aggregate(Max(<span class="hljs-string">'age'</span>))

<span class="hljs-comment"># Minimum age</span>
youngest_person = Person.objects.aggregate(Min(<span class="hljs-string">'age'</span>))
</code></pre>
<h3 id="heading-12-related-models-and-queries">12. <strong>Related models and queries:</strong></h3>
<pre><code class="lang-python"><span class="hljs-comment"># Assuming you have another model related to Person</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Address</span>(<span class="hljs-params">models.Model</span>):</span>
    person = models.OneToOneField(Person, on_delete=models.CASCADE)
    street = models.CharField(max_length=<span class="hljs-number">255</span>)
    city = models.CharField(max_length=<span class="hljs-number">100</span>)

<span class="hljs-comment"># Query persons with their associated addresses</span>
persons_with_addresses = Person.objects.select_related(<span class="hljs-string">'address'</span>)
</code></pre>
<h3 id="heading-13-filtering-with-date-fields">13. <strong>Filtering with date fields:</strong></h3>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> datetime <span class="hljs-keyword">import</span> date

<span class="hljs-comment"># Persons born after a specific date</span>
persons_born_after = Person.objects.filter(birthdate__gt=date(<span class="hljs-number">1990</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>))
</code></pre>
<p>These examples demonstrate the versatility of Django ORM, providing powerful tools for interacting with databases. Always refer to the <a target="_blank" href="https://docs.djangoproject.com/en/stable/topics/db/models/">Django documentation on models and queries</a> for more in-depth information and options.</p>
<p>These are just a few examples of the many queries you can perform using Django ORM. Django's ORM simplifies database interactions by providing a high-level, Pythonic interface for working with databases, making it more readable and maintainable than raw SQL queries.</p>
]]></content:encoded></item></channel></rss>