<?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[Django Master]]></title><description><![CDATA[Django Master]]></description><link>https://blog.django-tutorial.dev</link><generator>RSS for Node</generator><lastBuildDate>Mon, 11 May 2026 14:15:29 GMT</lastBuildDate><atom:link href="https://blog.django-tutorial.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Bridging the Gap: Integrating Arduino with Django for IoT Applications]]></title><description><![CDATA[Introduction
The Internet of Things (IoT) is revolutionizing how we interact with the physical world, enabling everyday objects to connect and communicate through the internet. Combining Arduino, a popular microcontroller platform, with Django, a rob...]]></description><link>https://blog.django-tutorial.dev/django-adruino</link><guid isPermaLink="true">https://blog.django-tutorial.dev/django-adruino</guid><category><![CDATA[django master]]></category><category><![CDATA[Django]]></category><category><![CDATA[django rest framework]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[arduino]]></category><category><![CDATA[Python]]></category><category><![CDATA[Multiply and surrender]]></category><dc:creator><![CDATA[Nischal lamichhane]]></dc:creator><pubDate>Sun, 30 Jun 2024 12:34:14 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1719730126005/d7740f96-49bc-499e-b013-3f39d7942af0.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>The Internet of Things (IoT) is revolutionizing how we interact with the physical world, enabling everyday objects to connect and communicate through the internet. Combining Arduino, a popular microcontroller platform, with Django, a robust Python web framework, opens up exciting possibilities for IoT projects. This blog post will guide you through the process of integrating Arduino with Django, allowing you to control and monitor your Arduino projects via a web interface.</p>
<h2 id="heading-why-combine-arduino-with-django">Why Combine Arduino with Django?</h2>
<ul>
<li><p><strong>Remote Control and Monitoring</strong>: Control your Arduino projects from anywhere in the world using a web browser.</p>
</li>
<li><p><strong>Data Logging and Visualization</strong>: Store and visualize sensor data collected by your Arduino in a Django-powered web app.</p>
</li>
<li><p><strong>Enhanced Interactivity</strong>: Create interactive web interfaces to make your projects more user-friendly.</p>
</li>
</ul>
<h2 id="heading-getting-started">Getting Started ...</h2>
<p><a target="_blank" href="https://medium.com/@djangomaster/bridging-the-gap-integrating-arduino-with-django-for-iot-applications-da247c34d034">READ HERE at medium</a></p>
]]></content:encoded></item><item><title><![CDATA[Handling Multiple Databases in Django]]></title><description><![CDATA[In the world of web development, managing data efficiently is paramount. Django, a high-level Python web framework, offers robust support for handling databases. However, as applications grow in complexity, the need to work with multiple databases ma...]]></description><link>https://blog.django-tutorial.dev/multiple-databases-in-django</link><guid isPermaLink="true">https://blog.django-tutorial.dev/multiple-databases-in-django</guid><category><![CDATA[multiple database]]></category><category><![CDATA[django master]]></category><category><![CDATA[Databases]]></category><category><![CDATA[sharding]]></category><category><![CDATA[sharding techniques]]></category><category><![CDATA[Django]]></category><category><![CDATA[django rest framework]]></category><category><![CDATA[django orm]]></category><category><![CDATA[Multiply and surrender]]></category><category><![CDATA[DjangoRestFramework]]></category><category><![CDATA[PostgreSQL]]></category><category><![CDATA[Redis]]></category><category><![CDATA[CouchDB]]></category><category><![CDATA[Oracle]]></category><category><![CDATA[MongoDB]]></category><dc:creator><![CDATA[Nischal lamichhane]]></dc:creator><pubDate>Tue, 30 Apr 2024 13:45:07 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1714483570506/b1b95abb-5666-4c76-81b3-f3c0219c9b03.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In the world of web development, managing data efficiently is paramount. Django, a high-level Python web framework, offers robust support for handling databases. However, as applications grow in complexity, the need to work with multiple databases may arise. Whether it's for sharding data, separating read and write operations, or integrating with legacy systems, Django provides powerful tools to tackle this challenge.</p>
<p>Head to the official documentation for multiple databases support <a target="_blank" href="https://docs.djangoproject.com/en/5.0/topics/db/multi-db/">here</a> .</p>
<p>Learn Python &amp; Django at <a target="_blank" href="https://django-tutorial.dev">django-tutorial.dev</a></p>
<h3 id="heading-understanding-multiple-databases-in-django"><strong>Understanding Multiple Databases in Django</strong></h3>
<p>Django's default behavior is to work with a single database. However, it also provides built-in support for managing multiple databases seamlessly. Each database connection is represented by a Django <code>DATABASES</code> setting in the project's settings file. These settings define various parameters such as the database engine, name, user, password, host, and port.</p>
<h3 id="heading-configuring-multiple-databases"><strong>Configuring Multiple Databases</strong></h3>
<p>To configure multiple databases in Django, start by defining each database in the <code>DATABASES</code> setting. For example:</p>
<pre><code class="lang-python"> DATABASES = {
    <span class="hljs-string">'default'</span>: {
        <span class="hljs-string">'ENGINE'</span>: <span class="hljs-string">'django.db.backends.mysql'</span>,
        <span class="hljs-string">'NAME'</span>: <span class="hljs-string">'my_database'</span>,
        <span class="hljs-string">'USER'</span>: <span class="hljs-string">'my_user'</span>,
        <span class="hljs-string">'PASSWORD'</span>: <span class="hljs-string">'my_password'</span>,
        <span class="hljs-string">'HOST'</span>: <span class="hljs-string">'localhost'</span>,
        <span class="hljs-string">'PORT'</span>: <span class="hljs-string">'3306'</span>,
    },
    <span class="hljs-string">'other_db'</span>: {
        <span class="hljs-string">'ENGINE'</span>: <span class="hljs-string">'django.db.backends.sqlite3'</span>,
        <span class="hljs-string">'NAME'</span>: BASE_DIR / <span class="hljs-string">'other_db.sqlite3'</span>,
    },
}
</code></pre>
<p>In this example, there are two database configurations: <code>'default'</code> and <code>'other_db'</code>. The <code>'default'</code> database is MySQL, while <code>'other_db'</code> uses SQLite. You can add as many database configurations as needed.</p>
<h3 id="heading-migrating-in-individual-databases"><strong>Migrating in individual databases</strong></h3>
<p>The <code>migrate</code> management command operates on one database at a time. By default, it operates on the <code>default</code> database, but by providing the <code>--database</code> option, you can tell it to synchronize a different database. So, to synchronize all models onto all databases in the first example above, you would need to call:</p>
<pre><code class="lang-python">py manage.py migrate
py manage.py migrate --database=default
</code></pre>
<p>If you don’t want every application to be synchronized onto a particular database, you can define a database router that implements a policy constraining the availability of particular models.</p>
<p>If, as in the second example above, you’ve left the <code>default</code> database empty, you must provide a database name each time you run <code>migrate</code>. Omitting the database name would raise an error. For the second example:</p>
<pre><code class="lang-python">py manage.py migrate --database=defaults
py manage.py migrate --database=other_db
</code></pre>
<h3 id="heading-using-other-management-commands"><strong>Using other management commands</strong></h3>
<p>Most other <code>django-admin</code> commands that interact with the database operate in the same way as <code>migrate</code> – they only ever operate on one database at a time, using<br /><code>--database</code> to control the database used.</p>
<p>An exception to this rule is the <code>makemigrations</code> command. It validates the migration history in the databases to catch problems with the existing migration files (which could be caused by editing them) before creating new migrations. By default, it checks only the <code>default</code> database, but it consults the <code>allow_migrate()</code> method of routers if any are installed.</p>
<h3 id="heading-database-routing"><strong>Database Routing</strong></h3>
<p>Once the databases are configured, Django needs to know which database to use for each query. This is where database routing comes into play. Django allows you to define custom database routers to control which database to use for specific models or operations.</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyAppRouter</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">db_for_read</span>(<span class="hljs-params">self, model, **hints</span>):</span>
        <span class="hljs-keyword">if</span> model._meta.app_label == <span class="hljs-string">'my_app'</span>:
            <span class="hljs-keyword">return</span> <span class="hljs-string">'other_db'</span>
        <span class="hljs-keyword">return</span> <span class="hljs-literal">None</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">db_for_write</span>(<span class="hljs-params">self, model, **hints</span>):</span>
        <span class="hljs-keyword">if</span> model._meta.app_label == <span class="hljs-string">'my_app'</span>:
            <span class="hljs-keyword">return</span> <span class="hljs-string">'other_db'</span>
        <span class="hljs-keyword">return</span> <span class="hljs-literal">None</span>
</code></pre>
<p><a target="_blank" href="https://docs.djangoproject.com/en/5.0/ref/django-admin/#django-admin-makemigrations">In</a> this example, <code>MyAppRouter</code> routes read and write operations for models in the <code>'my_app'</code> app to the <code>'other_db'</code> database.</p>
<h2 id="heading-database-routers">Database Routers</h2>
<p>A database Router is a class that provides up to four methods:</p>
<h3 id="heading-dbforreadmodel-hints">db_for_read(model, **hints)</h3>
<p>Suggest the database that should be used for read operations for objects of type model. If a database operation is able to provide any additional information that might assist in selecting a database, it will be provided in the hints dictionary. Details on valid hints are provided below.<br />Returns None if there is no suggestion.</p>
<h3 id="heading-dbforwritemodel-hints">db_for_write(model, **hints)</h3>
<p>Suggest the database that should be used for writes of objects of type Model. If a database operation is able to provide any additional information that might assist in selecting a database, it will be provided in the hints dictionary. Details on valid hints are provided below.<br />Returns None if there is no suggestion.</p>
<h3 id="heading-allowrelationobj1-obj2-hints">allow_relation(obj1, obj2, **hints)</h3>
<p>Return True if a relation between obj1 and obj2 should be allowed, False if the relation should be prevented, or None if the router has no opinion. This is purely a validation operation, used by foreign key and many to many operations to determine if a relation should be allowed between two objects.<br />If no router has an opinion (i.e. all routers return None), only relations within the same database are allowed.</p>
<h3 id="heading-allowmigratedb-applabel-modelnamenone-hints">allow_migrate(db, app_label, model_name=None, **hints)</h3>
<p>Determine if the migration operation is allowed to run on the database with alias db. Return True if the operation should run, False if it shouldn’t run, or None if the router has no opinion. The app_label positional argument is the label of the application being migrated.</p>
<p>A router doesn’t have to provide all these methods – it may omit one or more of them. If one of the methods is omitted, Django will skip that router when performing the relevant check.</p>
<h2 id="heading-hints">Hints</h2>
<p>The hints received by the database router can be used to decide which database should receive a given request.</p>
<p>At present, the only hint that will be provided is instance, an object instance that is related to the read or write operation that is underway. This might be the instance that is being saved, or it might be an instance that is being added in a many-to-many relation. In some cases, no instance hint will be provided at all. The router checks for the existence of an instance hint, and determine if that hint should be used to alter routing behavior.</p>
<h3 id="heading-using-multiple-databases-in-views-and-models"><strong>Using Multiple Databases in Views and Models</strong></h3>
<p>Once routing is configured, you can use multiple databases in your views and models. For example, to read from or write to a specific database, you can use Django's <code>using</code> method:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> my_app.models <span class="hljs-keyword">import</span> MyModel

<span class="hljs-comment"># Read from 'other_db'</span>
objs = MyModel.objects.using(<span class="hljs-string">'other_db'</span>).all()

<span class="hljs-comment"># Write to 'other_db'</span>
obj = MyModel(field1=value1, field2=value2)
obj.save(using=<span class="hljs-string">'other_db'</span>)
</code></pre>
<h3 id="heading-considerations-and-best-practices"><strong>Considerations and Best Practices</strong></h3>
<p>When working with multiple databases in Django, there are several considerations and best practices to keep in mind:</p>
<ol>
<li><p><strong>Consistency</strong>: Ensure data consistency across databases by carefully designing your database schema and transaction management.</p>
</li>
<li><p><strong>Performance</strong>: Monitor and optimize database performance, especially when dealing with multiple databases.</p>
</li>
<li><p><strong>Security</strong>: Secure database connections and credentials to prevent unauthorized access.</p>
</li>
<li><p><strong>Testing</strong>: Test your application thoroughly, especially when using multiple databases, to ensure correct behavior in various scenarios.</p>
</li>
<li><p><strong>Documentation</strong>: Document your database configurations, routing logic, and any customizations for future reference.</p>
</li>
</ol>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Handling multiple databases in Django opens up a world of possibilities for building scalable and efficient web applications. By understanding how to configure multiple databases, implement database routing, and use them in views and models, you can take full advantage of Django's powerful features while effectively managing your data.</p>
]]></content:encoded></item><item><title><![CDATA[The Great Showdown: HTML vs. Django]]></title><description><![CDATA[Welcome, dear readers, to the ultimate showdown between two titans of the web development world: HTML and Django. In one corner, we have HTML, the veteran markup language that's been shaping the web since the dawn of the internet. In the other corner...]]></description><link>https://blog.django-tutorial.dev/html-vs-django</link><guid isPermaLink="true">https://blog.django-tutorial.dev/html-vs-django</guid><category><![CDATA[html vs django]]></category><category><![CDATA[Django]]></category><category><![CDATA[django master]]></category><category><![CDATA[Multiply and surrender]]></category><category><![CDATA[Python]]></category><category><![CDATA[General Programming]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[HTML5]]></category><category><![CDATA[HTML]]></category><category><![CDATA[HTML CSS JAVASCRIPT]]></category><category><![CDATA[django rest framework]]></category><dc:creator><![CDATA[Nischal lamichhane]]></dc:creator><pubDate>Sun, 21 Apr 2024 12:43:08 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1713702450440/ca5ea139-c438-4d73-b003-ff2278f3e9ad.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Welcome, dear readers, to the ultimate showdown between two titans of the web development world: HTML and Django. In one corner, we have HTML, the veteran markup language that's been shaping the web since the dawn of the internet. In the other corner, we have Django, the powerful Python framework that's been revolutionizing web development with its magic touch. Let the battle begin!</p>
<p>(DON'T FORGET TO PULL THIS UP WHEN MEETING A HTML DEVELOPER)</p>
<p>Learn Python &amp; Django at <a target="_blank" href="https://django-tutorial.dev">django-tutorial.dev</a></p>
<h2 id="heading-differencepy">Difference.py :</h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Metrics</td><td>HTML</td><td>Django</td></tr>
</thead>
<tbody>
<tr>
<td><strong>Syntax Complexity</strong></td><td>Relatively simple syntax consisting of tags and attributes.</td><td>More complex syntax due to its Python-based templating language and MVC (Model-View-Controller) architecture.</td></tr>
<tr>
<td><strong>Flexibility</strong></td><td>Not Flexible</td><td>Very Flexible</td></tr>
<tr>
<td><strong>Development Speed</strong></td><td>Quick for static webpage creation but requires manual updating for dynamic content.</td><td>Rapid development for dynamic web applications with its built-in features like ORM (Object-Relational Mapping) and admin interface.</td></tr>
<tr>
<td><strong>Scalability</strong></td><td>Limited scalability for complex web applications without additional backend frameworks.</td><td>Highly scalable with support for handling large volumes of traffic and extensive customization options.</td></tr>
<tr>
<td><strong>Extendibility</strong></td><td>No concept of packages</td><td>Yes</td></tr>
<tr>
<td><strong>Code Reusability</strong></td><td>Limited reusability, as each webpage must be manually coded.</td><td>High code reusability through template inheritance, reusable components, and modular app structure.</td></tr>
<tr>
<td><strong>Security</strong></td><td>No built-in security features; vulnerabilities must be addressed manually.</td><td>Built-in security features such as CSRF (Cross-Site Request Forgery) protection, SQL injection prevention, and authentication system.</td></tr>
<tr>
<td><strong>Learning Curve:</strong></td><td>Low learning curve suitable for beginners; primarily focuses on markup structure</td><td>Moderate to steep learning curve due to its comprehensive framework features and Python-based syntax.</td></tr>
<tr>
<td><strong>Community Support</strong></td><td>Extensive community support with abundant resources, tutorials, and forums.</td><td>Active community with a wealth of documentation, libraries, and third-party packages to enhance development.</td></tr>
<tr>
<td><strong>Maintenance Effort</strong></td><td>Minimal maintenance effort for static web pages but requires manual updates for dynamic content.</td><td>Continuous maintenance required for updates, security patches, and optimization, but automated admin interface streamlines content management.</td></tr>
<tr>
<td><strong>Project Complexity</strong></td><td>Suited for simple static websites or basic web pages.</td><td>Ideal for complex web applications with advanced functionalities such as user authentication, database integration, and dynamic content generation.</td></tr>
<tr>
<td><strong>Hackability</strong></td><td>Can HACK NASA !!!</td><td><strong>CAN HACK HTML!!!!!!</strong></td></tr>
<tr>
<td><strong>Generation</strong></td><td>Cannot generate Django code</td><td>Can generate HTML using Templating engine</td></tr>
<tr>
<td><strong>Average Users</strong></td><td>below the table</td><td>below the table</td></tr>
<tr>
<td><strong>Capabilities</strong></td><td>Can give contents to a web page</td><td>Can give contents, styling, logic, intractability and dynamic content to a webpage</td></tr>
<tr>
<td><strong>Chad</strong></td><td>No</td><td>Yes</td></tr>
<tr>
<td><strong>Yappers</strong></td><td>Yes</td><td>No</td></tr>
<tr>
<td><strong>Server Side Scripting</strong></td><td>No</td><td>Very YES</td></tr>
</tbody>
</table>
</div><p>Average HTML Fan:</p>
<p><img src="https://media.tenor.com/WL5XmrkUVJcAAAAM/averagefan.gif" alt="Average Fan Fan Vs Enjoyer GIF - Average Fan Fan Vs Enjoyer Average Fan Vs  Average Enjoyer - Discover &amp; Share GIFs" class="image--center mx-auto" /></p>
<p>Average Django Enjoyer:</p>
<p><img src="https://media1.tenor.com/m/jHvyFefhKmcAAAAC/mujikcboro-seriymujik.gif" alt="Chad GIFs | Tenor" class="image--center mx-auto" /></p>
<h3 id="heading-conclusion">Conclusion:</h3>
<p>Sponsor this Blog to fund the Django side in this war between HTML and Django.<br />Mail me to update the blog with new metrics and stuff.</p>
]]></content:encoded></item><item><title><![CDATA[A Guide to Handling CORS in Django API Security]]></title><description><![CDATA[In today's interconnected web environment, building secure APIs is paramount for safeguarding data and ensuring smooth communication between servers and clients. Cross-Origin Resource Sharing (CORS) is a crucial aspect of API security, particularly i...]]></description><link>https://blog.django-tutorial.dev/cors-policy</link><guid isPermaLink="true">https://blog.django-tutorial.dev/cors-policy</guid><category><![CDATA[cors policy]]></category><category><![CDATA[django cors]]></category><category><![CDATA[django master]]></category><category><![CDATA[Django]]></category><category><![CDATA[django rest framework]]></category><category><![CDATA[DjangoRestFramework]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[General Programming]]></category><category><![CDATA[Multiply and surrender]]></category><category><![CDATA[django-cors-headers]]></category><dc:creator><![CDATA[Nischal lamichhane]]></dc:creator><pubDate>Fri, 12 Apr 2024 07:22:57 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1712906373178/0948527e-c1ac-468c-b6f0-ffd77fa78ce1.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In today's interconnected web environment, building secure APIs is paramount for safeguarding data and ensuring smooth communication between servers and clients. Cross-Origin Resource Sharing (CORS) is a crucial aspect of API security, particularly in Django applications, where improper CORS configuration can lead to vulnerabilities. In this blog post, we'll delve into understanding CORS, its importance in Django API security, and practical strategies to handle it effectively.</p>
<p>Learn Python &amp; Django at <a target="_blank" href="https://django-tutorial.dev">django-tutorial.dev</a></p>
<h3 id="heading-understanding-cors"><strong>Understanding CORS:</strong></h3>
<p>CORS is a security feature implemented by web browsers that restricts cross-origin HTTP requests initiated from scripts running on a web page. It is designed to prevent malicious websites from accessing resources on a different origin, thus mitigating various types of attacks such as Cross-Site Scripting (XSS) and Cross-Site Request Forgery (CSRF).</p>
<p>In Django, CORS is managed through middleware, which intercepts incoming HTTP requests and enforces CORS policies based on specified configurations.</p>
<h3 id="heading-importance-of-cors-in-django-api-security"><strong>Importance of CORS in Django API Security:</strong></h3>
<p>Django, being a powerful web framework for building APIs, needs to enforce strict CORS policies to prevent unauthorized access and protect sensitive data. Without proper CORS handling, your API could be vulnerable to attacks like unauthorized data retrieval or manipulation, potentially compromising the integrity and confidentiality of your application.</p>
<h3 id="heading-practical-strategies-to-handle-cors-in-django"><strong>Practical Strategies to Handle CORS in Django:</strong></h3>
<ol>
<li><p><strong>Install Django CORS Middleware:</strong> Start by installing the <code>django-cors-headers</code> package using pip:</p>
<pre><code class="lang-python"> pip install django-cors-headers
</code></pre>
</li>
<li><p><strong>Configure CORS Settings:</strong> Update your Django project's settings to include CORS middleware and specify allowed origins, methods, and headers. Here's an example configuration:</p>
<pre><code class="lang-python"> <span class="hljs-comment"># settings.py</span>

 INSTALLED_APPS = [
     ...
     <span class="hljs-string">'corsheaders'</span>,
     ...
 ]

 MIDDLEWARE = [
     ...
     <span class="hljs-string">'corsheaders.middleware.CorsMiddleware'</span>,
     ...
 ]

 CORS_ALLOWED_ORIGINS = [
     <span class="hljs-string">'http://localhost:3000'</span>,  <span class="hljs-comment"># Example: Allow requests from this origin</span>
 ]

 CORS_ALLOW_METHODS = [
     <span class="hljs-string">'GET'</span>,
     <span class="hljs-string">'POST'</span>,
     <span class="hljs-string">'PUT'</span>,
     <span class="hljs-string">'PATCH'</span>,
     <span class="hljs-string">'DELETE'</span>,
     <span class="hljs-string">'OPTIONS'</span>,
 ]

 CORS_ALLOW_HEADERS = [
     <span class="hljs-string">'Accept'</span>,
     <span class="hljs-string">'Content-Type'</span>,
     <span class="hljs-string">'Authorization'</span>,
 ]
</code></pre>
</li>
<li><p><strong>Handle Preflight Requests:</strong> Preflight requests are OPTIONS requests sent by the browser to determine if the actual request is safe to send. Ensure your Django application responds appropriately to these requests by allowing them to pass through without authentication or authorization checks.</p>
</li>
<li><p><strong>Test and Debug:</strong> Thoroughly test your API endpoints with different client applications and verify that CORS policies are correctly enforced. Use browser developer tools to inspect HTTP headers and responses, ensuring that CORS headers are present and accurately reflect your configured settings.</p>
</li>
<li><p><strong>Implement Additional Security Measures:</strong> While CORS is essential for securing your Django API, it's just one piece of the puzzle. Implement other security measures such as authentication, authorization, input validation, and rate limiting to fortify your application against a wide range of attacks.</p>
</li>
</ol>
<h3 id="heading-conclusion"><strong>Conclusion:</strong></h3>
<p>Handling CORS in Django API security requires careful configuration and adherence to best practices to protect against potential vulnerabilities. By understanding the fundamentals of CORS, configuring middleware, and implementing robust security measures, you can ensure that your Django applications remain resilient and secure in today's dynamic web landscape. Remember to stay informed about emerging threats and updates in web security to continuously improve the security posture of your Django APIs.</p>
]]></content:encoded></item><item><title><![CDATA[Django Signals: Surface Overview]]></title><description><![CDATA[In the dynamic world of web development, Django stands out as a powerful framework for crafting robust and scalable web applications. Among its many features, Django Signals emerge as a hidden gem, offering developers a mechanism to decouple various ...]]></description><link>https://blog.django-tutorial.dev/django-signals</link><guid isPermaLink="true">https://blog.django-tutorial.dev/django-signals</guid><category><![CDATA[Django]]></category><category><![CDATA[DjangoRestFramework]]></category><category><![CDATA[django rest framework]]></category><category><![CDATA[djangosignals]]></category><category><![CDATA[django master]]></category><category><![CDATA[Multiply and surrender]]></category><category><![CDATA[General Programming]]></category><category><![CDATA[Python]]></category><category><![CDATA[django signals]]></category><category><![CDATA[signals]]></category><dc:creator><![CDATA[Nischal lamichhane]]></dc:creator><pubDate>Tue, 02 Apr 2024 07:18:04 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1712041421327/65495a37-385a-488d-b551-03101a5fb7d8.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In the dynamic world of web development, Django stands out as a powerful framework for crafting robust and scalable web applications. Among its many features, Django Signals emerge as a hidden gem, offering developers a mechanism to decouple various components of their applications and enhance interactivity. In this blog post, we'll delve into the realm of Django Signals, exploring what they are, how they work, and how you can leverage them to streamline your Django projects.</p>
<p>Learn Python &amp; Django at <a target="_blank" href="https://django-tutorial.dev">django-tutorial.dev</a></p>
<h3 id="heading-understanding-django-signals"><strong>Understanding Django Signals</strong></h3>
<p>At its core, Django Signals provide a means for components within a Django application to communicate with each other in a decoupled manner. Inspired by the Observer design pattern, signals enable certain senders to notify a set of receivers when a particular action or event occurs.</p>
<h3 id="heading-anatomy-of-django-signals"><strong>Anatomy of Django Signals</strong></h3>
<p>Django Signals rely on the <code>signal</code> module, which allows developers to define custom signals and connect them to specific functions or methods. Let's break down the key components:</p>
<ol>
<li><p><strong>Signal Definition:</strong> Developers can define custom signals using the <code>django.dispatch.Signal</code> class. These signals serve as a communication mechanism, signaling when a particular event occurs. There are several Built-in signals in Django. Read about them <a target="_blank" href="https://blog.nischallamichhane.com.np/django-signals-built-in-signals">here</a>.</p>
</li>
<li><p><strong>Signal Sender:</strong> When a specific action or event occurs within the application, the sender triggers the corresponding signal by calling the <code>send()</code> method. The sender can include additional data as arguments when sending the signal.</p>
</li>
<li><p><strong>Signal Receiver:</strong> Receivers are functions or methods that are registered to respond to a particular signal. Developers can connect multiple receivers to a signal, enabling modular and extensible application behavior.</p>
</li>
</ol>
<h3 id="heading-practical-applications-of-django-signals"><strong>Practical Applications of Django Signals</strong></h3>
<p>Now that we understand the basics, let's explore some real-world scenarios where Django Signals can be invaluable:</p>
<ol>
<li><p><strong>Pre-Save and Post-Save Hooks:</strong> Utilize signals such as <code>pre_save</code> and <code>post_save</code> to perform actions before or after saving an object to the database. For example, you can automatically update related records, send notifications, or trigger additional processes based on changes to certain models.</p>
</li>
<li><p><strong>User Authentication and Authorization:</strong> Implement custom signals to integrate with Django's authentication system. For instance, you can execute custom logic when a user is created, updated, or deleted, enhancing security and access control within your application.</p>
</li>
<li><p><strong>Cache Invalidation:</strong> Maintain data consistency by employing signals to invalidate cache entries when relevant data is modified. This ensures that cached data remains synchronized with the underlying database, preventing stale or outdated information from being served to users.</p>
</li>
</ol>
<h3 id="heading-best-practices-and-considerations"><strong>Best Practices and Considerations</strong></h3>
<p>While Django Signals offer immense flexibility and functionality, it's essential to adhere to best practices to avoid common pitfalls:</p>
<ul>
<li><p><strong>Keep Signals Simple:</strong> Resist the temptation to overcomplicate your signal handling logic. Aim for simplicity and clarity to maintain code readability and ease of maintenance.</p>
</li>
<li><p><strong>Avoid Tight Coupling:</strong> Strive to keep your application components loosely coupled by utilizing signals judiciously. Over-reliance on signals can lead to spaghetti code and make your application harder to understand and maintain.</p>
</li>
<li><p><strong>Unit Testing:</strong> Test your signal handlers thoroughly to ensure they behave as expected under various scenarios. Mocking signals and receivers can facilitate isolated testing of individual components.</p>
</li>
</ul>
<h3 id="heading-real-world-application-simplified-communication"><strong>Real World Application : Simplified Communication</strong></h3>
<p>Django Signals enable components within an application to interact without tight coupling. Key components include signal definition, sender, and receiver.</p>
<ul>
<li><p><strong>Signal Definition:</strong> Custom signals are defined using <code>django.dispatch.Signal</code>, serving as communication channels for specific events.</p>
</li>
<li><p><strong>Signal Sender:</strong> Sends signals using the <code>send()</code> method when relevant events occur, including optional data arguments.</p>
</li>
<li><p><strong>Signal Receiver:</strong> Functions or methods connected to signals respond to specific events, allowing modular and extensible behavior.</p>
</li>
</ul>
<h3 id="heading-demo-app-notifications-with-django-signals"><strong>Demo App: Notifications with Django Signals</strong></h3>
<p>Let's create a demo app illustrating Django Signals in action. We'll build a simple notification system where users receive a welcome message upon registration.</p>
<ol>
<li><p><strong>Signal Definition:</strong> Define a custom signal <code>user_registered</code>.</p>
</li>
<li><p><strong>Signal Sender:</strong> Trigger <code>user_registered</code> signal upon user registration, sending user data as arguments.</p>
</li>
<li><p><strong>Signal Receiver:</strong> Connect a receiver to <code>user_registered</code> signal to send a welcome message to the user.</p>
</li>
</ol>
<h3 id="heading-code-demo"><strong>Code Demo:</strong></h3>
<pre><code class="lang-python"><span class="hljs-comment"># signals.py</span>
<span class="hljs-keyword">from</span> django.dispatch <span class="hljs-keyword">import</span> Signal

user_registered = Signal(providing_args=[<span class="hljs-string">"user"</span>])
</code></pre>
<pre><code class="lang-python"><span class="hljs-comment"># receivers.py</span>
<span class="hljs-keyword">from</span> django.dispatch <span class="hljs-keyword">import</span> receiver
<span class="hljs-keyword">from</span> .signals <span class="hljs-keyword">import</span> user_registered

<span class="hljs-meta">@receiver(user_registered)</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">send_welcome_message</span>(<span class="hljs-params">sender, **kwargs</span>):</span>
    user = kwargs[<span class="hljs-string">'user'</span>]
    <span class="hljs-comment"># Send welcome message logic here</span>
    send_user_mail(user.email,user.username,message = <span class="hljs-string">"Welcome to Silk Road"</span>)
</code></pre>
<p>send_user_mail will be a explicitly defined function that sends mail to the user with an activation link, welcome message or anything in between. Read About how to send mail from your django app <a target="_blank" href="https://blog.nischallamichhane.com.np/django-emails">here</a>:</p>
<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-keyword">from</span> .signals <span class="hljs-keyword">import</span> user_registered

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span>(<span class="hljs-params">models.Model</span>):</span>
    username = models.CharField(max_length=<span class="hljs-number">100</span>)
    email = models.EmailField()

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">create_user_profile</span>(<span class="hljs-params">sender, instance, created, **kwargs</span>):</span>
    <span class="hljs-keyword">if</span> created:
        user_registered.send(sender=User, user=instance)

models.signals.post_save.connect(create_user_profile, sender=User)
</code></pre>
<h3 id="heading-conclusion"><strong>Conclusion</strong></h3>
<p>Django Signals offer a concise and powerful mechanism for inter-component communication in Django applications. By understanding and harnessing their potential, developers can enhance modularity, extensibility, and maintainability. Explore Django Signals further to streamline your application's communication and unlock new possibilities. Happy coding!</p>
]]></content:encoded></item><item><title><![CDATA[Django Signals : Built-in signals]]></title><description><![CDATA[Django comes equipped with a powerful feature known as signals. Signals provide a way to allow various parts of your application to communicate asynchronously, enabling modular and extensible behavior. In this blog post, we'll take a closer look at s...]]></description><link>https://blog.django-tutorial.dev/django-signals-built-in-signals</link><guid isPermaLink="true">https://blog.django-tutorial.dev/django-signals-built-in-signals</guid><category><![CDATA[django signals]]></category><category><![CDATA[Django]]></category><category><![CDATA[djangosignals]]></category><category><![CDATA[django master]]></category><category><![CDATA[General Programming]]></category><category><![CDATA[Multiply and surrender]]></category><category><![CDATA[django rest framework]]></category><dc:creator><![CDATA[Nischal lamichhane]]></dc:creator><pubDate>Tue, 02 Apr 2024 06:43:09 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1712040586523/606bf8ac-a9e0-436e-8062-e59c934abb96.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Django comes equipped with a powerful feature known as signals. Signals provide a way to allow various parts of your application to communicate asynchronously, enabling modular and extensible behavior. In this blog post, we'll take a closer look at some of the built-in signals Django offers, along with their usage and significance.</p>
<p>Learn Python &amp; Django at <a target="_blank" href="https://django-tutorial.dev">django-tutorial.dev</a></p>
<p><strong>1. Model Signals:</strong> One of the most frequently used types of signals in Django is related to models. These signals are emitted by the Django ORM before or after certain model-related operations. For instance, the <code>pre_save</code> and <code>post_save</code> signals are sent before and after saving a model instance, respectively. Similarly, signals like <code>pre_delete</code> and <code>post_delete</code> are dispatched before and after deleting a model instance.</p>
<p>By connecting receiver functions to these signals, developers can perform additional tasks or execute custom logic when specific model-related events occur. For example, you might want to update related records in the database after a certain model instance is saved, or trigger notifications when a model instance is deleted.</p>
<ul>
<li><p><code>pre_save</code>: Sent just before a model's <code>save()</code> method is called.</p>
</li>
<li><p><code>post_save</code>: Sent just after a model's <code>save()</code> method is called.</p>
</li>
<li><p><code>pre_delete</code>: Sent just before a model's <code>delete()</code> method is called.</p>
</li>
<li><p><code>post_delete</code>: Sent just after a model's <code>delete()</code> method is called.</p>
</li>
<li><p><code>m2m_changed</code>: Sent when a many-to-many relation is modified.</p>
</li>
</ul>
<p><strong>2. Authentication Signals:</strong> Django's authentication system also emits signals during user authentication-related events. Signals such as <code>user_logged_in</code> and <code>user_logged_out</code> are sent when users successfully log in or log out of the system. These signals are invaluable for implementing additional functionality, such as recording login/logout timestamps, updating user activity logs, or sending email notifications upon user login.</p>
<ul>
<li><p><code>user_logged_in</code>: Sent when a user logs in.</p>
</li>
<li><p><code>user_logged_out</code>: Sent when a user logs out.</p>
</li>
<li><p><code>user_login_failed</code>: Sent when a login attempt fails.</p>
</li>
</ul>
<p><strong>3. Request/Response Signals:</strong> Django provides signals that allow you to hook into the request/response cycle of your web application. Signals like <code>request_started</code> and <code>request_finished</code> are dispatched when HTTP requests begin and end processing, respectively. These signals can be useful for tasks such as logging request metadata, capturing performance metrics, or implementing custom request/response middleware.</p>
<ul>
<li><p><code>request_started</code>: Sent when an HTTP request begins processing.</p>
</li>
<li><p><code>request_finished</code>: Sent when an HTTP request finishes processing.</p>
</li>
<li><p><code>got_request_exception</code>: Sent when an exception occurs while processing an HTTP request.</p>
</li>
</ul>
<p><strong>4. Management Signals:</strong> Additionally, Django emits signals during the execution of management commands, which are used for administrative tasks like database migrations, collecting static files, and running tests. Signals such as <code>pre_migrate</code> and <code>post_migrate</code> are sent before and after database migrations are applied, allowing developers to perform setup or cleanup tasks as needed.</p>
<ul>
<li><p><code>pre_migrate</code>: Sent before a migration is applied.</p>
</li>
<li><p><code>post_migrate</code>: Sent after a migration is applied.</p>
</li>
<li><p><code>setting_changed</code>: Sent when a Django setting is changed.</p>
</li>
</ul>
<p><strong>5. Other Signals:</strong> These are miscellaneous Signals that dont fit on above 4 categories, There is no further difference between them.</p>
<ul>
<li><p><code>class_prepared</code>: Sent when a model class has been prepared.</p>
</li>
<li><p><code>template_rendered</code>: Sent when a template is rendered.</p>
</li>
<li><p><code>setting_changed</code>: Sent when a Django setting is changed.</p>
</li>
<li><p><code>connection_created</code>: Sent when a database connection is created.</p>
</li>
</ul>
<h2 id="heading-conclusion">Conclusion:</h2>
<p>In conclusion, built-in signals in Django provide a flexible and powerful mechanism for extending and customizing the behavior of your web applications. By leveraging signals, developers can decouple different parts of their codebase, promote reusability, and maintain clean, modular architecture. Whether you're working with models, authentication, request handling, or management commands, Django's signals offer a robust toolkit for implementing advanced functionality and responding to various events within your application.</p>
]]></content:encoded></item><item><title><![CDATA[Integrate HTMX with Django: Replacing ReactJS]]></title><description><![CDATA[Introduction:
In the dynamic landscape of web development, staying abreast of the latest technologies is crucial. One such powerful combination is the integration of HTMX with Django, a blend that leverages modern websockets for enhanced real-time fu...]]></description><link>https://blog.django-tutorial.dev/django-htmx</link><guid isPermaLink="true">https://blog.django-tutorial.dev/django-htmx</guid><category><![CDATA[django-htmx]]></category><category><![CDATA[Django]]></category><category><![CDATA[django master]]></category><category><![CDATA[Multiply and surrender]]></category><category><![CDATA[htmx]]></category><category><![CDATA[General Programming]]></category><category><![CDATA[Python]]></category><category><![CDATA[general programming]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[backend web development]]></category><category><![CDATA[react js]]></category><category><![CDATA[React]]></category><category><![CDATA[Reactive Programming]]></category><dc:creator><![CDATA[Nischal lamichhane]]></dc:creator><pubDate>Tue, 27 Feb 2024 14:06:17 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1709042602754/77cb4804-014a-4e51-a259-35fe31becac1.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction:</h2>
<p>In the dynamic landscape of web development, staying abreast of the latest technologies is crucial. One such powerful combination is the integration of HTMX with Django, a blend that leverages modern websockets for enhanced real-time functionality. In this article, we'll delve into the world of HTMX and how it seamlessly integrates with Django to bring a new level of interactivity to your web applications.</p>
<p>Learn Python , HTMX &amp; Django at <a target="_blank" href="https://django-tutorial.dev">django-tutorial.dev</a></p>
<h2 id="heading-understanding-htmx">Understanding HTMX:</h2>
<p>HTMX, pronounced "hypertext marks," is a lightweight JavaScript library that facilitates seamless communication between the server and the client. Unlike traditional approaches, HTMX enables developers to update specific parts of a web page dynamically, without the need for a full-page reload. It achieves this by using AJAX requests, making it a powerful tool for creating responsive and interactive user interfaces.</p>
<p>Key Features of HTMX: Before we explore the integration of HTMX with Django, let's highlight some key features that make HTMX a valuable addition to your toolkit:</p>
<ol>
<li><p><strong>Declarative Syntax:</strong> HTMX employs a declarative syntax, allowing developers to define dynamic behavior directly in the HTML markup using data attributes. This simplifies the code and enhances readability, promoting a more intuitive development process.</p>
</li>
<li><p><strong>AJAX Requests Simplified:</strong> By abstracting away the complexities of AJAX requests, HTMX streamlines the process of fetching and updating data from the server. This leads to cleaner code and a more efficient development workflow.</p>
</li>
<li><p><strong>Compatibility with Django:</strong> HTMX aligns seamlessly with Django, making it an excellent choice for developers working within the Django ecosystem. Its compatibility extends to various Python frameworks, ensuring flexibility and ease of integration.</p>
</li>
</ol>
<h1 id="heading-integrating-htmx-with-django">Integrating HTMX with Django:</h1>
<p>Now, let's explore the steps to integrate HTMX with Django, specifically focusing on leveraging modern web sockets for real-time communication.</p>
<ol>
<li><p><strong>Installing HTMX:</strong> Begin by installing HTMX in your Django project. You can use package managers like pip to install the necessary dependencies. Ensure that HTMX is included in your project's static files. You can also use CDN for HTMX like this:</p>
<pre><code class="lang-haml"> &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/htmx/1.9.10/htmx.min.js" &gt;&lt;/script&gt;
</code></pre>
</li>
<li><p><strong>Adding HTMX to Templates:</strong> Integrate HTMX into your Django templates by including the necessary script tags. HTMX utilizes data attributes to define behavior, so make sure to annotate the HTML elements that you want to enhance with dynamic functionality.</p>
</li>
<li><p><strong>Setting Up Django Views:</strong> Update your Django views to handle the HTMX requests. This involves defining view functions that respond to specific HTMX-triggered actions. Use Django's robust capabilities to process data and return the appropriate response.</p>
</li>
<li><p><strong>Incorporating Websockets:</strong> To harness the power of modern websockets, consider integrating Django Channels into your project. Django Channels extends Django to handle WebSockets, enabling bidirectional communication between the server and the client.</p>
</li>
<li><p><strong>Real-Time Updates:</strong> With HTMX and Django Channels in place, you can achieve real-time updates on your web pages. For example, implement a chat application where messages are sent and received in real-time, providing a seamless and interactive user experience.</p>
</li>
</ol>
<p>Benefits of the Integration: The integration of HTMX with Django, coupled with modern Servers, offers several benefits to developers and end-users alike:</p>
<ol>
<li><p><strong>Enhanced User Experience:</strong> Real-time updates create a more engaging and interactive user experience. Whether it's live notifications or dynamic content updates, users will appreciate the responsiveness of the application.</p>
</li>
<li><p><strong>Reduced Server Load:</strong> By updating only the necessary parts of a page, HTMX reduces the server load compared to traditional full-page reloads. This optimization leads to a more efficient use of server resources.</p>
</li>
<li><p><strong>Simplified Development:</strong> The declarative syntax of HTMX and the compatibility with Django streamline the development process. Developers can focus on building features without getting bogged down by complex AJAX implementations.</p>
</li>
<li><p><strong>Scalability:</strong> Modern websockets, facilitated by Django Channels, pave the way for scalable and real-time applications. Whether you're building a collaborative editing tool or a live dashboard, the integration sets the stage for future scalability.</p>
</li>
</ol>
<p>Here is a code snippet that demonstrates a simple implementation of HTMX with Django and real-time updates without using websockets. For the sake of brevity, we'll create a basic example of a real-time counter.</p>
<pre><code class="lang-typescript">&lt;!-- Django Template <span class="hljs-keyword">with</span> HTMX Integration --&gt;
&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;meta http-equiv=<span class="hljs-string">"X-UA-Compatible"</span> content=<span class="hljs-string">"IE=edge"</span>&gt;
    &lt;meta name=<span class="hljs-string">"viewport"</span> content=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span>&gt;
    &lt;title&gt;HTMX and Django Real-Time Counter&lt;/title&gt;
    &lt;!-- Include HTMX library --&gt;
    &lt;script src=<span class="hljs-string">"{% static 'htmx.min.js' %}"</span> defer&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;

&lt;!-- Counter Display --&gt;
&lt;h1 id=<span class="hljs-string">"counter"</span> hx-get=<span class="hljs-string">"{% url 'get_counter' %}"</span>&gt;{% block counter %}{% endblock %}&lt;/h1&gt;

&lt;!-- Button to Increment Counter --&gt;
&lt;button hx-post=<span class="hljs-string">"{% url 'increment_counter' %}"</span> hx-target=<span class="hljs-string">"#counter"</span> hx-swap=<span class="hljs-string">"outerHTML"</span>&gt;
    Increment Counter
&lt;/button&gt;

&lt;/body&gt;
&lt;/html&gt;
</code></pre>
<p>In this Django template, we have a simple layout with a heading displaying the current counter value and a button to increment the counter. Notice the usage of HTMX attributes like <code>hx-get</code>, <code>hx-post</code>, <code>hx-target</code>, and <code>hx-swap</code> for handling AJAX requests.</p>
<p>Now, let's create the Django views and URLs to handle these HTMX requests and manage the counter:</p>
<pre><code class="lang-python"><span class="hljs-comment"># Django Views</span>
<span class="hljs-keyword">from</span> django.shortcuts <span class="hljs-keyword">import</span> render
<span class="hljs-keyword">from</span> django.http <span class="hljs-keyword">import</span> JsonResponse

counter_value = <span class="hljs-number">0</span>  <span class="hljs-comment"># Initial counter value</span>

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_counter</span>(<span class="hljs-params">request</span>):</span>
    <span class="hljs-comment"># View to retrieve the current counter value</span>
    <span class="hljs-keyword">return</span> JsonResponse({<span class="hljs-string">'counter'</span>: counter_value})

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">increment_counter</span>(<span class="hljs-params">request</span>):</span>
    <span class="hljs-comment"># View to increment the counter and return the updated value</span>
    <span class="hljs-keyword">global</span> counter_value
    counter_value += <span class="hljs-number">1</span>
    <span class="hljs-keyword">return</span> JsonResponse({<span class="hljs-string">'counter'</span>: counter_value})
</code></pre>
<p>And the corresponding Django URLs:</p>
<pre><code class="lang-python"><span class="hljs-comment"># Django URLs (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> get_counter, increment_counter

urlpatterns = [
    path(<span class="hljs-string">'get_counter/'</span>, get_counter, name=<span class="hljs-string">'get_counter'</span>),
    path(<span class="hljs-string">'increment_counter/'</span>, increment_counter, name=<span class="hljs-string">'increment_counter'</span>),
    <span class="hljs-comment"># Add other URLs as needed</span>
]
</code></pre>
<p>Make sure to include these URLs in your main <a target="_blank" href="http://urls.py"><code>urls.py</code></a> file.</p>
<h2 id="heading-polling-with-django-and-htmx">Polling with Django and HTMX:</h2>
<p><strong>Polling</strong> is when a client requests a particular piece of data at regular intervals (maybe every x seconds) and the server reverts with a usual response with the required data. This can be useful on an collaborative/team application, where a user's action needs to be reflected on other's screen. Below is an example:</p>
<p><img src="https://cdn.shortpixel.ai/client/q_lossy,ret_img,w_943/https://www.bocasay.com/wp-content/uploads/2020/07/kanban-board.png" alt="All you Need to Know about Kanban Method" /></p>
<p>Let's say we need to Implement a Kanban board in some sort of Development software. In a kanban board, anyone involved in the development should be able to transfer a to-do from one column to another. But having it accurately reflect on other developer's screen is hard. we can either have the user manually reload the page to see any changes or start setting up a websocket &amp; debugging inevitable bugs in the websocket. Here HTMX is the best solution. We will do Poll the state of kanban board in regular intervals (2s).</p>
<pre><code class="lang-typescript">&lt;div <span class="hljs-keyword">class</span>=<span class="hljs-string">"htmx-poller"</span> 
    hx-target=<span class="hljs-string">"#board"</span> 
    hx-swap=<span class="hljs-string">"innerHTML"</span> 
    hx-get=<span class="hljs-string">"{% url 'get_board' board.id %}"</span>
    hx-trigger=<span class="hljs-string">"every 2s"</span>&gt; &lt;/div&gt;

&lt;div id = <span class="hljs-string">"board"</span> &gt; &lt;/div&gt;
</code></pre>
<p>In above code snippet. we are getting the the board from the server every 2s and replacing the response with whatever was inside the board div.</p>
<p>hx-target --&gt; the element that is targetted for swapping with the response<br />hx-get --&gt; sends a get req to the 'get_board' url<br />hx-swap --&gt; specified what to do with pre existing html inside of the target element<br />hx-trigger --&gt; specifies when the request should be sent</p>
<p>For our purpose. our web server's code should look like this:</p>
<pre><code class="lang-python"><span class="hljs-comment">#urls.py </span>
<span class="hljs-keyword">from</span> django <span class="hljs-keyword">import</span> path 
<span class="hljs-keyword">from</span> views <span class="hljs-keyword">import</span> get_board

urlpatterns = [
    path(<span class="hljs-string">'board/&lt;int:id&gt;'</span>,get_board,name=<span class="hljs-string">'get_board'</span>),
]
</code></pre>
<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">get_board</span>(<span class="hljs-params">request,id</span>):</span>
    <span class="hljs-comment">#</span>
    <span class="hljs-comment">#</span>
    <span class="hljs-keyword">return</span> render(request,<span class="hljs-string">'path_to_board_component.html'</span>,context)
</code></pre>
<p>When we return render our board component, it will go to our hx-target which happens to be #board in our case and it will replace previously existing board</p>
<h2 id="heading-conclusion">Conclusion:</h2>
<p>Reject React.JS embrace HTMX</p>
]]></content:encoded></item><item><title><![CDATA[Database Relationships in Django]]></title><description><![CDATA[Introduction:
Django, a high-level Python web framework, empowers developers to build robust and scalable web applications efficiently. One of the key aspects that make Django powerful is its support for database relationships. In this article, we wi...]]></description><link>https://blog.django-tutorial.dev/database-relationships-in-django</link><guid isPermaLink="true">https://blog.django-tutorial.dev/database-relationships-in-django</guid><category><![CDATA[django database]]></category><category><![CDATA[django master]]></category><category><![CDATA[Multiply and surrender]]></category><category><![CDATA[Django]]></category><category><![CDATA[django rest framework]]></category><category><![CDATA[django orm]]></category><category><![CDATA[General Programming]]></category><category><![CDATA[Python]]></category><dc:creator><![CDATA[Nischal lamichhane]]></dc:creator><pubDate>Fri, 16 Feb 2024 10:45:15 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1708072804817/8d703d05-8765-4863-ae24-cc2b82c14d64.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Introduction:</p>
<p>Django, a high-level Python web framework, empowers developers to build robust and scalable web applications efficiently. One of the key aspects that make Django powerful is its support for database relationships. In this article, we will delve into the intricacies of database relationships in Django, exploring how they work and how they can be leveraged to design sophisticated and well-organized applications.<br />Learn Python &amp; Django at <a target="_blank" href="https://django-tutorial.dev">django-tutorial.dev</a></p>
<p>Understanding Models:</p>
<p>At the core of Django's database functionality are models. Models define the structure of your data, essentially acting as a blueprint for how information will be stored in the database. Django provides a range of field types to define different types of data, such as CharField for characters, IntegerField for integers, and DateTimeField for date and time information.</p>
<p>Creating Models:</p>
<p>To establish a database relationship in Django, it's crucial to create models that accurately represent the entities in your application. For instance, if you are developing a blog application, you might have models for 'Author,' 'Post,' and 'Comment.' By establishing relationships between these models, you can organize and connect your data effectively.</p>
<p>Types of Database Relationships:</p>
<p>Django supports three main types of database relationships: OneToOne, ForeignKey, and ManyToMany.</p>
<ol>
<li><h3 id="heading-onetoone-relationship">OneToOne Relationship:</h3>
<p> The OneToOneField is a type of field in Django models that establishes a one-to-one relationship between two models. This means that each record in one model is directly related to exactly one record in another model, and vice versa. This type of relationship is useful in scenarios where each instance of one model corresponds to a single instance of another model.</p>
<p> Creating a OneToOneField:</p>
<p> To illustrate the usage of OneToOneField, let's consider a common example: a user and a user profile. Each user has a unique profile, and each profile is associated with a single user. Here's how you can define this relationship in Django models:</p>
<pre><code class="lang-python"> <span class="hljs-keyword">from</span> django.db <span class="hljs-keyword">import</span> models

 <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span>(<span class="hljs-params">models.Model</span>):</span>
     username = models.CharField(max_length=<span class="hljs-number">50</span>)

 <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserProfile</span>(<span class="hljs-params">models.Model</span>):</span>
     user = models.OneToOneField(User, on_delete=models.CASCADE)
     bio = models.TextField()
</code></pre>
<p> In this example, the <code>UserProfile</code> model has a OneToOneField named <code>user</code> that links to the <code>User</code> model. The <code>on_delete</code> attribute is crucial here and determines the behavior when the referenced user is deleted. In this case, <code>models.CASCADE</code> is used, meaning that if a user is deleted, their corresponding user profile will also be deleted.</p>
<p> Attributes of OneToOneField:</p>
<ol>
<li><p><strong>on_delete:</strong><br /> As mentioned earlier, the <code>on_delete</code> attribute is mandatory for a OneToOneField. It specifies the behavior when the referenced object is deleted. Options include <code>CASCADE</code>, <code>PROTECT</code>, <code>SET_NULL</code>, <code>SET_DEFAULT</code>, <code>SET()</code>, and <code>DO_NOTHING</code>. Choosing the right option depends on the requirements of your application.</p>
</li>
<li><p><strong>limit_choices_to:</strong></p>
<ul>
<li><p>The <code>limit_choices_to</code> attribute restricts the available choices for the OneToOneField based on a condition. For instance, if you want to limit the available profiles to only those with a certain condition, you can use:</p>
<pre><code class="lang-python">  <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserProfile</span>(<span class="hljs-params">models.Model</span>):</span>
      user = models.OneToOneField(User, on_delete=models.CASCADE, limit_choices_to={<span class="hljs-string">'is_staff'</span>: <span class="hljs-literal">True</span>})
      bio = models.TextField()
</code></pre>
<p>  Here, only user profiles where the associated user is a staff member will be available as choices.</p>
</li>
</ul>
</li>
<li><p><strong>related_name:</strong></p>
<ul>
<li><p>The <code>related_name</code> attribute allows you to set the name of the reverse relation from the referenced model back to the model that defines the OneToOneField. This can be handy when you want to access the reverse relation easily. For example:</p>
<pre><code class="lang-python">  <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserProfile</span>(<span class="hljs-params">models.Model</span>):</span>
      user = models.OneToOneField(User, on_delete=models.CASCADE, related_name=<span class="hljs-string">'profile'</span>)
      bio = models.TextField()
</code></pre>
<p>  Now, you can access a user's profile using <code>user.profile</code>.</p>
</li>
</ul>
</li>
<li><p><strong>parent_link:</strong></p>
<ul>
<li>The <code>parent_link</code> attribute, when set to <code>True</code>, creates an additional hidden field to store the relationship between the models. This can be useful in certain scenarios, but it's not commonly used.</li>
</ul>
</li>
<li><p><strong>unique:</strong></p>
<ul>
<li>The <code>unique</code> attribute, when set to <code>True</code>, enforces that each instance of the model with a OneToOneField has a unique related object. This is similar to adding a unique constraint to the database.</li>
</ul>
</li>
</ol>
</li>
</ol>
<p>    Putting it All Together:</p>
<p>    Now that we've explored the attributes of OneToOneField, let's see how they can be combined to create a flexible and efficient data model. Continuing with our user and user profile example, we might have the following:</p>
<pre><code class="lang-python">    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span>(<span class="hljs-params">models.Model</span>):</span>
        username = models.CharField(max_length=<span class="hljs-number">50</span>)

    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserProfile</span>(<span class="hljs-params">models.Model</span>):</span>
        user = models.OneToOneField(User, on_delete=models.CASCADE, related_name=<span class="hljs-string">'profile'</span>, limit_choices_to={<span class="hljs-string">'is_staff'</span>: <span class="hljs-literal">True</span>}, unique=<span class="hljs-literal">True</span>)
        bio = models.TextField()
</code></pre>
<p>    In this setup:</p>
<ul>
<li><p><code>on_delete</code> ensures that when a user is deleted, their profile is also deleted.</p>
</li>
<li><p><code>related_name</code> makes it easy to access a user's profile using <code>user.profile</code>.</p>
</li>
<li><p><code>limit_choices_to</code> restricts the available choices to only user profiles where the associated user is a staff member.</p>
</li>
<li><p><code>unique</code> ensures that each user has a unique profile.</p>
</li>
</ul>
<p>    Mastering OneToOneField in Django opens up a world of possibilities for designing clean and efficient data models. Understanding the attributes such as <code>on_delete</code>, <code>related_name</code>, <code>limit_choices_to</code>, <code>parent_link</code>, and <code>unique</code> allows developers to tailor the behavior of the OneToOneField to fit the specific needs of their applications. As you embark on your journey as a Django developer, incorporating these concepts into your projects will contribute to building robust and well-organized applications.\</p>
<ol start="2">
<li><h3 id="heading-foreignkey-relationship">ForeignKey Relationship:</h3>
<p> A ForeignKey is a field in a Django model that creates a many-to-one relationship between two models. This relationship signifies that each record in the referencing model (the model containing the ForeignKey) is associated with exactly one record in the referenced model. This type of relationship is particularly useful when modeling scenarios where entities are interconnected, such as the relationship between authors and their books in a library application.</p>
<p> Creating a ForeignKey Relationship:</p>
<p> To illustrate the usage of ForeignKey, let's consider a common example: a blog application where each post is associated with an author. Here's how you can define this relationship in Django models:</p>
<pre><code class="lang-python"> <span class="hljs-keyword">from</span> django.db <span class="hljs-keyword">import</span> models

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

 <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">200</span>)
     content = models.TextField()
     author = models.ForeignKey(Author, on_delete=models.CASCADE)
</code></pre>
<p> In this example, the <code>Post</code> model has a ForeignKey named <code>author</code> that references the <code>Author</code> model. The <code>on_delete</code> attribute is crucial and specifies what should happen when the referenced author is deleted. In this case, <code>models.CASCADE</code> is used, indicating that if an author is deleted, all of their associated posts will also be deleted.</p>
<p> Attributes of ForeignKey:</p>
<ol>
<li><p><strong>on_delete:</strong></p>
<ul>
<li>The <code>on_delete</code> attribute is mandatory for a ForeignKey and determines the behavior when the referenced object is deleted. As mentioned earlier, options include <code>CASCADE</code>, <code>PROTECT</code>, <code>SET_NULL</code>, <code>SET_DEFAULT</code>, <code>SET()</code>, and <code>DO_NOTHING</code>. Choosing the right option is crucial for maintaining data integrity and preventing unexpected behavior.</li>
</ul>
</li>
<li><p><strong>related_name:</strong></p>
<ul>
<li><p>Similar to the OneToOneField, the <code>related_name</code> attribute allows you to set the name of the reverse relation from the referenced model back to the model that defines the ForeignKey. This is useful when you want to access the reverse relation easily. For example:</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">200</span>)
      content = models.TextField()
      author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name=<span class="hljs-string">'posts'</span>)
</code></pre>
<p>  Now, you can access an author's posts using <code>author.posts</code>.</p>
</li>
</ul>
</li>
<li><p><strong>related_query_name:</strong></p>
<ul>
<li><p>The <code>related_query_name</code> attribute allows you to specify the name to use for the reverse relation from the referenced model to the model that defines the ForeignKey. This is useful when performing queries. For example:</p>
<pre><code class="lang-python">  <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Author</span>(<span class="hljs-params">models.Model</span>):</span>
      name = models.CharField(max_length=<span class="hljs-number">100</span>)

  <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">200</span>)
      content = models.TextField()
      author = models.ForeignKey(Author, on_delete=models.CASCADE, related_query_name=<span class="hljs-string">'post'</span>)
</code></pre>
<p>  Now, you can use <code>Author.objects.filter(post__title__icontains='Django')</code> to filter authors based on their posts.</p>
</li>
</ul>
</li>
<li><p><strong>limit_choices_to:</strong></p>
<ul>
<li><p>The <code>limit_choices_to</code> attribute restricts the available choices for the ForeignKey based on a condition. For instance, if you want to limit the available authors to only those with a certain condition, you can use:</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">200</span>)
      content = models.TextField()
      author = models.ForeignKey(Author, on_delete=models.CASCADE, limit_choices_to={<span class="hljs-string">'is_published'</span>: <span class="hljs-literal">True</span>})
</code></pre>
<p>  Here, only authors with the specified condition (<code>is_published=True</code>) will be available as choices.</p>
</li>
</ul>
</li>
<li><p><strong>to_field:</strong></p>
<ul>
<li><p>The <code>to_field</code> attribute allows you to specify the field on the related model that should be used as the target of the ForeignKey. This can be useful when you want to establish the ForeignKey relationship with a field other than the primary key. For example:</p>
<pre><code class="lang-python">  <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Author</span>(<span class="hljs-params">models.Model</span>):</span>
      name = models.CharField(max_length=<span class="hljs-number">100</span>)
      email = models.EmailField(unique=<span class="hljs-literal">True</span>)

  <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">200</span>)
      content = models.TextField()
      author = models.ForeignKey(Author, on_delete=models.CASCADE, to_field=<span class="hljs-string">'email'</span>)
</code></pre>
<p>  Here, the <code>email</code> field in the <code>Author</code> model is used as the target field for the ForeignKey.</p>
</li>
</ul>
</li>
<li><p><strong>db_constraint:</strong></p>
<ul>
<li>The <code>db_constraint</code> attribute, when set to <code>False</code>, disables the database constraint for the ForeignKey. This means that the database won't enforce referential integrity, allowing you to have references to non-existent rows. While this can be useful in certain scenarios, it should be used cautiously to avoid data inconsistencies.</li>
</ul>
</li>
</ol>
</li>
</ol>
<p>    Putting it All Together:</p>
<p>    Let's explore how these attributes can be combined to create a flexible and efficient data model. Continuing with our blog example, we might have the following:</p>
<pre><code class="lang-python">    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Author</span>(<span class="hljs-params">models.Model</span>):</span>
        name = models.CharField(max_length=<span class="hljs-number">100</span>)
        is_published = models.BooleanField(default=<span class="hljs-literal">True</span>)

    <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">200</span>)
        content = models.TextField()
        author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name=<span class="hljs-string">'posts'</span>, related_query_name=<span class="hljs-string">'post'</span>, limit_choices_to={<span class="hljs-string">'is_published'</span>: <span class="hljs-literal">True</span>}, to_field=<span class="hljs-string">'name'</span>, db_constraint=<span class="hljs-literal">False</span>)
</code></pre>
<p>    In this setup:</p>
<ul>
<li><p><code>on_delete</code> ensures that when an author is deleted, all of their associated posts are also deleted.</p>
</li>
<li><p><code>related_name</code> allows easy access to an author's posts using <code>author.posts</code>.</p>
</li>
<li><p><code>related_query_name</code> provides a clear way to perform queries on the reverse relation (<code>Author.objects.filter(post__title__icontains='Django')</code>).</p>
</li>
<li><p><code>limit_choices_to</code> restricts the available authors to only those with the specified condition (<code>is_published=True</code>).</p>
</li>
<li><p><code>to_field</code> specifies the field on the related model (<code>Author</code>) that should be used as the target of the ForeignKey (<code>name</code> in this case).</p>
</li>
<li><p><code>db_constraint=False</code> disables the database constraint for the ForeignKey.</p>
</li>
</ul>
<p>    In this article, we've explored the power of ForeignKey in Django and its attributes that shape the behavior of the relationship. Understanding how to leverage <code>on_delete</code>, <code>related_name</code>, <code>related_query_name</code>, <code>limit_choices_to</code>, <code>to_field</code>, and <code>db_constraint</code> empowers developers to design intricate and efficient data models tailored to the specific requirements of their applications. As you embark on your journey as a Django developer, incorporating these concepts into your projects will contribute to building scalable and maintainable web applications.</p>
<ol start="3">
<li><h3 id="heading-manytomany-relationship">ManyToMany Relationship:</h3>
<p> A ManyToManyField in Django establishes a many-to-many relationship between two models, allowing each record in one model to be associated with multiple records in another model, and vice versa. This type of relationship is common in scenarios where entities can have multiple connections with each other, such as the relationship between students and courses in an education system.</p>
<p> Creating a Many-to-Many Relationship:</p>
<p> To illustrate the usage of ManyToManyField, let's consider a classic example: a music application where each artist can be associated with multiple genres, and each genre can be linked to multiple artists. Here's how you can define this relationship in Django models:</p>
<pre><code class="lang-python"> <span class="hljs-keyword">from</span> django.db <span class="hljs-keyword">import</span> models

 <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Artist</span>(<span class="hljs-params">models.Model</span>):</span>
     name = models.CharField(max_length=<span class="hljs-number">100</span>)
     genres = models.ManyToManyField(<span class="hljs-string">'Genre'</span>)

 <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Genre</span>(<span class="hljs-params">models.Model</span>):</span>
     name = models.CharField(max_length=<span class="hljs-number">50</span>)
</code></pre>
<p> In this example, the <code>Artist</code> model has a ManyToManyField named <code>genres</code> that references the <code>Genre</code> model. This allows an artist to be associated with multiple genres, and a genre to be linked to multiple artists.</p>
<p> Attributes of ManyToManyField:</p>
<ol>
<li><p><strong>symmetrical:</strong></p>
<ul>
<li>The <code>symmetrical</code> attribute, by default set to <code>True</code>, implies that if an instance of model A is related to an instance of model B, then the reverse is also true. In our music application example, if an artist is associated with a genre, then that genre is also associated with the artist. Setting <code>symmetrical</code> to <code>False</code> can be useful in scenarios where the relationship between the two models is not necessarily reciprocal.</li>
</ul>
</li>
</ol>
</li>
</ol>
<pre><code class="lang-python">        <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Artist</span>(<span class="hljs-params">models.Model</span>):</span>
            name = models.CharField(max_length=<span class="hljs-number">100</span>)
            genres = models.ManyToManyField(<span class="hljs-string">'Genre'</span>, symmetrical=<span class="hljs-literal">False</span>)
</code></pre>
<ol start="2">
<li><p><strong>through:</strong></p>
<ul>
<li>The <code>through</code> attribute allows the creation of a custom intermediary model for the many-to-many relationship. This intermediary model can have additional fields, providing more flexibility and control over the relationship.</li>
</ul>
</li>
</ol>
<pre><code class="lang-python">        <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Membership</span>(<span class="hljs-params">models.Model</span>):</span>
            artist = models.ForeignKey(Artist, on_delete=models.CASCADE)
            genre = models.ForeignKey(Genre, on_delete=models.CASCADE)
            date_joined = models.DateField()

        <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Artist</span>(<span class="hljs-params">models.Model</span>):</span>
            name = models.CharField(max_length=<span class="hljs-number">100</span>)
            genres = models.ManyToManyField(<span class="hljs-string">'Genre'</span>, through=<span class="hljs-string">'Membership'</span>)

        <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Genre</span>(<span class="hljs-params">models.Model</span>):</span>
            name = models.CharField(max_length=<span class="hljs-number">50</span>)
</code></pre>
<p>        Here, the <code>Membership</code> model serves as the intermediary model with an additional field <code>date_joined</code>, allowing you to track when an artist joined a particular genre.</p>
<ol start="3">
<li><p><strong>related_name:</strong></p>
<ul>
<li>Similar to ForeignKey, the <code>related_name</code> attribute allows you to set the name of the reverse relation from the referenced model back to the model that defines the ManyToManyField. This is useful when you want to access the reverse relation easily.</li>
</ul>
</li>
</ol>
<pre><code class="lang-python">        <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Artist</span>(<span class="hljs-params">models.Model</span>):</span>
            name = models.CharField(max_length=<span class="hljs-number">100</span>)
            genres = models.ManyToManyField(<span class="hljs-string">'Genre'</span>, related_name=<span class="hljs-string">'artists'</span>)
</code></pre>
<p>        Now, you can access all artists associated with a genre using <code>genre.artists.all()</code>.</p>
<ol start="4">
<li><p><strong>related_query_name:</strong></p>
<ul>
<li>The <code>related_query_name</code> attribute allows you to specify the name to use for the reverse relation from the referenced model to the model that defines the ManyToManyField when performing queries.</li>
</ul>
</li>
</ol>
<pre><code class="lang-python">        <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Genre</span>(<span class="hljs-params">models.Model</span>):</span>
            name = models.CharField(max_length=<span class="hljs-number">50</span>)
            artists = models.ManyToManyField(<span class="hljs-string">'Artist'</span>, related_query_name=<span class="hljs-string">'artist'</span>)
</code></pre>
<p>        Now, you can use <code>Genre.objects.filter(artist__name__icontains='John')</code> to filter genres based on the associated artists.</p>
<ol start="5">
<li><p><strong>limit_choices_to:</strong></p>
<ul>
<li>The <code>limit_choices_to</code> attribute restricts the available choices for the ManyToManyField based on a condition.</li>
</ul>
</li>
</ol>
<pre><code class="lang-python">        <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Artist</span>(<span class="hljs-params">models.Model</span>):</span>
            name = models.CharField(max_length=<span class="hljs-number">100</span>)
            genres = models.ManyToManyField(<span class="hljs-string">'Genre'</span>, limit_choices_to={<span class="hljs-string">'is_active'</span>: <span class="hljs-literal">True</span>})
</code></pre>
<p>        Here, only active genres will be available as choices for the artist.</p>
<ol start="6">
<li><p><strong>symmetrical:</strong></p>
<ul>
<li>In addition to the <code>symmetrical</code> attribute mentioned earlier, the ManyToManyField also has a <code>symmetrical</code> option that can be set to <code>False</code> on one side of the relationship to indicate that the reverse relation should not be created. This is useful when dealing with scenarios where the relationship is asymmetrical.</li>
</ul>
</li>
</ol>
<pre><code class="lang-python">        <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Artist</span>(<span class="hljs-params">models.Model</span>):</span>
            name = models.CharField(max_length=<span class="hljs-number">100</span>)
            genres = models.ManyToManyField(<span class="hljs-string">'Genre'</span>, symmetrical=<span class="hljs-literal">False</span>)
</code></pre>
<p>    Putting it All Together:</p>
<p>    Let's explore how these attributes can be combined to create a flexible and efficient data model. Continuing with our music application example, we might have the following:</p>
<pre><code class="lang-python">    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Membership</span>(<span class="hljs-params">models.Model</span>):</span>
        artist = models.ForeignKey(Artist, on_delete=models.CASCADE)
        genre = models.ForeignKey(Genre, on_delete=models.CASCADE)
        date_joined = models.DateField()

    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Artist</span>(<span class="hljs-params">models.Model</span>):</span>
        name = models.CharField(max_length=<span class="hljs-number">100</span>)
        genres = models.ManyToManyField(<span class="hljs-string">'Genre'</span>, through=<span class="hljs-string">'Membership'</span>, related_name=<span class="hljs-string">'artists'</span>, related_query_name=<span class="hljs-string">'artist'</span>, limit_choices_to={<span class="hljs-string">'is_active'</span>: <span class="hljs-literal">True</span>}, symmetrical=<span class="hljs-literal">False</span>)

    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Genre</span>(<span class="hljs-params">models.Model</span>):</span>
        name = models.CharField(max_length=<span class="hljs-number">50</span>)
        is_active = models.BooleanField(default=<span class="hljs-literal">True</span>)
</code></pre>
<p>    In this setup:</p>
<ul>
<li><p><code>through='Membership'</code> introduces an intermediary model for the many-to-many relationship, allowing us to store additional information like the <code>date_joined</code>.</p>
</li>
<li><p><code>related_name</code> and <code>related_query_name</code> make it convenient to access the reverse relation from both sides of the relationship.</p>
</li>
<li><p><code>limit_choices_to</code> restricts the available genres for an artist to only those that are active.</p>
</li>
<li><p><code>symmetrical=False</code> indicates that the relationship is not necessarily reciprocal, allowing for asymmetrical connections.</p>
</li>
</ul>
<p>    In this article, we've delved into the ManyToManyField in Django and its various attributes that shape the behavior of many-to-many relationships. Understanding how to use <code>symmetrical</code>, <code>through</code>, <code>related_name</code>, <code>related_query_name</code>, <code>limit_choices_to</code>, and <code>symmetrical</code> allows developers to create intricate and flexible data models that accurately represent the complex relationships in their applications. As you navigate the landscape of Django development, incorporating these concepts into your projects will empower you to build scalable and well-organized web applications.</p>
<p>Conclusion:</p>
<p>In this article, we've explored the fundamental concepts of database relationships in Django. Understanding how to leverage OneToOne, ForeignKey, and ManyToMany relationships allows developers to design complex and interconnected applications with ease. As you continue your journey into Django development, mastering these relationships will be essential for building scalable and maintainable web applications.</p>
]]></content:encoded></item><item><title><![CDATA[Mastering Django Forms: An Incomprehensive Guide]]></title><description><![CDATA[What are Forms?
Django, a high-level web framework written in Python, empowers developers to create robust and scalable web applications. One of the fundamental components of building interactive web forms in Django is its powerful form handling syst...]]></description><link>https://blog.django-tutorial.dev/django-forms</link><guid isPermaLink="true">https://blog.django-tutorial.dev/django-forms</guid><category><![CDATA[django forms]]></category><category><![CDATA[Django]]></category><category><![CDATA[django rest framework]]></category><category><![CDATA[django master]]></category><category><![CDATA[Multiply and surrender]]></category><category><![CDATA[General Programming]]></category><category><![CDATA[Python]]></category><dc:creator><![CDATA[Nischal lamichhane]]></dc:creator><pubDate>Wed, 31 Jan 2024 08:08:09 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1706687969338/1ca8eec0-696b-4111-b279-d47260f1eef0.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-what-are-forms"><strong>What are Forms?</strong></h1>
<p>Django, a high-level web framework written in Python, empowers developers to create robust and scalable web applications. One of the fundamental components of building interactive web forms in Django is its powerful form handling system. <strong><em>Django forms provide a seamless way to handle user input, validate data, and simplify the process of creating HTML forms.</em></strong></p>
<p>Learn Python &amp; Django at <a target="_blank" href="https://django-tutorial.dev">django-tutorial.dev</a></p>
<h2 id="heading-understanding-django-forms"><strong>Understanding Django Forms</strong></h2>
<p>In Django, a form is a Python class that defines the fields and behavior of the form. These fields can be as simple as a text input or as complex as a file upload. Django forms take care of rendering HTML, validating data, and handling user input.</p>
<h3 id="heading-creating-a-basic-form"><strong>Creating a Basic Form</strong></h3>
<p>Let's start by creating a simple Django form. Consider a scenario where you want to collect user information, such as their name and email.</p>
<pre><code class="lang-python"><span class="hljs-comment"># forms.py</span>
<span class="hljs-keyword">from</span> django <span class="hljs-keyword">import</span> forms

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserForm</span>(<span class="hljs-params">forms.Form</span>):</span>
    name = forms.CharField(label=<span class="hljs-string">'Your Name'</span>, max_length=<span class="hljs-number">100</span>)
    email = forms.EmailField(label=<span class="hljs-string">'Your Email'</span>)
</code></pre>
<p>Here, we define a <code>UserForm</code> class that inherits from <code>forms.Form</code>. The form has two fields: <code>name</code> and <code>email</code>. The <code>CharField</code> and <code>EmailField</code> are examples of form fields provided by Django.</p>
<h3 id="heading-rendering-forms-in-views"><strong>Rendering Forms in Views</strong></h3>
<p>Now that we have our form, let's see how to use it in a view. Below is a simple view that renders the form and handles the form submission.</p>
<pre><code class="lang-python"><span class="hljs-comment"># 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> UserForm

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">user_info</span>(<span class="hljs-params">request</span>):</span>
    <span class="hljs-keyword">if</span> request.method == <span class="hljs-string">'POST'</span>:
        form = UserForm(request.POST)
        <span class="hljs-keyword">if</span> form.is_valid():
            <span class="hljs-comment"># Do something with the valid form data</span>
            <span class="hljs-keyword">return</span> redirect(<span class="hljs-string">'success_page'</span>)
    <span class="hljs-keyword">else</span>:
        form = UserForm()

    <span class="hljs-keyword">return</span> render(request, <span class="hljs-string">'user_info.html'</span>, {<span class="hljs-string">'form'</span>: form})
</code></pre>
<p>In this view, we instantiate the <code>UserForm</code> class. If the request method is POST, it means the form is being submitted, so we validate the form. If the form is valid, we can perform actions with the submitted data.</p>
<h3 id="heading-html-template-for-form-rendering"><strong>HTML Template for Form Rendering</strong></h3>
<p>To render the form in an HTML template, create a template named <code>user_info.html</code>.</p>
<pre><code class="lang-haml">&lt;!-- user_info.html --&gt;
&lt;form method="post" action="{% url 'user_info' %}"&gt;
    {% csrf_token %}
    {{ form.as_p }}
    &lt;button type="submit"&gt;Submit&lt;/button&gt;
&lt;/form&gt;
</code></pre>
<p>Here, <code>{{</code><a target="_blank" href="http://form.as"><code>form.as</code></a><code>_p }}</code> automatically renders the form fields as paragraphs. Django takes care of rendering the HTML based on the form definition. Note that <code>{%csrf_token%}</code> is a context processor available to all templates. Read about context processors <a target="_blank" href="https://blog.nischallamichhane.com.np/context-processors-in-django">here</a> . You can use <code>@csrf_exempt</code> decorator in your function if you dont want to use csrf_token context processor. Read more about decorators <a target="_blank" href="https://blog.nischallamichhane.com.np/django-decorators">here</a></p>
<h2 id="heading-validating-data-with-django-forms"><strong>Validating Data with Django Forms</strong></h2>
<p>Django forms come with built-in validators that make it easy to ensure the submitted data meets certain criteria.</p>
<h3 id="heading-custom-validation"><strong>Custom Validation</strong></h3>
<p>Suppose you want to ensure that the user's name does not contain numbers. You can add a custom validator to the <code>name</code> field in the <code>UserForm</code> class.</p>
<pre><code class="lang-python"><span class="hljs-comment"># forms.py</span>
<span class="hljs-keyword">from</span> django.core.exceptions <span class="hljs-keyword">import</span> ValidationError

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">validate_no_numbers</span>(<span class="hljs-params">value</span>):</span>
    <span class="hljs-keyword">if</span> any(char.isdigit() <span class="hljs-keyword">for</span> char <span class="hljs-keyword">in</span> value):
        <span class="hljs-keyword">raise</span> ValidationError(<span class="hljs-string">'Name cannot contain numbers.'</span>)

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserForm</span>(<span class="hljs-params">forms.Form</span>):</span>
    name = forms.CharField(label=<span class="hljs-string">'Your Name'</span>, max_length=<span class="hljs-number">100</span>, validators=[validate_no_numbers])
    email = forms.EmailField(label=<span class="hljs-string">'Your Email'</span>)
</code></pre>
<p>Now, if a user tries to submit a name with numbers, the form will be considered invalid, and an appropriate error message will be displayed.</p>
<h2 id="heading-enhancing-forms-with-widgets"><strong>Enhancing Forms with Widgets</strong></h2>
<p>Django provides widgets to customize the HTML rendering of form fields. Let's enhance our <code>UserForm</code> by adding a date of birth field with a DateInput widget.</p>
<pre><code class="lang-python"><span class="hljs-comment"># forms.py</span>
<span class="hljs-keyword">from</span> django.forms <span class="hljs-keyword">import</span> DateInput

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserForm</span>(<span class="hljs-params">forms.Form</span>):</span>
    name = forms.CharField(label=<span class="hljs-string">'Your Name'</span>, max_length=<span class="hljs-number">100</span>)
    email = forms.EmailField(label=<span class="hljs-string">'Your Email'</span>)
    dob = forms.DateField(label=<span class="hljs-string">'Date of Birth'</span>, widget=DateInput(attrs={<span class="hljs-string">'type'</span>: <span class="hljs-string">'date'</span>}))
</code></pre>
<p>In this example, the <code>DateInput</code> widget is used to render the date field as an input with a date picker.</p>
<h2 id="heading-adding-classnames-and-styling-to-django-forms"><strong>Adding Classnames and Styling to Django Forms</strong></h2>
<p>Ensuring that your Django forms not only function well but also look visually appealing is crucial for providing a positive user experience. Django allows you to customize the rendering of form elements by adding classnames and styling through the use of widgets and HTML attributes. Let's explore how you can enhance the appearance of your forms.</p>
<h3 id="heading-styling-form-fields-with-classnames"><strong>Styling Form Fields with Classnames</strong></h3>
<p>You can add custom classnames to form fields to apply specific styles. This is particularly useful when you want to customize the appearance of individual fields or apply a consistent style across your forms.</p>
<pre><code class="lang-python"><span class="hljs-comment"># forms.py</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserForm</span>(<span class="hljs-params">forms.Form</span>):</span>
    name = forms.CharField(label=<span class="hljs-string">'Your Name'</span>, max_length=<span class="hljs-number">100</span>, widget=forms.TextInput(attrs={<span class="hljs-string">'class'</span>: <span class="hljs-string">'custom-input'</span>}))
    email = forms.EmailField(label=<span class="hljs-string">'Your Email'</span>, widget=forms.EmailInput(attrs={<span class="hljs-string">'class'</span>: <span class="hljs-string">'custom-input'</span>}))
    dob = forms.DateField(label=<span class="hljs-string">'Date of Birth'</span>, widget=DateInput(attrs={<span class="hljs-string">'type'</span>: <span class="hljs-string">'date'</span>, <span class="hljs-string">'class'</span>: <span class="hljs-string">'custom-input'</span>}))
</code></pre>
<p>In the above example, the <code>custom-input</code> class is added to each form field, allowing you to target and style them in your CSS.</p>
<h3 id="heading-applying-overall-form-styles"><strong>Applying Overall Form Styles</strong></h3>
<p>To style the form as a whole, you can utilize the form element in your HTML template and assign a class to it.</p>
<pre><code class="lang-haml">&lt;!-- user_info.html --&gt;
&lt;form method="post" action="{% url 'user_info' %}" class="custom-form"&gt;
    {% csrf_token %}
    {{ form.as_p }}
    &lt;button type="submit" class="custom-button"&gt;Submit&lt;/button&gt;
&lt;/form&gt;
</code></pre>
<p>In this case, the form has been assigned the <code>custom-form</code> class, and the submit button has the <code>custom-button</code> class. This allows you to apply specific styles to the entire form or individual elements.</p>
<h3 id="heading-writing-css-styles-for-custom-classes"><strong>Writing CSS Styles for Custom Classes</strong></h3>
<p>Now that you've added custom classnames to your form elements, it's time to define the styles in your CSS file. Create a CSS file (e.g., <code>styles.css</code>) and link it in your HTML template.</p>
<pre><code class="lang-css"><span class="hljs-comment">/* styles.css */</span>
<span class="hljs-selector-class">.custom-input</span> {
    <span class="hljs-comment">/* Add your custom styles for form fields here */</span>
    <span class="hljs-attribute">border</span>: <span class="hljs-number">1px</span> solid <span class="hljs-number">#ccc</span>;
    <span class="hljs-attribute">padding</span>: <span class="hljs-number">8px</span>;
}

<span class="hljs-selector-class">.custom-form</span> {
    <span class="hljs-comment">/* Add overall form styles here */</span>
    <span class="hljs-attribute">max-width</span>: <span class="hljs-number">400px</span>;
    <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span> auto;
}

<span class="hljs-selector-class">.custom-button</span> {
    <span class="hljs-comment">/* Add styles for the submit button here */</span>
    <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#4CAF50</span>;
    <span class="hljs-attribute">color</span>: white;
    <span class="hljs-attribute">padding</span>: <span class="hljs-number">10px</span> <span class="hljs-number">15px</span>;
    <span class="hljs-attribute">border</span>: none;
    <span class="hljs-attribute">cursor</span>: pointer;
}
</code></pre>
<p>Ensure that the CSS file is properly linked in your HTML template. With these styles, you have the flexibility to create a visually appealing and cohesive design for your Django forms.</p>
<h3 id="heading-topics-to-explore-on-your-own">Topics to Explore on your own:</h3>
<ol>
<li><p>Existence of FreeWill (if it exists)</p>
</li>
<li><p>Creating a form for a modal and using widget to stylize the fields and add more properties like required, multiple, placeholder etc</p>
</li>
<li><p>Using init function to loop through all fields of the form customizing them</p>
</li>
<li><p>Overriding default functions like save and cleaned_data</p>
</li>
</ol>
<h2 id="heading-conclusion"><strong>Conclusion</strong></h2>
<p>Django forms are a powerful tool for handling user input in web applications. Whether you're collecting simple information or dealing with complex data, Django forms simplify the process of validation, rendering HTML, and processing user input. As you delve deeper into Django development, mastering the intricacies of forms will undoubtedly contribute to the efficiency and robustness of your web applications. Suffer coding!</p>
<h1 id="heading-this-is-your-7900-steps-in-becoming-a-django-master-jr"><strong>This is your 7/900 Steps in becoming a Django Master jr.</strong></h1>
]]></content:encoded></item><item><title><![CDATA[Django Decorators: An incomprehensive guide]]></title><description><![CDATA[Mastering Django Decorators: A Deep Dive into Pythonic Web Development
Django, a web framework written in Python, is celebrated for its simplicity and flexibility. One of the powerful features that contribute to this reputation is decorators. Decorat...]]></description><link>https://blog.django-tutorial.dev/django-decorators</link><guid isPermaLink="true">https://blog.django-tutorial.dev/django-decorators</guid><category><![CDATA[django decorators]]></category><category><![CDATA[Multiply and surrender]]></category><category><![CDATA[Django]]></category><category><![CDATA[django master]]></category><category><![CDATA[General Programming]]></category><category><![CDATA[Python]]></category><category><![CDATA[Python Decorator]]></category><category><![CDATA[django rest framework]]></category><dc:creator><![CDATA[Nischal lamichhane]]></dc:creator><pubDate>Wed, 31 Jan 2024 07:41:48 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1706686490045/e64f57a1-e3ff-4b38-ada4-894966729da5.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-mastering-django-decorators-a-deep-dive-into-pythonic-web-development"><strong>Mastering Django Decorators: A Deep Dive into Pythonic Web Development</strong></h1>
<p>Django, a web framework written in Python, is celebrated for its simplicity and flexibility. One of the powerful features that contribute to this reputation is decorators. Decorators in Django allow developers to modify or extend the behavior of functions or methods effortlessly. In this blog post, we'll embark on a journey to master Django decorators, exploring their basics, common use cases, and advanced patterns.</p>
<p>Learn Python &amp; Django at <a target="_blank" href="https://django-tutorial.dev">django-tutorial.dev</a></p>
<h2 id="heading-understanding-python-decorators"><strong>Understanding Python Decorators</strong></h2>
<p>Before diving into Django-specific decorators, it's essential to understand Python decorators in general. In Python, a decorator is a function that takes another function and extends or modifies its behavior. Decorators are denoted with the <code>@</code> symbol and are placed above the function they decorate.</p>
<pre><code class="lang-python"><span class="hljs-comment"># A simple decorator</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">my_decorator</span>(<span class="hljs-params">func</span>):</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">wrapper</span>():</span>
        print(<span class="hljs-string">"Something is happening before the function is called."</span>)
        func()
        print(<span class="hljs-string">"Something is happening after the function is called."</span>)
    <span class="hljs-keyword">return</span> wrapper

<span class="hljs-meta">@my_decorator</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">say_hello</span>():</span>
    print(<span class="hljs-string">"Hello!"</span>)

say_hello()

<span class="hljs-string">"""
The output will be:

    Something is happening before the function is called.
    Hello!
    Something is happening after the function is called.

"""</span>
</code></pre>
<p>In this example, <code>my_decorator</code> is a simple decorator that adds behavior before and after the <code>say_hello</code> function is called.</p>
<h2 id="heading-django-view-decorators"><strong>Django View Decorators</strong></h2>
<p>In Django, decorators are widely used to enhance the functionality of views. Let's explore some common view decorators and their applications.</p>
<h3 id="heading-loginrequired"><code>@login_required</code></h3>
<p>The <code>@login_required</code> decorator ensures that a view can only be accessed by authenticated users. If a user is not logged in, they are redirected to the login page.</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> django.contrib.auth.decorators <span class="hljs-keyword">import</span> login_required

<span class="hljs-meta">@login_required</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">my_secure_view</span>(<span class="hljs-params">request</span>):</span>
    <span class="hljs-comment"># Your view logic here</span>
    <span class="hljs-keyword">return</span> render(request, <span class="hljs-string">'secure_page.html'</span>)
</code></pre>
<p>This decorator simplifies the process of securing views that require user authentication.</p>
<h3 id="heading-permissionrequired"><code>@permission_required</code></h3>
<p>Similar to <code>@login_required</code>, the <code>@permission_required</code> decorator checks if a user has specific permissions to access a view.</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> django.contrib.auth.decorators <span class="hljs-keyword">import</span> permission_required

<span class="hljs-meta">@permission_required('myapp.can_view_data')</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">restricted_data_view</span>(<span class="hljs-params">request</span>):</span>
    <span class="hljs-comment"># Your view logic here</span>
    <span class="hljs-keyword">return</span> render(request, <span class="hljs-string">'restricted_data.html'</span>)
</code></pre>
<p>This decorator is useful when you need to control access based on custom permissions defined in your Django app aka Roles of User. This will be handy when you are creating a platform where there are more than 1 types of users like admin, management, employee &amp; Clients.</p>
<h2 id="heading-custom-decorators"><strong>Custom Decorators</strong></h2>
<p>While Django provides useful built-in decorators, you'll often find the need to create your own custom decorators to encapsulate reusable functionality.</p>
<h3 id="heading-creating-an-underrated-decorator"><strong>Creating an Underrated Decorator</strong></h3>
<p>I don't want any supporter of UML( political party) to access my site. I can create a custom decorator to Respond to UML supporters with a message while giving anyone else complete access to my web app. I am going to just respond the text.<br />"<em>YOU ARE THE PROBLEM</em>"</p>
<pre><code class="lang-python"><span class="hljs-comment">#    app/decorators.py</span>
<span class="hljs-keyword">from</span> django.http <span class="hljs-keyword">import</span> HttpResponse

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_help</span>(<span class="hljs-params">view_func</span>):</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">wrapper</span>(<span class="hljs-params">request,*args,**kwargs</span>):</span>
        <span class="hljs-keyword">if</span> request.user.name <span class="hljs-keyword">in</span> uml_supporter_list: <span class="hljs-comment">#this is already documented list</span>
            <span class="hljs-keyword">return</span> HttpResponse(<span class="hljs-string">"YOU ARE THE PROBLEM"</span>)
        <span class="hljs-keyword">else</span>:
            view_func(request,*args,**kwargs)
        <span class="hljs-keyword">return</span> wrapper
</code></pre>
<p>Now, I can use <code>@get_help</code> to decline any UML supporters of my Web Service</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> app.decorators <span class="hljs-keyword">import</span> get_help
<span class="hljs-keyword">from</span> django.shortcuts <span class="hljs-keyword">import</span> render

<span class="hljs-meta">@get_help</span>
<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">'app/index.html'</span>)
</code></pre>
<h3 id="heading-creating-a-logging-decorator"><strong>Creating a Logging Decorator</strong></h3>
<p>Let's say you want to log information about the arguments and return value of a view. You can create a custom logging decorator for this purpose. Below is a code for File based logging using python's built in module called 'logging'. For Django decorators the wrapper needs to take <em>request</em>, *<em>args</em> and **<em>kwargs</em> as parameter in most cases.</p>
<pre><code class="lang-python"><span class="hljs-comment">#    app/decorators.py</span>
<span class="hljs-keyword">import</span> logging

<span class="hljs-comment"># Configure the logging settings (add this to your settings.py or another configuration file)</span>
logging.basicConfig(filename=<span class="hljs-string">'views.log'</span>, level=logging.INFO, format=<span class="hljs-string">'%(asctime)s - %(levelname)s - %(message)s'</span>)

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">log_view</span>(<span class="hljs-params">func</span>):</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">wrapper</span>(<span class="hljs-params">request, *args, **kwargs</span>):</span>
        <span class="hljs-comment"># Log information before calling the view</span>
        log_message = <span class="hljs-string">f"<span class="hljs-subst">{request.user}</span> is calling <span class="hljs-subst">{func.__name__}</span> with arguments: <span class="hljs-subst">{args}</span>, <span class="hljs-subst">{kwargs}</span>"</span>
        logging.info(log_message)

        result = func(request, *args, **kwargs)

        <span class="hljs-comment"># Log information after calling the view</span>
        log_message = <span class="hljs-string">f"<span class="hljs-subst">{func.__name__}</span> returned: <span class="hljs-subst">{result}</span>"</span>
        logging.info(log_message)

        <span class="hljs-keyword">return</span> result
    <span class="hljs-keyword">return</span> wrapper
</code></pre>
<p>Now, you can use <code>@log_view</code> to add logging to any view.</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> app.decorators <span class="hljs-keyword">import</span> log_view

<span class="hljs-meta">@log_view</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">my_logged_view</span>(<span class="hljs-params">request</span>):</span>
    <span class="hljs-comment"># Your view logic here</span>
    <span class="hljs-keyword">return</span> render(request, <span class="hljs-string">'logged_page.html'</span>)
</code></pre>
<h3 id="heading-handling-function-arguments-in-decorators"><strong>Handling Function Arguments in Decorators</strong></h3>
<p>Sometimes, you might need decorators that accept arguments. This can be achieved by adding an extra layer of nested functions.</p>
<pre><code class="lang-python"><span class="hljs-comment">#    app/decorators.py</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">custom_decorator</span>(<span class="hljs-params">arg1, arg2</span>):</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">decorator</span>(<span class="hljs-params">func</span>):</span>
        <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">wrapper</span>(<span class="hljs-params">*args, **kwargs</span>):</span>
            <span class="hljs-comment"># Custom logic using arg1 and arg2</span>
            result = func(*args, **kwargs)
            <span class="hljs-comment"># Additional logic if needed</span>
            <span class="hljs-keyword">return</span> result
        <span class="hljs-keyword">return</span> wrapper
    <span class="hljs-keyword">return</span> decorator
</code></pre>
<p>Now, when applying the decorator, you provide arguments like so:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> app.decorators <span class="hljs-keyword">import</span> custom_decorator
<span class="hljs-meta">@custom_decorator(arg1='value1', arg2='value2')</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">my_decorated_function</span>():</span>
    <span class="hljs-comment"># Your function logic here</span>
    <span class="hljs-keyword">pass</span>
</code></pre>
<p>This pattern allows decorators to be flexible and adaptable to various scenarios.</p>
<h2 id="heading-advanced-decorator-patterns"><strong>Advanced Decorator Patterns</strong></h2>
<p>As you delve deeper into Django development, you may encounter advanced decorator patterns that leverage class-based views or mixins. For example, the <code>@method_decorator</code> allows applying decorators to specific HTTP methods.</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> django.utils.decorators <span class="hljs-keyword">import</span> method_decorator
<span class="hljs-keyword">from</span> django.views <span class="hljs-keyword">import</span> View

<span class="hljs-meta">@method_decorator(login_required, name='dispatch')</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MySecureView</span>(<span class="hljs-params">View</span>):</span>
    <span class="hljs-comment"># Your view logic here</span>
</code></pre>
<p>This ensures that the <code>login_required</code> decorator is only applied to the <code>dispatch</code> method of the class-based view.</p>
<h2 id="heading-conclusion"><strong>Conclusion</strong></h2>
<p>Mastering Django decorators opens the door to elegant and modular code. Whether you're securing views, logging information, or creating custom functionality, decorators provide a clean and Pythonic way to enhance your web development experience. As you continue your Django journey, experimenting with and understanding decorators will undoubtedly contribute to the efficiency and maintainability of your codebase. Suffer decorating!</p>
<h1 id="heading-this-is-your-6900-steps-in-becoming-a-django-master-jr"><strong>This is your 6/900 Steps in becoming a Django Master jr.</strong></h1>
]]></content:encoded></item><item><title><![CDATA[Sending an Email from your Django Server with the Django Master]]></title><description><![CDATA[Sending emails from a Django server is a crucial aspect of many web applications. It allows you to communicate with users, send notifications, and perform various other tasks. In this guide, I'll walk you through the process of setting up email funct...]]></description><link>https://blog.django-tutorial.dev/django-emails</link><guid isPermaLink="true">https://blog.django-tutorial.dev/django-emails</guid><category><![CDATA[Django]]></category><category><![CDATA[django rest framework]]></category><category><![CDATA[django master]]></category><category><![CDATA[Multiply and surrender]]></category><category><![CDATA[General Programming]]></category><category><![CDATA[Python]]></category><category><![CDATA[smtp server]]></category><dc:creator><![CDATA[Nischal lamichhane]]></dc:creator><pubDate>Tue, 23 Jan 2024 04:46:16 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1705984900176/704b5df4-e9a1-4f0a-a355-45fbd0548828.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Sending emails from a Django server is a crucial aspect of many web applications. It allows you to communicate with users, send notifications, and perform various other tasks. In this guide, I'll walk you through the process of setting up email functionality in your Django project using SMTP and specifically, using <a target="_blank" href="http://smtp.gmail.com"><code>smtp.gmail.com</code></a>.</p>
<p>To a Master like me, SMTP stands for Send Mail To Peasants. But to a peasant like you, SMTP should stand for Simple Mail Transfer Protocol. It is the standard Protocol followed by emailing systems. You will be using Gmail's SMTP server to send the mail as it doesn't require your project to be hosted.</p>
<p>Learn Python &amp; Django at <a target="_blank" href="https://django-tutorial.dev">django-tutorial.dev</a></p>
<h3 id="heading-setting-up-django-for-email"><strong>Setting up Django for Email</strong></h3>
<h4 id="heading-1-install-django-amp-decouple">1. Install Django &amp; decouple</h4>
<p>If you haven't already, install Django and decouple using the following commands:</p>
<pre><code class="lang-bash">pip install Django
pip install python-decouple
</code></pre>
<h4 id="heading-2-setting-up-variables">2. Setting up Variables</h4>
<p>You will need an App Password for your gmail account to use gmail's smtp. For this:</p>
<ol>
<li><p>Goto your Google Accounts Security settings <a target="_blank" href="http://myaccount.google.com">here</a></p>
</li>
<li><p>Turn on 2 Factor Authentication (2FA)</p>
</li>
<li><p>Goto App Passwords and create an app password</p>
</li>
<li><p>Copy the Password and securely store it somewhere.</p>
</li>
</ol>
<p>After You have the App password, create an .env file that will have your environment variables for development stage. I have explained what this does in <a target="_blank" href="https://blog.nischallamichhane.com.np/securing-yourself-a-masters-guide-to-fortification">this Blog.</a> This is what .env file should look like:</p>
<pre><code class="lang-plaintext">EMAIL_HOST_USER='django@master.com'
EMAIL_HOST_PASSWORD'xxxx xxxx xxxx xxxx'
</code></pre>
<h4 id="heading-3-configure-email-settings">3. Configure Email Settings</h4>
<p>In your Django project settings (<a target="_blank" href="http://settings.py"><code>settings.py</code></a>), find the <code>EMAIL_BACKEND</code> setting and set it to <code>'django.core.mail.backends.smtp.EmailBackend'</code>. Also, configure the SMTP settings for Gmail:</p>
<pre><code class="lang-python"><span class="hljs-comment"># settings.py</span>
<span class="hljs-keyword">from</span> decouple <span class="hljs-keyword">import</span> config
<span class="hljs-comment"># Email settings</span>
EMAIL_BACKEND = <span class="hljs-string">'django.core.mail.backends.smtp.EmailBackend'</span>
EMAIL_HOST = <span class="hljs-string">'smtp.gmail.com'</span>
EMAIL_PORT = <span class="hljs-number">587</span>
EMAIL_USE_TLS = <span class="hljs-literal">True</span>
EMAIL_HOST_USER = config(<span class="hljs-string">'EMAIL_HOST_USER'</span>)  <span class="hljs-comment"># Your Gmail email address</span>
EMAIL_HOST_PASSWORD = config(<span class="hljs-string">'EMAIL_HOST_PASSWORD'</span>)  <span class="hljs-comment"># Your Gmail email password or app password</span>
</code></pre>
<p>Values in EMAIL_HOST_USER and EMAIL_HOST_PASSWORD will be replaced by decouple with your actual Gmail credentials from '.env' file. Note: It's recommended to use an app password for better security.</p>
<h3 id="heading-writing-the-django-view"><strong>Writing the Django View</strong></h3>
<p>Now, let's create a simple Django view that sends an email when accessed.</p>
<h4 id="heading-1-import-required-modules">1. Import Required Modules</h4>
<p>In your <a target="_blank" href="http://views.py"><code>views.py</code></a> file, import the necessary modules:</p>
<pre><code class="lang-python"><span class="hljs-comment"># views.py</span>

<span class="hljs-keyword">from</span> django.core.mail <span class="hljs-keyword">import</span> send_mail
<span class="hljs-keyword">from</span> django.http <span class="hljs-keyword">import</span> HttpResponse
</code></pre>
<h4 id="heading-2-create-the-email-sending-view">2. Create the Email-Sending View</h4>
<p>Add a function in your <a target="_blank" href="http://views.py"><code>views.py</code></a> to handle email sending:</p>
<pre><code class="lang-python"><span class="hljs-comment"># views.py</span>
<span class="hljs-keyword">from</span> decouple <span class="hljs-keyword">import</span> config
<span class="hljs-keyword">from</span> django.core.mail <span class="hljs-keyword">import</span> send_mail

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">send_email_view</span>(<span class="hljs-params">request</span>):</span>
    to_email = request.user.email
    subject = <span class="hljs-string">'Hello from Your Django App'</span>
    message = <span class="hljs-string">'This is a test email sent from your Django app.'</span>
    from_email = config(<span class="hljs-string">'EMAIL_HOST_USER'</span>)  <span class="hljs-comment"># Sender's email address</span>
    recipient_list = [to_email]  <span class="hljs-comment"># Recipient's email address</span>

    send_mail(subject, message, from_email, recipient_list)

    <span class="hljs-keyword">return</span> HttpResponse(<span class="hljs-string">'Email sent successfully!'</span>)
</code></pre>
<p>You can also research on sending html files as the email message that will render on the receiver's end to prettify your emails.</p>
<h3 id="heading-urls-and-testing"><strong>URLs and Testing</strong></h3>
<p>Finally, configure a URL for your new view in your <a target="_blank" href="http://urls.py"><code>urls.py</code></a>:</p>
<pre><code class="lang-python"><span class="hljs-comment"># 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> send_email_view

urlpatterns = [
    path(<span class="hljs-string">'send_email/'</span>, send_email_view, name=<span class="hljs-string">'send_email'</span>),
]
</code></pre>
<p>Now, run your Django development server and navigate to <a target="_blank" href="http://localhost:8000/send_email/"><code>http://localhost:8000/send_email/</code></a> to trigger the email-sending view. Check the console for any errors, and if everything is set up correctly, you should see the 'Email sent successfully!' message.</p>
<h3 id="heading-conclusion"><strong>Conclusion</strong></h3>
<p>Congratulations! You've successfully set up email functionality in your Django project using Gmail's SMTP server. This is a basic example, and you can expand upon it by customizing the email content, handling attachments, or incorporating email templates.</p>
<p>Additionally, you may want to explore Django's built-in support for sending HTML emails and managing email templates for a more professional and customizable approach. Suffer Coding!</p>
<h1 id="heading-this-is-your-5900-steps-in-becoming-a-django-master-jr">This is your 5/900 Steps in becoming a Django Master jr.</h1>
]]></content:encoded></item><item><title><![CDATA[Securing yourself: A Master's Guide to Fortification]]></title><description><![CDATA[Intro: As a seasoned Django Master and a discerning GitHub Appraiser, my journey involves not only crafting sophisticated Django packages but also delving into the GitHub project repositories of my disciples. In this quest, I often come across projec...]]></description><link>https://blog.django-tutorial.dev/django-production-practices</link><guid isPermaLink="true">https://blog.django-tutorial.dev/django-production-practices</guid><category><![CDATA[Multiply and surrender]]></category><category><![CDATA[Django]]></category><category><![CDATA[django rest framework]]></category><category><![CDATA[DjangoRestFramework]]></category><category><![CDATA[django orm]]></category><category><![CDATA[General Programming]]></category><category><![CDATA[django master]]></category><category><![CDATA[GitHub]]></category><category><![CDATA[version control]]></category><category><![CDATA[#Git #GitHub #VersionControl #DistributedVersionControl #CentralizedVersionControl #DevOps #SoftwareDevelopment #CodeManagement #CodeCollaboration #CodeSharing #OpenSource #Programming #DeveloperTools #Technology #CodingTips]]></category><dc:creator><![CDATA[Nischal lamichhane]]></dc:creator><pubDate>Mon, 08 Jan 2024 11:24:15 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1704712950600/3de20f2b-009f-4056-a706-20f94315c134.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Intro: As a seasoned Django Master and a discerning GitHub Appraiser, my journey involves not only crafting sophisticated Django packages but also delving into the GitHub project repositories of my disciples. In this quest, I often come across projects that exhibit vulnerability and insecurity. Let's explore some of the common pitfalls I've observed during my ventures.</p>
<p>Learn Python &amp; Django at <a target="_blank" href="https://django-tutorial.dev">django-tutorial.dev</a></p>
<h1 id="heading-common-mistakes">Common Mistakes:</h1>
<ol>
<li><h3 id="heading-vulnerable-secretkey"><strong>Vulnerable SECRET_KEY:</strong></h3>
<p> One of the prevalent mistakes I encounter is the exposure of the SECRET_KEY. This crucial piece of information should always be guarded with the utmost care.</p>
</li>
<li><h3 id="heading-vulnerable-apikey"><strong>Vulnerable API_KEY:</strong></h3>
<p> Similar to SECRET_KEY, API_KEYs are often left unprotected. This oversight can lead to potential security breaches, compromising the integrity of your project.</p>
</li>
<li><h3 id="heading-vulnerable-database"><strong>Vulnerable DATABASE:</strong></h3>
<p> Exposing database credentials is another pitfall. It's essential to shield this sensitive information from prying eyes to prevent unauthorized access.</p>
</li>
<li><h3 id="heading-using-class-based-views-never-use-it"><strong>Using Class Based Views (NEVER USE IT):</strong></h3>
<p> While not a security risk per se, It is Risking Yourself to Brain Damage just by it's Use or by someone else when they are trying to box you.<br /> NEVER USE CLASS BASED VIEW</p>
</li>
<li><h3 id="heading-vulnerable-debug-status"><strong>Vulnerable DEBUG status:</strong></h3>
<p> Keeping the DEBUG mode on in a production environment is a significant security flaw. This can expose sensitive information and open the door to potential exploits.</p>
</li>
<li><h3 id="heading-vulnerable-data"><strong>Vulnerable DATA:</strong></h3>
<p> Mishandling and exposing critical data within your project can have severe consequences. Proper precautions must be taken to ensure data security.</p>
</li>
</ol>
<h1 id="heading-preventing-mistakes">Preventing Mistakes</h1>
<p>To tackle these common mistakes, I recommend employing a robust solution – Python-decouple.</p>
<h3 id="heading-python-decouple"><strong>Python-decouple:</strong></h3>
<p>Python-decouple is a Django package that advocates for a strict separation of settings from code. The solution lies in creating a .env file housing crucial information such as SECRET_KEY, API_KEY, DEBUG status, SMTP credentials, and external database URLs. By utilizing the config(data_name) method, these values can be accessed from the .env file, ensuring a secure and modular approach.</p>
<h3 id="heading-why-not-just-use-environment-variables-and-the-osenviron-method-like-in-python">Why not just Use environment variables and the os.environ method like in python?</h3>
<p>Cause It will only return String. and we might need to get a Boolean or some other type of data and stop being so stupid.</p>
<p>example code for .env file:</p>
<pre><code class="lang-python"><span class="hljs-comment"># .env</span>
SECRET_KEY=my_super_secret_key
DEBUG=<span class="hljs-literal">True</span> 
<span class="hljs-comment"># Database</span>
DATABASE_URL=postgresql://your_db_user:your_db_password@localhost/your_db_name

<span class="hljs-comment"># Email settings</span>
EMAIL_HOST=your_email_host
EMAIL_PORT=your_email_port
EMAIL_USE_TLS=<span class="hljs-literal">True</span>
EMAIL_HOST_USER=your_email_username
EMAIL_HOST_PASSWORD=your_email_password
</code></pre>
<p>Example code for the settings.py:</p>
<pre><code class="lang-python"><span class="hljs-comment"># settings.py</span>

<span class="hljs-keyword">from</span> decouple <span class="hljs-keyword">import</span> config

<span class="hljs-comment"># SECURITY WARNING: keep the secret key used in production secret!</span>
SECRET_KEY = config(<span class="hljs-string">'SECRET_KEY'</span>)

<span class="hljs-comment"># SECURITY WARNING: don't run with debug turned on in production!</span>
DEBUG = config(<span class="hljs-string">'DEBUG'</span>, default=<span class="hljs-literal">False</span>, cast=bool)

<span class="hljs-comment"># Database</span>
<span class="hljs-comment"># https://docs.djangoproject.com/en/3.2/ref/settings/#databases</span>

DATABASES = {
    <span class="hljs-string">'default'</span>: config(<span class="hljs-string">'DATABASE_URL'</span>,cast = str),
}

<span class="hljs-comment"># Email settings</span>
EMAIL_BACKEND = <span class="hljs-string">'django.core.mail.backends.smtp.EmailBackend'</span>
EMAIL_HOST = config(<span class="hljs-string">'EMAIL_HOST'</span>)
EMAIL_PORT = config(<span class="hljs-string">'EMAIL_PORT'</span>, cast=int)
EMAIL_USE_TLS = config(<span class="hljs-string">'EMAIL_USE_TLS'</span>, default=<span class="hljs-literal">True</span>, cast=bool)
EMAIL_HOST_USER = config(<span class="hljs-string">'EMAIL_HOST_USER'</span>)
EMAIL_HOST_PASSWORD = config(<span class="hljs-string">'EMAIL_HOST_PASSWORD'</span>)
</code></pre>
<p>If You are Using the code from your github repo in production, then you need to either create a .env file inside of the root directory of your production environment.</p>
<h3 id="heading-how-does-it-work"><strong>How does it work?</strong></h3>
<p><em>Decouple</em> always searches for <em>Options</em> in this order:</p>
<ol>
<li><p>Environment variables;</p>
</li>
<li><p>Repository: ini or .env file;</p>
</li>
<li><p>Default argument passed to config.</p>
</li>
</ol>
<h3 id="heading-understanding-the-cast-argument"><strong>Understanding the CAST argument</strong></h3>
<p>By default, all values returned by decouple are strings, after all they are read from text files or the environment.</p>
<p>However, your Python code may expect some other value type, for example:</p>
<ul>
<li><p>Django’s DEBUG expects a boolean True or False.</p>
</li>
<li><p>Django’s EMAIL_PORT expects an integer.</p>
</li>
<li><p>Django’s ALLOWED_HOSTS expects a list of hostnames.</p>
</li>
<li><p>Django’s SECURE_PROXY_SSL_HEADER expects a tuple with two elements, the name of the header to look for and the required value.</p>
</li>
</ul>
<p>Did you really need to read this? Maybe you are slow...</p>
<p><strong>Implementation:</strong></p>
<ol>
<li><p>Create a .env file with sensitive data.</p>
</li>
<li><p>Use Python-decouple's config(data_name) method to access values.</p>
</li>
<li><p>Configure your version control system (Git) to ignore the .env file, preventing inadvertent exposure.</p>
</li>
</ol>
<p>By adopting Python-decouple and implementing a .env file, you fortify your project against several vulnerabilities in one fell swoop. This proactive approach not only enhances security but also fosters good development practices.</p>
<h1 id="heading-this-is-your-4900-steps-in-becoming-a-django-master-jr">This is your 4/900 Steps in becoming a Django Master jr.</h1>
]]></content:encoded></item><item><title><![CDATA[Integrate React with Django [NO API]]]></title><description><![CDATA[Introduction: As a Django enthusiast venturing into the world of frontend development, integrating React.js with Django can open up exciting possibilities for building dynamic and interactive web applications. In this article, we will explore how to ...]]></description><link>https://blog.django-tutorial.dev/django-reactjs</link><guid isPermaLink="true">https://blog.django-tutorial.dev/django-reactjs</guid><category><![CDATA[django master]]></category><category><![CDATA[Multiply and surrender]]></category><category><![CDATA[Django]]></category><category><![CDATA[django rest framework]]></category><category><![CDATA[DjangoRestFramework]]></category><category><![CDATA[django orm]]></category><category><![CDATA[General Programming]]></category><dc:creator><![CDATA[Nischal lamichhane]]></dc:creator><pubDate>Mon, 08 Jan 2024 08:54:42 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1704703875546/07d25fbb-06fb-4f11-937f-f96777f22cdf.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><em>Introduction:</em> As a Django enthusiast venturing into the world of frontend development, integrating React.js with Django can open up exciting possibilities for building dynamic and interactive web applications. In this article, we will explore how to seamlessly integrate React.js with Django using the django-reactjs package, empowering you to create modern and responsive web applications.</p>
<p><em>Understanding React.js and Django:</em> Before diving into the integration process, let's briefly understand the strengths of React.js and Django.</p>
<p>React.js is a JavaScript library for building user interfaces, particularly for single-page applications where updates occur frequently. It allows developers to create reusable UI components, making the code modular and easy to maintain. React's virtual DOM efficiently updates only the necessary components, optimizing performance.</p>
<p>On the other hand, Django is a high-level Python web framework known for its simplicity, flexibility, and scalability. It follows the Model-View-Controller (MVC) architectural pattern, promoting clean and organized code. Django excels in handling server-side logic, managing databases, and routing requests.</p>
<p>Learn Python &amp; Django at <a target="_blank" href="https://django-tutorial.dev">django-tutorial.dev</a></p>
<h2 id="heading-why-integrate-reactjs-with-django"><em>Why Integrate React.js with Django?</em></h2>
<p>Integrating React.js with Django leverages the strengths of both technologies. Django handles backend operations, such as database management, authentication, and routing, while React.js takes charge of the frontend, providing a responsive and interactive user interface.</p>
<p>This combination is particularly beneficial for creating complex applications where real-time updates and a seamless user experience are essential. The django-reactjs package streamlines the integration process, making it easier for developers to harness the power of both technologies.</p>
<p><em>Installing django-reactjs:</em> To get started, install the django-reactjs package using the following command:</p>
<pre><code class="lang-bash">pip install django-reactjs
</code></pre>
<p>Next, add 'react' to your <code>INSTALLED_APPS</code> in the <a target="_blank" href="http://settings.py"><code>settings.py</code></a> file:</p>
<pre><code class="lang-python">INSTALLED_APPS = [
    <span class="hljs-comment"># ...</span>
    <span class="hljs-string">'react'</span>,
]
</code></pre>
<p>Run migrations to apply the changes:</p>
<pre><code class="lang-bash">python manage.py migrate
</code></pre>
<p><em>Setting Up React Components:</em> Create a new folder, let's call it 'frontend,' to store your React components. Inside this folder, initialize a new React app using your preferred method, such as Create React App or manually setting up a project.</p>
<p>Once your React app is set up, you can start building components. Django-Reactjs provides a <code>{% react_component %}</code> template tag to render React components within your Django templates.</p>
<p><em>Creating Django Views:</em> To connect your Django backend with the React frontend, create views that will render your React components. In your <a target="_blank" href="http://views.py">views.py</a> file, import the necessary modules and use the <code>ReactView</code> class provided by Django-Reactjs.</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> django.shortcuts <span class="hljs-keyword">import</span> render
<span class="hljs-keyword">from</span> react.views <span class="hljs-keyword">import</span> ReactView

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyReactView</span>(<span class="hljs-params">ReactView</span>):</span>
    template_name = <span class="hljs-string">'index.html'</span>  <span class="hljs-comment"># Replace with your template name</span>
    component_name = <span class="hljs-string">'MyReactApp'</span>  <span class="hljs-comment"># Replace with your React component name</span>
</code></pre>
<p><em>Configuring URLs:</em> In your <a target="_blank" href="http://urls.py">urls.py</a> file, map the URL to the corresponding view.</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> MyReactView

urlpatterns = [
    path(<span class="hljs-string">'react-app/'</span>, MyReactView.as_view(), name=<span class="hljs-string">'react-app'</span>),
    <span class="hljs-comment"># Add other URLs as needed</span>
]
</code></pre>
<p><em>Rendering React Components:</em> Finally, in your Django template (e.g., index.html), use the <code>{% react_component %}</code> template tag to render your React component.</p>
<pre><code class="lang-plaintext">{% extends 'base.html' %}

{% block content %}
    &lt;div id="app"&gt;
        {% react_component 'MyReactApp' %}
    &lt;/div&gt;
{% endblock %}
</code></pre>
<p><em>Conclusion:</em> Integrating React.js with Django using the Django-Reactjs package is a powerful combination that allows you to build robust and modern web applications. By leveraging the strengths of both technologies, you can create a seamless user experience while benefiting from Django's backend capabilities. Experiment with different React components, explore additional features of Django-Reactjs, and take your web development skills to new heights. Happy coding!</p>
<h1 id="heading-the-django-reactjs-package-is-deprecated-goodluck-creating-an-api-now">The django-reactjs Package is Deprecated, 😜 Goodluck Creating an API now</h1>
]]></content:encoded></item><item><title><![CDATA[Understanding Django Context Processors:]]></title><description><![CDATA[Introduction:
Django, a powerful web framework for building web applications using Python, provides a variety of tools to simplify development tasks. One such tool that plays a crucial role in managing data across multiple views and templates is the ...]]></description><link>https://blog.django-tutorial.dev/django-context-processors</link><guid isPermaLink="true">https://blog.django-tutorial.dev/django-context-processors</guid><category><![CDATA[Multiply and surrender]]></category><category><![CDATA[Django]]></category><category><![CDATA[django master]]></category><category><![CDATA[General Programming]]></category><dc:creator><![CDATA[Nischal lamichhane]]></dc:creator><pubDate>Sun, 31 Dec 2023 13:19:51 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1704026572620/d0974038-a8ee-41bf-a744-731152a49280.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-introduction"><strong>Introduction:</strong></h1>
<p>Django, a powerful web framework for building web applications using Python, provides a variety of tools to simplify development tasks. One such tool that plays a crucial role in managing data across multiple views and templates is the Context Processor. In this guide, we'll explore what context processors are, how they work, and how to leverage them in Django projects.</p>
<p>Learn Python &amp; Django at <a target="_blank" href="https://django-tutorial.dev">django-tutorial.dev</a></p>
<h2 id="heading-prerequisites">Prerequisites:</h2>
<ol>
<li><p>Nepali Citizenship</p>
</li>
<li><p>Tax Clearance certificate</p>
</li>
<li><p>Daura-Suruwal (दौरा सुरुवाल)</p>
</li>
<li><p>Dhaka Topi</p>
</li>
<li><p>Nepali Flag</p>
</li>
</ol>
<h2 id="heading-what-is-a-context-processor"><strong>What is a Context Processor?</strong></h2>
<p>In Django, a context processor is a Python function that adds data to the context of every template rendered (like a बिचौलिया {middleman}). The context in Django refers to a dictionary-like object that stores variables accessible within a template.</p>
<pre><code class="lang-python"><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> TaskForm

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">createtask</span>(<span class="hljs-params">request</span>):</span>
    <span class="hljs-keyword">if</span> request.method == <span class="hljs-string">'POST'</span>:
        form = TaskForm(request.POST)

        <span class="hljs-keyword">if</span> form.is_valid():
            form.save()
            <span class="hljs-keyword">return</span> redirect(<span class="hljs-string">'home'</span>)
    <span class="hljs-keyword">else</span>:
        form = TaskForm()
        context={
            <span class="hljs-string">'form'</span>:form
        }
    <span class="hljs-keyword">return</span> render(request,<span class="hljs-string">'home/createtask.html'</span>,context)
</code></pre>
<p>The snippet is from the <a target="_blank" href="https://blog.nischallamichhane.com.np/creating-the-best-todo-app-with-the-django-master-pt2">Best TODO app with the Django Master</a>. In the<br /><code>render(request,'home/createtask.html',context)</code> line, 'context' is the context that we are<br />adding to the createtask.html template. Context processors allow you to inject additional data into this context, making it available to all templates across your project.</p>
<h2 id="heading-how-context-processors-work"><strong>How Context Processors Work</strong></h2>
<p>Context processors are executed every time a template is rendered. They run before the template is rendered, allowing you to include dynamic data in the context. Context processors are often used to include data that is common across multiple views or templates, eliminating the need to pass the same data in each view function.</p>
<p>Here's a step-by-step overview of how context processors work:</p>
<ol>
<li><p><strong>Creation of the Context:</strong> When a view function is called and a template is rendered, Django creates a context, which is essentially a dictionary containing variables.</p>
</li>
<li><p><strong>Context Processors Execution:</strong> Before the template is rendered, Django executes all registered context processors. These processors can add, modify, or remove variables from the context.</p>
</li>
<li><p><strong>Template Rendering:</strong> Once the context processors have executed, the updated context is passed to the template engine for rendering. The template can then access the variables in the context.</p>
</li>
</ol>
<h2 id="heading-creating-a-context-processor"><strong>Creating a Context Processor</strong></h2>
<p>Creating a context processor involves defining a Python function that adds data to the context. Follow these steps to create a basic context processor:</p>
<ol>
<li><p><strong>Create a Python file for Context Processors:</strong> Create a file named <code>context_processors.py</code> inside your Django app.</p>
</li>
<li><p><strong>Define the Context Processor Function:</strong> In <code>context_processors.py</code>, define a function that takes the request as an argument and returns a dictionary containing the data you want to add to the context. For example:</p>
<pre><code class="lang-python"> <span class="hljs-comment"># myapp/context_processors.py</span>
 <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">CustomDataNameGoesInHereAreYouBlindBro</span>(<span class="hljs-params">request</span>):</span>
     <span class="hljs-keyword">return</span> {<span class="hljs-string">'slogan'</span>: <span class="hljs-string">'KP OLI murdabad'</span>}
</code></pre>
</li>
<li><p><strong>Register the Context Processor:</strong> In your Django project settings (<code>settings.py</code>), add the path to the context processor function to the <code>context_processors</code> list. It should look like:</p>
<pre><code class="lang-python"> <span class="hljs-comment"># settings.py</span>
 TEMPLATES = [
     {
         <span class="hljs-string">'OPTIONS'</span>: {
             <span class="hljs-string">'context_processors'</span>: [
                 <span class="hljs-string">'myapp.context_processors.CustomDataNameGoesInHereAreYouBlindBro'</span>,
             ],
         },
     },
 ]
</code></pre>
<p> Ensure that you replace <code>'myapp.context_processors.CustomDataNameGoesInHereAreYouBlindBro'</code> with the correct path to your context processor and the correct function name.</p>
</li>
</ol>
<h2 id="heading-using-context-variables-in-templates"><strong>Using Context Variables in Templates</strong></h2>
<p>Once the context processor is registered, you can use the added variables in your templates. For example, if the context processor adds a variable named <code>slogan</code>, you can access it in a template like this:</p>
<pre><code class="lang-haml">&lt;!-- bebsite.html --&gt;
&lt;p&gt;{{ slogan }}&lt;/p&gt;
</code></pre>
<h2 id="heading-common-use-cases-for-context-processors"><strong>Common Use Cases for Context Processors</strong></h2>
<p>Context processors can be employed for various purposes, including:</p>
<ol>
<li><p><strong>Global Settings:</strong> Include global settings that are applicable to all templates, such as site configuration or user preferences.</p>
</li>
<li><p><strong>User Authentication:</strong> Add information about the current user to the context, making it accessible in templates without explicitly passing it in each view.</p>
</li>
<li><p><strong>Dynamic Navigation:</strong> Include data for dynamic navigation menus that need to be consistent across multiple pages.</p>
</li>
<li><p><strong>SEO Metadata:</strong> Inject SEO-related information, such as page titles or meta tags, into the context for better search engine optimization.</p>
</li>
</ol>
<h2 id="heading-conclusion"><strong>Conclusion</strong></h2>
<p>Context processors are a powerful tool in the Django framework, enabling developers to manage and share data seamlessly across different views and templates. By understanding how context processors work and leveraging them effectively, you can streamline your code and enhance the consistency and maintainability of your Django projects. You can experiment with context processors in your projects to discover the flexibility and convenience they bring to web development with Django, but you won't go far.</p>
<h2 id="heading-this-is-your-step-3900-of-becoming-a-django-master-jr">This is your step 3/900 of becoming a Django Master jr.</h2>
<p>In The Next Blog we will be discussing about Migrations in Django</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1704028548192/881341b8-1624-4668-93f2-493ec2457246.jpeg" alt class="image--center mx-auto" /></p>
<p>Thanks to <a target="_blank" href="https://github.com/kushalsubedi/">Kushal subedi</a> for article topic</p>
]]></content:encoded></item><item><title><![CDATA[Understanding Static Files in Django]]></title><description><![CDATA[Django, a high-level Python web framework, empowers developers to build robust and dynamic web applications. As you embark on your journey to become a Django Master, it's crucial to grasp the concept of static files within the framework.
Learn Python...]]></description><link>https://blog.django-tutorial.dev/django-static-files</link><guid isPermaLink="true">https://blog.django-tutorial.dev/django-static-files</guid><category><![CDATA[Multiply and surrender]]></category><category><![CDATA[django master]]></category><category><![CDATA[Django]]></category><category><![CDATA[General Programming]]></category><dc:creator><![CDATA[Nischal lamichhane]]></dc:creator><pubDate>Thu, 28 Dec 2023 08:28:14 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1703751986944/46571c93-9373-414d-a783-759050817d1b.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Django, a high-level Python web framework, empowers developers to build robust and dynamic web applications. As you embark on your journey to become a Django Master, it's crucial to grasp the concept of static files within the framework.</p>
<p>Learn Python &amp; Django at <a target="_blank" href="https://django-tutorial.dev">django-tutorial.dev</a></p>
<h2 id="heading-what-are-static-files"><strong>What are Static Files?</strong></h2>
<p>Static files in Django refer to assets that don't change during the execution of a web application. These can include stylesheets (CSS), JavaScript files, images, and other resources that contribute to the overall look and feel of your site. Unlike dynamic content generated on-the-fly, static files remain constant, providing a consistent user experience.</p>
<h2 id="heading-the-role-of-static-files"><strong>The Role of Static Files</strong></h2>
<p>Static files play a vital role in enhancing the aesthetics and functionality of a web application. They contribute to the user interface, making it visually appealing and interactive. For instance, CSS stylesheets determine the layout and presentation of HTML elements, while JavaScript files add dynamic behavior to the client-side, enabling features like form validation or real-time updates.</p>
<h2 id="heading-managing-static-files-in-django"><strong>Managing Static Files in Django</strong></h2>
<p>Django simplifies the handling of static files through the <code>django.contrib.staticfiles</code> app. To get started, ensure that <code>'django.contrib.staticfiles'</code> is included in the <code>INSTALLED_APPS</code> setting of your project.</p>
<h3 id="heading-1-directory-structure"><strong>1. Directory Structure</strong></h3>
<p>Create a <code>static</code> directory within your Django app or project to organize static files. Django follows a convention over configuration approach, so placing static files in this directory ensures they are recognized by the framework.</p>
<pre><code class="lang-plaintext">your_app/
|-- static/
|   |-- your_app/
|       |-- css/
|       |-- js/
|       |-- img/
</code></pre>
<h3 id="heading-2-configuring-static-files"><strong>2. Configuring Static Files</strong></h3>
<p>In your project's settings, define the <code>STATIC_URL</code> and <code>STATICFILES_DIRS</code> settings:</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>
<p><code>STATIC_URL</code> specifies the base URL for serving static files, while <code>STATICFILES_DIRS</code> points to the location of your static files.</p>
<h3 id="heading-3-using-static-files-in-templates"><strong>3. Using Static Files in Templates</strong></h3>
<p>In your HTML templates, load static files using the <code>{% static %}</code> template tag:</p>
<pre><code class="lang-haml">&lt;!-- example.html --&gt;

&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
    &lt;link rel="stylesheet" href="{% static 'your_app/css/style.css' %}"&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;!-- Your HTML content here --&gt;
    &lt;script src="{% static 'your_app/js/script.js' %}"&gt;&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>
<h3 id="heading-4-serving-static-files-in-django"><strong>4. Serving Static Files in Django:</strong></h3>
<p>In your template you've used the <code>static</code> tag. but Django Server doesn't know what it means. so We need to make sure the Static Files are being served one way or another. There are Two ways to serve Static Files in Django.</p>
<h3 id="heading-1development-environment-debugtrue"><strong>1.Development Environment (DEBUG=True):</strong></h3>
<p>In your <a target="_blank" href="http://settings.py"><code>settings.py</code></a> for development:</p>
<pre><code class="lang-python"><span class="hljs-comment"># settings.py</span>

DEBUG = <span class="hljs-literal">True</span>

<span class="hljs-comment"># Static files (CSS, JavaScript, images)</span>
STATIC_URL = <span class="hljs-string">'/static/'</span>
STATICFILES_DIRS = [
    BASE_DIR / <span class="hljs-string">"static"</span>,
]
</code></pre>
<p>With <code>DEBUG=True</code>, Django's built-in development server automatically handles serving static files from the <code>static</code> directory of your apps.</p>
<p>In your template, use the <code>{% static %}</code> tag to reference static files:</p>
<pre><code class="lang-plaintext">&lt;!-- example.html --&gt;

&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
    &lt;link rel="stylesheet" href="{% static 'your_app/css/style.css' %}"&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;!-- Your HTML content here --&gt;
    &lt;img src="{% static 'your_app/img/example.jpg' %}" alt="Example Image"&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>
<h3 id="heading-2-production-environment-debugfalse"><strong>2. Production Environment (DEBUG=False):</strong></h3>
<p>In a production environment, you should use a dedicated web server like Nginx or Apache to serve static files for better performance. You may also consider using WhiteNoise as middleware.</p>
<p>In your <a target="_blank" href="http://settings.py"><code>settings.py</code></a> for production:</p>
<pre><code class="lang-python"><span class="hljs-comment">#settings.py</span>

DEBUG = <span class="hljs-literal">False</span>

<span class="hljs-comment"># Static files (CSS, JavaScript, images)</span>
STATIC_URL = <span class="hljs-string">'/static/'</span>
STATIC_ROOT = BASE_DIR / <span class="hljs-string">"staticfiles"</span>
</code></pre>
<p>Before deploying, collect static files:</p>
<pre><code class="lang-bash">
python manage.py collectstatic
</code></pre>
<p>This command gathers static files from each app and places them in the <code>STATIC_ROOT</code> directory.</p>
<p>Configure your production web server (e.g., Nginx) to serve static files directly. For example, in Nginx:</p>
<pre><code class="lang-nginx"><span class="hljs-attribute">location</span> /static/ {
    <span class="hljs-attribute">alias</span> /path/to/your/staticfiles/;
}
</code></pre>
<p>Adjust the path accordingly based on your project structure.</p>
<p>By configuring static file serving appropriately for both development and production, you ensure a smooth delivery of static assets in your Django application.</p>
<p>Additionally You can use Middleware inside of Django to serve the Static Files, read about it below:</p>
<h2 id="heading-middleware-for-serving-static-files-in-production"><strong>Middleware for Serving Static Files in Production</strong></h2>
<p>WhiteNoise is a great middleware for serving static files efficiently in a Django application. It's particularly useful for simplicity and ease of integration, making it an excellent choice, especially for smaller projects or when you want a straightforward solution. Here's how you can configure WhiteNoise as middleware in your Django project:</p>
<h3 id="heading-install-whitenoise"><strong>Install WhiteNoise</strong></h3>
<p>First, you need to install the <code>whitenoise</code> package. You can do this using <code>pip</code>:</p>
<pre><code class="lang-bash">pip install whitenoise
</code></pre>
<h3 id="heading-update-middleware-and-static-files-configuration"><strong>Update Middleware and Static Files Configuration</strong></h3>
<ol>
<li><p>Add <code>'whitenoise.middleware.WhiteNoiseMiddleware',</code> to the <code>MIDDLEWARE</code> setting in your <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>

 MIDDLEWARE = [
     <span class="hljs-comment"># Other middleware entries</span>
     <span class="hljs-string">'whitenoise.middleware.WhiteNoiseMiddleware'</span>,
     <span class="hljs-comment"># ...</span>
 ]
</code></pre>
</li>
<li><p>Configure WhiteNoise to serve static files by adding the following settings:</p>
<pre><code class="lang-python"> <span class="hljs-comment"># settings.py</span>

 <span class="hljs-comment"># Enable WhiteNoise for serving static files</span>
 STATIC_URL = <span class="hljs-string">'/static/'</span>
 STATICFILES_STORAGE = <span class="hljs-string">'whitenoise.storage.CompressedManifestStaticFilesStorage'</span>
</code></pre>
<p> The <code>STATICFILES_STORAGE</code> setting is crucial for telling Django to use WhiteNoise's storage backend for handling static files.</p>
</li>
</ol>
<h3 id="heading-adjusting-url-patterns"><strong>Adjusting URL Patterns</strong></h3>
<p>Now, you can simplify your <a target="_blank" href="http://urls.py"><code>urls.py</code></a> by removing the manual addition of static files using <code>urlpatterns += static(...)</code>, as WhiteNoise will take care of this for you.</p>
<pre><code class="lang-python">pythonCopy code<span class="hljs-comment"># 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

urlpatterns = [
    path(<span class="hljs-string">'admin/'</span>, admin.site.urls),
    <span class="hljs-comment"># Your other URL patterns go here</span>
]
</code></pre>
<h3 id="heading-collect-static-files"><strong>Collect Static Files</strong></h3>
<p>Ensure you collect static files before deploying your application:</p>
<pre><code class="lang-bash">python manage.py collectstatic
</code></pre>
<h3 id="heading-conclusion"><strong>Conclusion</strong></h3>
<p>By integrating WhiteNoise as middleware in your Django project, you benefit from a straightforward and efficient solution for serving static files in production. This not only simplifies your configuration but also enhances the performance of your application. As you continue your Django development journey, understanding and utilizing tools like WhiteNoise contribute to building robust and scalable web applications.</p>
<h2 id="heading-this-is-your-2900-step-in-becoming-the-django-master">This is your 2/900 step in becoming the Django Master</h2>
]]></content:encoded></item><item><title><![CDATA[Creating the Best TODO app With the Django Master [pt.3]]]></title><description><![CDATA[This is the Third Part of multipart Blog, in this Blog, we will be Looking at the T of MVT architecture of Django.
What is T?
T stands for Templates, a Template in Django is a Html File that is used to Generate a GUI for Average stupid user that cant...]]></description><link>https://blog.django-tutorial.dev/creating-the-best-todo-app-with-the-django-master-pt3</link><guid isPermaLink="true">https://blog.django-tutorial.dev/creating-the-best-todo-app-with-the-django-master-pt3</guid><category><![CDATA[Django]]></category><category><![CDATA[DjangoRestFramework]]></category><category><![CDATA[django master]]></category><category><![CDATA[General Programming]]></category><category><![CDATA[Multiply and surrender]]></category><dc:creator><![CDATA[Nischal lamichhane]]></dc:creator><pubDate>Wed, 27 Dec 2023 17:08:42 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1703698760072/1cf056af-8923-4ea5-9c7f-8033caf497c1.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-this-is-the-third-part-of-multipart-blog-in-this-blog-we-will-be-looking-at-the-t-of-mvt-architecture-of-django">This is the Third Part of multipart Blog, in this Blog, we will be Looking at the T of MVT architecture of Django.</h3>
<h2 id="heading-what-is-t">What is T?</h2>
<p>T stands for Templates, a Template in Django is a Html File that is used to Generate a GUI for Average stupid user that cant read the console. Templates are written in Templates directory that can be either in Root directory or the App directory and are rendered by views as a response to specific URLs in urls.py.</p>
<p>We will be diving into template Inheritance Directly Like a Sigma</p>
<ol>
<li><p>Create a Templates directory in the root directory of the project</p>
</li>
<li><p>Create a 'base.html' file in this directory. we will be inheriting this html file</p>
</li>
<li><p>Create another directory named includes inside of the templates directory. Shit like Sidebar, Header, Footer and more site-wide components are kept in that directory. You will Put header.html in this directory</p>
</li>
<li><p>Create a directory named 'home' inside templates directory and create an 'index.html' and 'createtask.html' files. The 'home' directory will help us organize our templates.</p>
</li>
<li><p>If you did everything right, which I highly doubt. This is what your directory structure should look like</p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1703665629360/86753179-9f46-47f9-b5a8-6516cb6a33c9.png" alt class="image--center mx-auto" /></p>
</li>
</ol>
<h2 id="heading-shit-to-read">SHIT to Read:</h2>
<p>Django Uses JINJA templating Engine for template rendering. Read about it here:<br /><a target="_blank" href="https://jinja.palletsprojects.com/en/3.1.x/">BORING SHIT</a></p>
<h2 id="heading-how-it-works">How it Works:</h2>
<p>In Django the Templates can be inherited, included and more shit like this. Most Rudimentary thing in all of these is Creating Blocks.<br />we will write base.html and then we will inherit base.html in all other pages and just change the content body and nothing else following DRY concept.</p>
<h2 id="heading-headerhtml">Header.html:</h2>
<pre><code class="lang-haml">&lt;nav class="navbar navbar-expand-sm navbar-light bg-success"&gt;
    &lt;div class="container-fluid"&gt;
        &lt;a class="navbar-brand" href="#"&gt;To-Do App&lt;/a&gt;
        &lt;button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarID"
            aria-controls="navbarID" aria-expanded="false" aria-label="Toggle navigation"&gt;
            &lt;span class="navbar-toggler-icon"&gt;&lt;/span&gt;
        &lt;/button&gt;
        &lt;div class="collapse navbar-collapse" id="navbarID"&gt;
            &lt;div class="navbar-nav"&gt;
                &lt;a class="nav-link " aria-current="page" href="{% url "home" %}"&gt;Home&lt;/a&gt;
            &lt;/div&gt;
            &lt;div class="navbar-nav"&gt;
                &lt;a class="nav-link " aria-current="page" href="{% url "createtask" %}"&gt;Add a Task&lt;/a&gt;
            &lt;/div&gt;
        &lt;/div&gt;
    &lt;/div&gt;
&lt;/nav&gt;
</code></pre>
<p><strong>href="{% url "home" %}"</strong> will be converted into <strong>href="/"</strong><br /><strong>href="{% url "createtask" %}"</strong> will be converted into <strong>href="/createtask/"</strong><br />This all happens dynamically Thanks to Jinja Templating engine</p>
<h2 id="heading-basehtml">Base.html:</h2>
<pre><code class="lang-haml">&lt;!doctype html&gt;
&lt;html lang="en"&gt;
    &lt;head&gt;
        &lt;title&gt; Todo|{% block title %}Basefile{% endblock title %}&lt;/title&gt;
        &lt;!-- Required meta tags --&gt;
        &lt;meta charset="utf-8" /&gt;
        &lt;meta
            name="viewport"
            content="width=device-width, initial-scale=1, shrink-to-fit=no"
<span class="hljs-comment">        /&gt;</span>

        &lt;!-- Bootstrap CSS v5.2.1 --&gt;
        &lt;link
            href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css"
            rel="stylesheet"
            integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN"
            crossorigin="anonymous"
<span class="hljs-comment">        /&gt;</span>
    &lt;/head&gt;

    &lt;body&gt;
            {% include "includes/header.html" %}
        &lt;main&gt;
            {% block content %}{% endblock content %}
        &lt;/main&gt;
        &lt;footer&gt;

        &lt;/footer&gt;
        &lt;!-- Bootstrap JavaScript Libraries --&gt;
        &lt;script
            src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.8/dist/umd/popper.min.js"
            integrity="sha384-I7E8VVD/ismYTF4hNIPjVp/Zjvgyol6VFvRkX/vR+Vc4jQkC+hVqc2pM8ODewa9r"
            crossorigin="anonymous"
        &gt;&lt;/script&gt;

        &lt;script
            src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.min.js"
            integrity="sha384-BBtl+eGJRgqQAUMxJ7pMwbEyER4l1g+O15P+16Ep7Q9Q+zqX6gSbd85u4mG4QzX+"
            crossorigin="anonymous"
        &gt;&lt;/script&gt;
    &lt;/body&gt;
&lt;/html&gt;
</code></pre>
<p>The <strong>{% block title %}Basefile{% endblock title %}</strong> is called a Block. If we inherit this<br />file, we can replace the text "Basefile" with a single line of code and no repeating html code.</p>
<p>The <strong>{% include "includes/header.html" %}</strong> is called a Include. It is similar to inheriting but we can't change any content of the Parent template easily. We are including header for our site in our base.html in this case.</p>
<h2 id="heading-indexhtml">Index.html:</h2>
<pre><code class="lang-haml">{% extends "base.html" %}

{% block content %}
    &lt;div
        class="container-md"
    &gt;
    &lt;div
        class="table-responsive-md"
    &gt;
        &lt;table
            class="table table-striped-columns table-hover table-borderless table-primary align-middle"
        &gt;
            &lt;thead class="table-light"&gt;
                &lt;caption&gt;
                    Task List
                &lt;/caption&gt;
                &lt;tr&gt;
                    &lt;th&gt;Task ID&lt;/th&gt;
                    &lt;th&gt;Task &lt;/th&gt;
                    &lt;th&gt;Expires on&lt;/th&gt;
                    &lt;th&gt;Status&lt;/th&gt;
                    &lt;th&gt;Actions&lt;/th&gt;
                &lt;/tr&gt;
            &lt;/thead&gt;
            &lt;tbody class="table-group-divider"&gt;
                {% for task in tasks %}
                &lt;tr class="table-primary"&gt;
                    &lt;td scope="row"&gt;{{task.id}}&lt;/td&gt;
                    &lt;td&gt;{{task.title}}&lt;/td&gt;
                    &lt;td&gt;{% if task.expired %}
                        Task has expired.
                        {% else %}
                        {{task.expires}}
                        {% endif %}&lt;/td&gt;
                    &lt;td&gt;
                        {% if task.is_complete %}
                        Task Completed
                        {% else %}
                        Task Pending
                        {% endif %}
                    &lt;/td&gt;
                    &lt;td&gt;
                        {% if task.is_complete %}
                        &lt;a class="btn btn-danger" href = {% url 'togglestatus' task_id=task.id %} &gt; Mark as incomplete&lt;/a&gt;
                        {% else %}
                        &lt;a  class ="btn btn-success" href = {% url 'togglestatus' task_id=task.id %} &gt; Mark as Complete&lt;/a&gt;
                        {% endif %}
                    &lt;/td&gt;
                &lt;/tr&gt;
                {% endfor %}
            &lt;/tbody&gt;
            &lt;tfoot&gt;

            &lt;/tfoot&gt;
        &lt;/table&gt;
    &lt;/div&gt;

    &lt;/div&gt;

{% endblock content %}
</code></pre>
<p>The <strong>{% extends "base.html" %}</strong> is what's inheriting the base.html template. now we can change just what's inside of the <strong>{% block content %}{% endblock content %}</strong> and <strong>{% block title %}{% endblock title %}</strong> that we wrote on base.html file.</p>
<h2 id="heading-createtaskhtml">Createtask.html:</h2>
<pre><code class="lang-haml">{% extends "base.html" %}

{% block content %}
&lt;div class="container"&gt;
&lt;form class=" needs-validation form-control" novalidate method="POST"&gt;
    {% csrf_token %}
  {{form.as_p}}
    &lt;button class="btn btn-success" type="submit"&gt;Submit form&lt;/button&gt;
&lt;/form&gt;
&lt;/div&gt;
{% endblock content %}
</code></pre>
<p>The {% csrf_token %} is required by default on every post request. CSRF stands for Cross Site Request Forgery. only Nerds get deep into it. We will just use the csrf_token tag.</p>
<h3 id="heading-for-stupid-people">For Stupid People:</h3>
<p><strong>None of the shit inside {{ }} ,{% %} will be rendered on the response, website.</strong> It simply is used for Logic part for the engine.<br />{% tag %} is called a tag.<br />{{ variable }} is called a variable.</p>
<h1 id="heading-how-to-run-the-server">How to RUN the Server:</h1>
<ol>
<li><p>Open console.</p>
</li>
<li><p>Go to the directory that has manage.py file.</p>
</li>
<li><pre><code class="lang-python">   py manage.py makemigrations
   py manage.py migrate
</code></pre>
</li>
<li><pre><code class="lang-python">   py manage.py runserver
</code></pre>
<p> GOTO your Microsoft EDGE browser. If you're using any other browser, YOU CANNOT BE A DJANGO MASTER.</p>
</li>
</ol>
<h3 id="heading-this-concludes-the-multipart-blog-creating-the-best-todo-app-with-the-django-master-3-pts"><strong>This</strong> Concludes the Multipart BLOG Creating the Best TODO app With the Django Master [3 pts]</h3>
]]></content:encoded></item><item><title><![CDATA[Creating the Best TODO app With the Django Master [pt.2]]]></title><description><![CDATA[This is the second Part of multipart Blog, in this Blog, we will be Looking at the V of MVT architecture of Django.
What is V?
V stands for Views, a View in Django is a function that is used to Generate a Response for a request. Views are written in ...]]></description><link>https://blog.django-tutorial.dev/creating-the-best-todo-app-with-the-django-master-pt2</link><guid isPermaLink="true">https://blog.django-tutorial.dev/creating-the-best-todo-app-with-the-django-master-pt2</guid><category><![CDATA[Django]]></category><category><![CDATA[General Programming]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[Multiply and surrender]]></category><category><![CDATA[django master]]></category><dc:creator><![CDATA[Nischal lamichhane]]></dc:creator><pubDate>Wed, 27 Dec 2023 08:12:17 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1703698799217/642312e7-2d2a-4e1e-bc27-e968579a110e.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-this-is-the-second-part-of-multipart-blog-in-this-blog-we-will-be-looking-at-the-v-of-mvt-architecture-of-django">This is the second Part of multipart Blog, in this Blog, we will be Looking at the V of MVT architecture of Django.</h3>
<h2 id="heading-what-is-v">What is V?</h2>
<p>V stands for Views, a View in Django is a function that is used to Generate a Response for a request. Views are written in views.py and are mapped to specific URLs in urls.py.</p>
<ol>
<li><p>Create Urls.py inside your "home" directory.</p>
</li>
<li><p>Your Functions will be Written in the views.py</p>
</li>
<li><p>Create a Forms.py inside your "home" directory. Your directory Structure should look like this:</p>
</li>
<li><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1702559731402/f73668b4-fbaa-4856-9e03-1c8ea5cf589e.png" alt class="image--center mx-auto" /></p>
<p> Create a class named "TaskForm" inside your forms.py like so</p>
<pre><code class="lang-python"> <span class="hljs-keyword">from</span> django.forms <span class="hljs-keyword">import</span> ModelForm
 <span class="hljs-keyword">from</span> .models <span class="hljs-keyword">import</span> Task

 <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">TaskForm</span>(<span class="hljs-params">ModelForm</span>):</span>
     <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Meta</span>:</span>
         model = Task
         fields=[<span class="hljs-string">'title'</span>,<span class="hljs-string">'expires'</span>]
</code></pre>
</li>
<li><p>Create a function named createtask that takes request as a parameter, saves the TaskForm if the request method is POST else just returns some stuff like shown. all of the .html files we are rendering to are called templates which will be the topic of the next blog from the Django Master</p>
<pre><code class="lang-python"> <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> TaskForm

 <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">createtask</span>(<span class="hljs-params">request</span>):</span>
     <span class="hljs-keyword">if</span> request.method == <span class="hljs-string">'POST'</span>:
         form = TaskForm(request.POST)

         <span class="hljs-keyword">if</span> form.is_valid():
             form.save()
             <span class="hljs-keyword">return</span> redirect(<span class="hljs-string">'home'</span>)
     <span class="hljs-keyword">else</span>:
         form = TaskForm()
         context={
             <span class="hljs-string">'form'</span>:form
         }
     <span class="hljs-keyword">return</span> render(request,<span class="hljs-string">'home/createtask.html'</span>,context)
</code></pre>
</li>
<li><p>Create a function named togglestatus that will toggle the Boolean value in the "complete" field of Task Model like so</p>
<pre><code class="lang-python"> <span class="hljs-keyword">from</span> django.shortcuts <span class="hljs-keyword">import</span> redirect
 <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">togglestatus</span>(<span class="hljs-params">request,task_id</span>):</span>
     task = Task.objects.get(id=task_id)
     <span class="hljs-keyword">if</span> task.complete==<span class="hljs-literal">True</span>:
         task.complete=<span class="hljs-literal">False</span>
     <span class="hljs-keyword">else</span>:
         task.complete=<span class="hljs-literal">True</span>
     task.save()
     <span class="hljs-keyword">return</span> redirect(<span class="hljs-string">'home'</span>)
</code></pre>
</li>
<li><p>Create list called urlpatterns and map the function to the routes like this.</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> .<span class="hljs-keyword">import</span> views

 urlpatterns = [
     path(<span class="hljs-string">''</span>,views.index,name=<span class="hljs-string">'home'</span>),
     path(<span class="hljs-string">'createtask/'</span>,views.createtask,name=<span class="hljs-string">'createtask'</span>),
     path(<span class="hljs-string">'togglestatus/&lt;int:task_id&gt;/'</span>,views.togglestatus,name=<span class="hljs-string">'togglestatus'</span>)
 ]
</code></pre>
<p> The name property in the Path() will help us immensely in Templates by just having to remember the name of the URL instead of the whole path. we will use this name by using the {% url 'name' %} in the next Blog</p>
<p> In the next Blog we will see how the T in MVT architecture works in Django. Till Then, Keep Misinforming People</p>
</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[Creating the Best TODO app With the Django Master [pt.1]]]></title><description><![CDATA[This will be a Multipart Blog, this part we will be looking at the M of MVT architecture which is Models.
I will dominate Django Very Hard with No Mercy. In this Blog we are going to create a Database to store our Todo tasks in and perform CRUD opera...]]></description><link>https://blog.django-tutorial.dev/creating-the-best-todo-app-with-the-django-master-pt1</link><guid isPermaLink="true">https://blog.django-tutorial.dev/creating-the-best-todo-app-with-the-django-master-pt1</guid><category><![CDATA[django master]]></category><category><![CDATA[Django]]></category><category><![CDATA[Multiply and surrender]]></category><category><![CDATA[django rest framework]]></category><category><![CDATA[General Programming]]></category><dc:creator><![CDATA[Nischal lamichhane]]></dc:creator><pubDate>Wed, 13 Dec 2023 07:58:34 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1703699025545/ab110c22-901d-45f1-926d-a62d44ebdca2.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-this-will-be-a-multipart-blog-this-part-we-will-be-looking-at-the-m-of-mvt-architecture-which-is-models">This will be a Multipart Blog, this part we will be looking at the M of MVT architecture which is Models.</h3>
<p>I will dominate Django Very Hard with No Mercy. In this Blog we are going to create a Database to store our Todo tasks in and perform CRUD operations in that data with the help of Django's default Admin Panel</p>
<ol>
<li><p>Create virtual environment.</p>
</li>
<li><p>Activate the virtual environment.</p>
</li>
<li><p>Install Django in the environment.</p>
</li>
<li><p>Create a Django Project named Todo.</p>
</li>
<li><p>run the Django server</p>
</li>
<li><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1702452152375/c6ae33d7-f155-4b4a-8e30-ee709c9dba3b.png" alt class="image--center mx-auto" /></p>
<p> Create an app named home &amp; add home to the installed apps list in settings.py</p>
<pre><code class="lang-python"> django-admin startapp home
</code></pre>
</li>
<li><p>Create the Model (database) for the Task</p>
<pre><code class="lang-python"> <span class="hljs-keyword">from</span> django.db <span class="hljs-keyword">import</span> models

 <span class="hljs-comment"># Create your models here.</span>

 <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Task</span>(<span class="hljs-params">models.Model</span>):</span>
     title = models.CharField(max_length=<span class="hljs-number">200</span>)
     complete = models.BooleanField(default=<span class="hljs-literal">False</span>)
     created = models.DateTimeField(auto_now_add=<span class="hljs-literal">True</span>)
     expires = models.DateTimeField(auto_now_add=<span class="hljs-literal">False</span>,blank=<span class="hljs-literal">True</span>,null=<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

<span class="hljs-meta">     @property </span>
     <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">is_complete</span>(<span class="hljs-params">self</span>):</span>
         <span class="hljs-keyword">return</span> self.complete
</code></pre>
</li>
<li><p>Add the Model in the Admin Panel by adding it to the admin.py file</p>
<pre><code class="lang-python"> <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> Task

 <span class="hljs-comment"># Register your models here.</span>

 admin.site.register(Task)
</code></pre>
</li>
<li><p>Make migrations, migrate and Create superuser</p>
<pre><code class="lang-python"> py manage.py makemigrations
 py manage.py migrate
 py manage.py createsuperuser
</code></pre>
</li>
<li><p>Run the Server and go to admin panel.</p>
</li>
<li><pre><code class="lang-python">py manage.py runserver 
goto https://localhost:<span class="hljs-number">8000</span>/admin
</code></pre>
</li>
<li><p>login to admin panel and you should see the Tasks under the Home section. Click on Tasks and do CRUD operations.</p>
</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1702453967109/f3f57a74-3a16-4b5c-bec3-2aaaace25b27.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-congratulations-youve-successfully-created-the-database-for-the-best-todo-app-ever">Congratulations! You've successfully created the database for The Best Todo app ever.</h2>
<h2 id="heading-youve-completed-2900-steps-of-becoming-a-django-master">You've completed 2/900 steps of becoming a Django Master</h2>
<p>In next Blog, we'll be looking at the V part of MVT architecture</p>
]]></content:encoded></item><item><title><![CDATA[Getting Started with Django from Scratch]]></title><description><![CDATA[You'll need these prerequisites:

Brain

Computer (with Windows in it)

Python-the programming language, PIP

Python (optional only for people with passion)

Access to clean drinking water, edible food, breathable air, Clothes, body, Doctorate in Com...]]></description><link>https://blog.django-tutorial.dev/getting-started-with-django-from-scratch</link><guid isPermaLink="true">https://blog.django-tutorial.dev/getting-started-with-django-from-scratch</guid><category><![CDATA[Multiply and surrender]]></category><category><![CDATA[Django]]></category><category><![CDATA[General Programming]]></category><category><![CDATA[Python]]></category><dc:creator><![CDATA[Nischal lamichhane]]></dc:creator><pubDate>Wed, 13 Dec 2023 07:12:33 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1702474910123/3d6d7119-f5a9-4cd6-bd42-6772151e3128.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>You'll need these prerequisites:</p>
<ul>
<li><p>Brain</p>
</li>
<li><p>Computer (with Windows in it)</p>
</li>
<li><p>Python-the programming language, PIP</p>
</li>
<li><p>Python (optional only for people with passion)</p>
</li>
<li><p>Access to clean drinking water, edible food, breathable air, Clothes, body, Doctorate in Computer Science, 30Years of Experience as a 19-year-old or (You need to be a Django Master like me).</p>
</li>
<li><p>Browser in your Computer</p>
</li>
<li><p>Keyboard</p>
</li>
<li><p>Keyboard Switches</p>
</li>
<li><p>Keycaps</p>
</li>
<li><p>Mouse</p>
</li>
<li><p>Mouse Buttons</p>
</li>
<li><p>Mouse Pad</p>
</li>
<li><p>Electricity</p>
</li>
<li><p>Connection to Internet</p>
</li>
<li><p>a Life (optional)</p>
</li>
<li><p>Power Cord</p>
</li>
<li><p>LED Lights (very Important)</p>
</li>
<li><p>Learn the Django Docs byheart 3 times (can't be skipped)</p>
</li>
</ul>
<h1 id="heading-installing-django">Installing Django</h1>
<p>Whenever You are Trying to use the Best Web Framework there is a.k.a. Django. Our Project may depend on some certain lower tier packages to run. and sometimes those packages get updated to higher versions that could cause a project already in deployment to crash. and when we do need to Maintain/add a feature to a project already in Production. we need to know all the packages used and their versions. which makes 1 developer working with more than 1 project a nightmare.</p>
<p>PS: I never Have any problem like this because I am the Django Master.</p>
<p>To resolve this possible future issue, we create Virtual environment to develop our project in, and we will use fancy commands to create a requirements.txt file to let our deployment server know what packages are required to run the project.</p>
<p>You need to type python -m venv &lt;virtualenv name&gt; in console of your choice. and<br />&lt;virtualenv name&gt;/scripts/activate to activate the Virtual Environment. Below is an example for creating a virtual environment in python named "theusernamedvirtualenvironmentnamegoesinhere"</p>
<pre><code class="lang-python">python -m venv theusernamedvirtualenvironmentnamegoesinhere

theusernamedvirtualenvironmentnamegoesinhere\scripts\activate
</code></pre>
<p>You should see this sort of screen after you've activated the virtual environment.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1702449119622/6db83305-1bad-40f2-a749-9c0fc4f3f5de.jpeg" alt class="image--center mx-auto" /></p>
<p>You know when the Virtual environment is activated by looking for a (theusernamedvirtualenvironmentnamegoesinhere) in the beginning of each line.</p>
<p>You need to hit pip freeze after activating the virtual env. and it should return blank line, which means no packages have been installed in our environment(virtual)</p>
<p>if there are some package names being returned by pip freeze, recheck if your virtual environment is active.<br />once you have made sure your virtual environment is active. you can go ahead and download Django with pip:</p>
<pre><code class="lang-r">pip install django
</code></pre>
<p>you should see this screen:  </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1702449671467/f4ddadaf-7d2d-4fe5-9713-0cd0af7aa553.jpeg" alt class="image--center mx-auto" /></p>
<p>after the download is complete, You can do pip freeze and it should show Django, asgiref, sqlparse, tzdata as the packages. You are ready to start your project now.</p>
<p>the command to create a Django project is:</p>
<pre><code class="lang-r">django-admin startproject yourprojectnamegoesinhere .
</code></pre>
<p>the "." at last tells Django that the current directory you're in will be your main project folder. if you don't add that . at the end then your project will be made inside of a folder named "yourprojectnamegoesinhere"</p>
<p>then we need to go to the project's main folder and use the following command</p>
<pre><code class="lang-r">py manage.py runserver
</code></pre>
<p>This command will start the server for us and give us the link to the port where the local server is hosted. below is a figure demonstrating it:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1702450427416/91cd8397-40d6-4d36-a4a5-5e3608de795a.jpeg" alt class="image--center mx-auto" /></p>
<p>Now, we can see the Actual Web Server if we go to Https://localhost:8000/ on our browser of choice. The landing page of empty Django web server Looks like this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1702450605271/2df7f61e-8d4a-4872-aa06-de6ad6318ded.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-congratulations-youve-completed-1900-steps-of-becoming-a-django-master">CONGRATULATIONS! You've completed 1/900 Steps of Becoming a Django Master.</h3>
<p>In next Blog We'll be creating The Best To-do app anyone's ever seen</p>
]]></content:encoded></item><item><title><![CDATA[What The Fuck is Django, and why is it the best?]]></title><description><![CDATA[In this blog, Django will be getting chained by the Django Master himself, just like the old times.
Django is a Batteries-included WEB Framework written in Python. Django takes care of the difficult stuff so that you can concentrate on building your ...]]></description><link>https://blog.django-tutorial.dev/wtf-is-django-and-why-is-it-the-best</link><guid isPermaLink="true">https://blog.django-tutorial.dev/wtf-is-django-and-why-is-it-the-best</guid><category><![CDATA[Django]]></category><category><![CDATA[General Programming]]></category><category><![CDATA[Python]]></category><category><![CDATA[DjangoRestFramework]]></category><category><![CDATA[Multiply and surrender]]></category><category><![CDATA[django master]]></category><dc:creator><![CDATA[Nischal lamichhane]]></dc:creator><pubDate>Wed, 13 Dec 2023 04:16:34 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1702474943605/d9fdb8b6-067f-4c3f-84d3-15a7003d6b3d.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this blog, Django will be getting chained by the Django Master himself, just like the old times.</p>
<p>Django is a Batteries-included WEB Framework written in Python. Django takes care of the difficult stuff so that you can concentrate on building your web application. But as a Django Master, I don't need Django to take care of the difficult Stuff for me. Django emphasizes reusability of components, also referred to as DRY (Don't Repeat Yourself) and comes with ready-to-use features like login system, database connection and CRUD operations (Create Read Update Delete).</p>
<h1 id="heading-flow-of-data-in-a-django-server">Flow of Data in a Django Server</h1>
<h1 id="heading-request-response-flow">Request-Response Flow</h1>
<p>When a Request is received by the Django server, Some Magic happens, and a Response is Generated. I've devised a Very Detailed Flowchart of the process below:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1702401670449/8213fa6f-fc87-4b1f-854f-1b685d1d6630.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-how-does-the-algorithm-work">How does the "Algorithm" work?</h2>
<p>As a Django Master, I like to explain the Algorithm as:<br />When A Request is received by the Server. The Server Looks at the URL that the request is looking for. Then It will look for the Function assigned to handle that URL request. It invokes the Function that will return a Webpage, that gets sent as the Response To that request.</p>
<h2 id="heading-what-if-the-url-doesnt-have-a-function">What if the URL doesn't have a function?</h2>
<p>Then Obviously an Error Occurs. If you needed to "Know" what happens if URL doesn't have a Function that can handle it. then I suggest you stop reading all blogs from the Django Master. Your monkey brain can't handle the amount of knowledge in upcoming Blogs.</p>
<h2 id="heading-what-is-the-architecture-that-django-uses">What is the Architecture that Django Uses?</h2>
<p>Django Uses MVT architecture.<br />MVT stands for Model-View-Template</p>
<p>If someone says Django is MVC architecture. Your Response to that request should be, "YOU'RE WRONG AND I HATE YOU!!!"</p>
<p>Below is a Detailed Figure that demonstrates MVT:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1702437570030/89ba104d-4c6f-44e4-9ee5-751047c6e9e2.png" alt class="image--center mx-auto" /></p>
<p>If you're not a Django master, you probably Need more explanation on the Figure.</p>
<p>Model: Model is the Database for Django. It is written in Models.py</p>
<p>View: View are the function that will take the data out of database. It is written in Views.py</p>
<p>Template: Template is a Skeleton of the HTML file that wont have any data. It is written in Templates folder</p>
<p>Here is Examples of Model, View and Template's Code:</p>
<pre><code class="lang-python">Models.py:

<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">Message</span>(<span class="hljs-params">models.Model</span>):</span>
    messageid = models.AutoField(primary_Key = <span class="hljs-literal">True</span>)
    content = models.CharField()
</code></pre>
<pre><code class="lang-python">views.py:

<span class="hljs-keyword">from</span> django.shortcuts <span class="hljs-keyword">import</span> render
<span class="hljs-keyword">from</span> .models <span class="hljs-keyword">import</span> Message

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">index</span>(<span class="hljs-params">request,message_id</span>):</span>
    template_path = <span class="hljs-string">'templates/index.html'</span>
    msg = Message.objects.get(messageid=message_id)
    context = {
        <span class="hljs-string">'message'</span>:msg,
    }    
    <span class="hljs-keyword">return</span> render(request,template_path,context)
</code></pre>
<pre><code class="lang-xml">Templates/index.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> Messages <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">p</span>&gt;</span> The Message is: {{messgage.content}} <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>
<p>Thats the Basics of Django. In next blog, We'll start Creating Best TODO Apps the world has ever seen with the Django Master <a class="user-mention" href="https://hashnode.com/@hehenischal">Nischal lamichhane</a> .</p>
]]></content:encoded></item></channel></rss>