<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Django lions 🔥 - Medium]]></title>
        <description><![CDATA[We share innovative stories about Django and other tech blogs submitted by our finest developers. - Medium]]></description>
        <link>https://medium.com/djangotube?source=rss----26e6b1ba0dee---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Django lions 🔥 - Medium</title>
            <link>https://medium.com/djangotube?source=rss----26e6b1ba0dee---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 08:09:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/djangotube" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[What are Django models?]]></title>
            <link>https://medium.com/djangotube/what-are-django-models-4c0043f2f1f1?source=rss----26e6b1ba0dee---4</link>
            <guid isPermaLink="false">https://medium.com/p/4c0043f2f1f1</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <dc:creator><![CDATA[Hemanth S P]]></dc:creator>
            <pubDate>Mon, 14 Oct 2024 02:57:41 GMT</pubDate>
            <atom:updated>2024-10-14T03:04:55.208Z</atom:updated>
            <content:encoded><![CDATA[<p>Data is part of any application, and based on the type of data, the storage will also differ; however, Django supports only SQL databases, To effectively store data in this table, Django provides models so In this article, we will explore what the Django model is and how it will work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/657/1*LMxGEu4cUw9By3OWjrREpA.png" /><figcaption>Django models</figcaption></figure><p>You already know Django is built on MVT architecture; here M refers to Models. So what are models then?</p><h3><strong>The table of contents is</strong></h3><ul><li>What are models in Django?</li><li>Fields</li><li>Field types</li><li>Field options</li><li>Meta</li><li>Model attributes</li><li>Model methods</li><li>Model inheritance</li></ul><h4>📑 Models</h4><p>The Django models are where we store the data, and they contain essential fields for how we are going to store the data. So in modern applications, if you want to store the data, we need a database, so this is exactly where models can be used in Django.</p><p>For example, a model looks like this.</p><pre>from django.db import models<br><br>class Student(models.Model):<br>    name = models.CharField(max_length=100)<br>    age = models.CharField(max_length=100, default=1)</pre><p>Here, the student is the model name; this model has two fields: name and age. Each model maps to a single table in the databases; each field, or we can call it attributes, represents the table column.</p><p>After defining the models, we need to <strong>makemigrations</strong> and <strong>migrate</strong> to replicate this data structure to a physical database, and in the database, it will look like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*1kgvGGEjnBXFVXZ2oCifYQ.png" /></figure><p>Here you may see one more extra column called id. This is an auto-generated column by Django by default; this is an auto-incremented and primary key; however, this behaviour of the id can be overridden using DEFAULT_AUTO_FIELD (app level or global) or writing <strong>primary_key=True</strong> in any one of the fields because each model requires only one primary key either by defining explicitly (custom) or implicitly (id).</p><h4>📑 Fields</h4><p>Django models have attributes. These attributes are called fields; these fields are mapped to table columns. In the above student model, we defined name and age fields.</p><p>While writing field names, you should consider a few important concepts.</p><ul><li>Field names should not conflict with model methods like clean, save, and delete.</li><li>Do not use Python-reserved keywords as field names.</li><li>Field names should not contain double underscores.</li><li>Field names should end with an underscore</li><li>You can use SQL-reserved keywords as field names.</li><li>If you want to use a conflicted field name, then you can use the db_column option inside the field. This option will rename the table column in the database.</li></ul><h4>📑 Field types</h4><p>Field types refer to field data types; these field classes determine in the table column what kind of data to store; for example, in the above student model, the name is a vachar data type and the age is the integer type; every field is a subclass of the Fields class. These Django-built-in field class types have minimal validation logic; however, we can also create custom field class types.</p><h4>📑 Field Options</h4><p>There are several field options available, and we can pass to each field; however, a few options are only restricted to a few field class types. For example, the max_length option is mainly for <strong>CharField</strong>; some options are optional, and some of them are mandatory.</p><p>The most used ones are null, blank, max_length, default, help_text, and and primary_key. Django offers the 3 most common database relations.</p><ul><li>many to one (foreign key field)</li><li>many to many (many to many fields)</li><li>one to one (one to one field)</li></ul><h4>📑 Meta</h4><p>Meta is used to give metadata to our models, and it is an inner class; it is not related to any field, and it is completely optional to define; for example, it looks like this.</p><pre>from django.db import models<br><br>class Student(models.Model):<br>    name = models.CharField(max_length=100)<br>    age = models.CharField(max_length=100, default=1)<br><br>    class Meta:<br>        ordering = [&quot;age&quot;]</pre><p>Some of the most used meta fields are ordering, db_table, verbose name, abstract, app_label, db_table_comment, managed, proxy, permissions, default permissions, index, unique together, and constraints.</p><h4>📑 Model attributes</h4><p>Other than field attributes, which we already discussed above, another major important attribute is the model manager. This is an interface to use with which we made a database query. By default, Django provides a default manager called objects, and we can also write a custom model manager if we want. These managers will be accessible via model class but not model instances. for example, here I defined the <strong>MyCustomManger</strong></p><pre>from django.db import models<br>from django.db.models import Manager<br><br><br>class MyCustomManger(Manager):<br>    def get_queryset(self):<br>        return super().get_queryset().filter(age__gte=18)<br><br><br>class Student(models.Model):<br>    name = models.CharField(max_length=100)<br>    age = models.CharField(max_length=100, default=1)<br><br>    men_objects = MyCustomManger()<br><br>    class Meta:<br>        ordering = [&quot;age&quot;]</pre><h4>📑 <strong>Model methods</strong></h4><p>Django models methods used to keep business logic in one place. Django has a bunch of default methods in that the most used ones are str, get_absolute_url, save, delete, etc., and we can write our custom model methods to give row-level access and the manager method used for table-wide access.</p><pre>class Student(models.Model):<br>    name = models.CharField(max_length=100)<br>    age = models.CharField(max_length=100, default=1)<br><br>    def welcome_name(self):<br>        return f&quot;hi {self.name}&quot;<br>    <br>    @property<br>    def mr_name(self):<br>        return f&quot;mr {self.name}&quot;</pre><p>We can also define Python properties inside the model, but for me, it looks like the property also works exactly like the model method. Please let me know if you guys think why we need property in this case in the comment section below.</p><h4>📑 Model inheritance</h4><p>Model inheritance works exactly like Python class inheritance; however, in the Django model, inheritance is mainly used to hold common information in the parent model.</p><p>Model inheritance has three types, such as</p><ul><li>abstract base class,</li><li>multi-table inheritance, and</li><li>proxy models.</li></ul><h4>⤵ <strong>Abstract base class</strong></h4><p>The abstract base class is used to put some common information in the parent class at the Python level. After that, we can define the child class that is inherent in all the fields from the parent model, but to achieve this, we need to set <strong>abstract=True </strong>on the abstract model.</p><pre>class CommonInfoHolder(models.Model):<br>    created_at = models.DateTimeField(auto_now_add=True)<br>    updated_at = models.DateTimeField(auto_now=True)<br><br>    class Meta:<br>        abstract = True<br><br><br>class People(CommonInfoHolder):<br>    name = models.CharField(max_length=100)<br>    age = models.CharField(max_length=100, default=1)</pre><p>Here CommonInfoHolder is the abstract model, which means we cannot create a table for the abstract model and we cannot use queryset (manager) on this model, but the people model will have 4 fields: name, age, created_at, and updated_at.</p><p>Django supports meta inheritance too, meaning if we define any meta option in the CommonInfoHolder base class, those options will definitely be included in the people class, and if the child model wants an extended parent meta option, then it can subclass we need to write in the meta option like this.</p><p>However, the abstract meta option will not be inherited from the child metaclass.</p><pre>class People(CommonInfoHolder):<br>    name = models.CharField(max_length=100)<br>    age = models.CharField(max_length=100, default=1)<br><br>    class Meta(CommonInfoHolder.Meta):<br>        db_comment = &quot;my country people&quot;</pre><p>Note that inherited fields from the abstract base class can be overridden with other fields with the same name and can be removed with None. and in the table, it will look like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/999/1*XbYU1Bi763tLXjAY6W0lKA.png" /></figure><h4>⤵ Multi-table inheritance</h4><p>This is the second way of model inheritance; in this, each model creates a separate table and can be queried separately; however, this way of inheritance creates a one-to-one field representation model, for example, in the below models.</p><pre><br><br>class M1(models.Model):<br>    math_m1 = models.CharField(max_length=100)<br><br>class M2(M1):<br>    math_m2 = models.CharField(max_length=100)</pre><pre>&gt;&gt;&gt; M1.objects.create(math_m1=”hi”)<br>&lt;M1: M1 object (6)&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*m1Xt15IFSXR5CRIGEuwv5A.png" /></figure><pre>&gt;&gt;&gt; M2.objects.create(math_m2=”bye”)<br>&lt;M2: M2 object (7)&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*skUVCM7porvcUVZsCsd49A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*M0KEToNx-288bslUVdcaIg.png" /></figure><h4>⤵ Proxy models</h4><p>proxy models Inheritance is used to give Python-level extension behaviour to models like meta options, managers, and model methods without altering the originals from the non-proxied model.</p><pre>class M1(models.Model):<br>    math_m1 = models.CharField(max_length=100)<br><br><br>class MyM1(M1):<br>    class Meta:<br>        proxy = True<br><br>    def ret_name(self):<br>        pass</pre><pre>&gt;&gt;&gt; MyM1.objects.create(math_m1=”asdf”)<br>&lt;MyM1: MyM1 object (8)&gt;</pre><p>here I am just using MyM1 model as a proxy model to do all the work</p><h4>⤵ Unmanaged models</h4><p>Unmanaged models will not create any- tables in Django, but we can query from these models, and it is mainly used to create the SQL views. To create an unmanaged model, we just need to set managed=False in the meta option.</p><pre><br>class IloveYouu(models.Model):<br>    name = models.CharField(max_length=100)<br>    <br>    class Meta:<br>        managed = False</pre><p>When we do makemigrations and migrate, the migration file will be generated, but the table will not be created.</p><h4>🤔 So what is the difference between proxy inheritance and unmanaged models?</h4><p>From the top point of view, both look similar, but their behaviour is different.</p><ul><li>To just change the Python-level behaviour and keep all the same fields, we can use proxy inheritance. Proxy models are directly in sync with the parent model.</li><li>To give a mirroring for existing models or database tables, then we can use unmanaged models.</li></ul><h3>🧠 Final thoughts</h3><p>Django gives great flexibility to manage database tables and data, so for that the primary API is Django models that we discussed deeply in this article, so please go through the Django documents once, and if you have any doubts about this article, please let me know in the space provided below, and take a moment to clap.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c0043f2f1f1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/djangotube/what-are-django-models-4c0043f2f1f1">What are Django models?</a> was originally published in <a href="https://medium.com/djangotube">Django lions 🔥</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Django exceptions handling introduction]]></title>
            <link>https://medium.com/djangotube/an-overview-of-common-django-exceptions-and-errors-10351227eadb?source=rss----26e6b1ba0dee---4</link>
            <guid isPermaLink="false">https://medium.com/p/10351227eadb</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <dc:creator><![CDATA[Hemanth S P]]></dc:creator>
            <pubDate>Sat, 10 Aug 2024 02:53:48 GMT</pubDate>
            <atom:updated>2024-08-31T20:28:39.067Z</atom:updated>
            <content:encoded><![CDATA[<h3>Django exceptions handling an introduction</h3><h4>In this blog, I will share a few small descriptions of the commonly seen exceptions and errors in Django with an example and how to handle them in a specific way.</h4><figure><img alt="An overview of common Django exceptions and errors" src="https://cdn-images-1.medium.com/max/1024/0*vdwiuoJoRivYAJE4" /><figcaption>Photo by <a href="https://unsplash.com/@faisaldada?utm_source=medium&amp;utm_medium=referral">Faisal</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Contents 🏁:</h4><ul><li>Exception name.</li><li>How does this occur with an example?</li><li>How do I catch the exception?</li></ul><h4># DoesNotExist 📌</h4><ul><li>This exception occurs when you try to access the objects or records that do not exist for whatever input value you provided at that time. To avoid this exception, you can add one if check, but this is not recommended because this calls one more SQL call to the database, which is unnecessary.</li><li>This exception is well-known in Django.</li><li>for an Example</li></ul><pre>Student.objects.get(name=&quot;god&quot;) ❌</pre><ul><li>I assume you are already familiar with Django Shell, and in this blog, I consider only student models with only one field, which is the name.</li><li>now, consider The student model has zero records; when you execute the above code, the shell will throw an error like this.</li></ul><pre>DoesNotExist: Student matching query does not exist.</pre><ul><li>For a trick, you can use the if condition to skip this error (but this is not recommended).</li></ul><pre>if Student.objects.filter(name=&quot;god&quot;).exists():<br>   Student.objects.get(name=&quot;god&quot;)</pre><ul><li>However, the best way to catch the error is to try except.🎉</li></ul><pre>try:<br>    Student.objects.get(name=&quot;god&quot;)<br>except Student.DoesNotExist:<br>    print(&quot;There is no student information.&quot;)<br>    </pre><h4># MultipleObjectsReturned 📌</h4><ul><li>This exception occurs when you try to access the objects or records that do exist with more times for whatever the input value you provided at that time using the get method. To avoid this error, you can use a filter with the first method, or if you call the catch the exception, you can.</li></ul><p>example.</p><ul><li>now, consider The student model has two records with the name god; when you execute the above code, the shell will throw an error like this.</li></ul><pre>Student.objects.get(name=&quot;god&quot;) ❌</pre><pre>MultipleObjectsReturned: get() returned more than one Student — it returned 2!</pre><ul><li>So you can use a filter to fetch which god you want, and make sure to use order_by(for consistent results) when using the filter to get 🎉.</li></ul><pre>Student.objects.filter(name=&quot;god&quot;).order_by(&quot;-created_at&quot;).first()</pre><p>or if you want to catch the exception, then you can. 🎉</p><pre>try:<br>    Student.objects.get(name=&quot;god&quot;)<br>except Student.MultipleObjectsReturned:<br>    print(&quot;There are students.&quot;)</pre><h4># ConnectionDoesNotExist</h4><ul><li>suppose when you configured multiple DB connections for your project in setting, for example, write and read databases. And when you try to fetch the records using the database, which does not exist, this exception will occur.</li></ul><pre>Student.objects.using(&quot;write&quot;).get(name=&quot;god&quot;) # ✅<br>Student.objects.using(&quot;read&quot;).get(name=&quot;god&quot;) # ✅<br>Student.objects.using(&quot;bus&quot;).get(name=&quot;god&quot;) # ❌ bcz <br># database called bus does not exist in settings</pre><h4># ValueError: Cannot assign “instance”: the current database router prevents this relation.</h4><ul><li>suppose when you configure multiple DB connections for your project in settings, for example, write and read databases, and in the student model you have defined one more foreign key field and you are trying to copy the foreign key value from reader db to writer db at that time this error will come.</li></ul><pre>class Student(models.Model):<br>    name = CharField()<br>    city = ForeignKey(City)<br><br>Student.objects.create(name=&quot;god&quot;, city=city)<br><br>w = Student.objects.using(&quot;write&quot;).get(name=&quot;god&quot;)<br>r = Student.objects.using(&quot;read&quot;).get(name=&quot;god&quot;)<br>w.city = r.city<br>w.save() ❌<br></pre><pre>ValueError: Cannot assign “&lt;Student: god&gt;”: the current database router prevents this relation.</pre><h4># Permission denied to create a database</h4><ul><li>Usually, you will get this error for the first time when you just start to run <strong>Pytest</strong> or <strong>Django test</strong> in your terminal.</li></ul><pre>Got an error creating the test database: permission denied to create database</pre><ul><li>To solve this error, you need to log in to your database engine and give create db access to your db user.</li><li>I will show an example of PostgreSQL</li></ul><pre>sudo su — postgres<br># enter your laptop password<br>postgres@ubu:~$ psql<br>postgres=# ALTER USER {you db user name} CREATEDB;<br>ALTER ROLE<br></pre><p>And after that, if you wish to revoke <strong>createdDb</strong> access to your, then use the below command.</p><pre>postgres=# ALTER USER {you db user name} NOCREATEDB;<br>ALTER ROLE</pre><h4># SoftTimeLimitExceeded</h4><ul><li>Usually, this error will come in the Celery part. When you integrate Celery into your project, then in Django settings we need to specify the <strong>soft </strong>and <strong>hard time</strong> limits in seconds. When you define the soft time limit, if your code takes longer than the soft time limit at that time, this error will occur, and this error is catchable but the hard time limit is not catchable.</li></ul><pre>billiard.exceptions.SoftTimeLimitExceeded: SoftTimeLimitExceeded()</pre><ul><li>you can catch this exception.</li></ul><pre>settings.py<br>CELERY_TASK_TIME_LIMIT = 60 * 2<br>CELERY_TASK_SOFT_TIME_LIMIT = 60 * 1<br><br>from billiard.exceptions import SoftTimeLimitExceeded<br><br>@shared_task<br>def say_hi():<br>    try:<br>        # some code/network call that takes more than 1 minute<br>    except SoftTimeLimitExceeded:<br>        hurry()<br>        print(&quot;Catch and hurry to finish the task; otherwise, a hardtime limit error will occur.&quot;)</pre><ul><li>If your hurry function takes more than 2 minutes, the hard-time limit error will occur.</li></ul><pre>billiard.exceptions.TimeLimitExceeded: TimeLimitExceeded(120,)<br># and you can not catch this error</pre><h4><strong># AttributeError</strong></h4><ul><li>This error applies to Python and Django, and the meaning is the same, like objects have no field.</li><li>suppose I have a student model with only one field called name, but I am trying to access a no-existing field, let’s say first_name, so when you try to access this field on a student instance, then this error will occur.</li></ul><pre>student = Student.objects.create(name=&quot;god&quot;)<br>student.first_name<br>AttributeError: &#39;Student&#39; object has no attribute &#39;first_name&#39;</pre><ul><li>And if you are trying to access an empty query set</li></ul><pre>Student.objects.filter(name=&quot;he&quot;).first().name<br>AttributeError: ‘NoneType’ object has no attribute ‘name’</pre><ul><li>you can catch this error</li></ul><pre>try:<br>    Student.objects.filter(name=&quot;he&quot;).first().name<br>except AttributeError:<br>    print(&quot;I got it&quot;)</pre><h3># KeyError</h3><ul><li>This error occurs when we try to access a non-existing key in the dictionary data structure.</li></ul><pre>my_dict = {}<br>my_dict[&quot;name&quot;]<br>KeyError: &#39;name&#39;</pre><ul><li>you can catch this error</li></ul><pre>try:<br>    my_dict = {}<br>    my_dict[&quot;name&quot;]<br>except KeyError:<br>    print(&quot;catch&quot;)</pre><h3># Read-only replica db</h3><ul><li>If your project has a write and read replica database configured, and if you are trying to delete records in the replica database, then this error will occur because the read replica is only designed for reading purposes but not writing purposes.</li></ul><pre>cannot execute [UPDATE or DELETE] in a read-only transaction</pre><h3># ValidationError</h3><ul><li>This error occurs for multiple reasons, but I will share one example. Suppose you are trying to fetch the record with a malformed input field; in this example, I am supposed to pass the valid UUID to the primary key, but I password malformed UUID.</li></ul><pre>Student.objects.get(id=&quot;1234–234r-1234&quot;)<br><br>ValidationError: [&#39;“1234-234r-1234” is not a valid UUID.&#39;]</pre><ul><li><strong>note</strong>: Always sanitize the input field using serializer or form when the user hits APIs.</li></ul><h3># NameError</h3><ul><li>when the key is not defined, here the given_name variable is not defined but we are trying to assign it.</li></ul><pre>Student.objects.get(name=given_name)</pre><pre>NameError: name ‘given_name’ is not defined</pre><h3># UnboundLocalError</h3><ul><li>This is another version of the name error; for example, look at the below example to understand better.</li></ul><pre>def hi(name):<br>   print(first_name)<br>   first_name = name<br><br>hi(&quot;test&quot;)<br><br>UnboundLocalError: local variable &#39;first_name&#39; referenced before assignment</pre><pre>def hi(name):<br>   print(first_name)<br><br>hi(&quot;test&quot;)<br><br>NameError: name &#39;first_name&#39; is not defined</pre><h3># TypeError</h3><ul><li>This error will occur whenever the code tries to make an incompatible operation between objects.</li></ul><pre>None + None<br>TypeError: unsupported operand type(s) for +: &#39;NoneType&#39; and &#39;NoneType&#39;</pre><h3># DataError</h3><ul><li>When you push more data than the maximum size, for example, in the <em>student</em> model name field type is <em>CharField,</em> and, its max_length is 10, but when you try to assign 11 characters, an error will occur.</li></ul><pre>student = Student.objects.get(name=&quot;god&quot;)<br>student.name =&quot;12345678901&quot;<br>student.save()<br><br>DataError: value too long for type character varying (10)</pre><h3># IndexError</h3><ul><li>This is a pure Python error, and most of them already know when this error occurs. For example, when we try to access the list using the index, that is greater than the list length, an error will occur.</li></ul><pre>li = [1]<br>li[1] # index 1<br><br>IndexError: list index out of range</pre><ul><li>you can catch this error</li></ul><pre>li = [1,3]<br>try:<br>    li[4] # accessing index 4<br> except IndexError:<br>   print(&quot;catch&quot;)</pre><h3># DisallowedHost 🌍</h3><ul><li>This occurs when you try to hit the Django Rest API with some host and the host is not defined in ALLOWED_HOSTS.</li><li>If the web request origin is not defined in the ALLOWED_HOSTS, then Django will block the request by saying DisallowedHost.</li></ul><h3>conclusion</h3><p>Although I provided an example of common Django exceptions and errors in this blog post, there are still a lot of Django and Python exceptions and errors available, and you may encounter additional unaware errors when attempting to deploy your Django project with additional setup, such as SSL certification. For a thorough understanding, please read the Django document 📚, and let me know if you have any questions in the space provided for comments below 💬.</p><p>if you like this story, then</p><ul><li>clap 50 times.</li><li>Share this article with your groups.</li><li>subscribe for more.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10351227eadb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/djangotube/an-overview-of-common-django-exceptions-and-errors-10351227eadb">Django exceptions handling introduction</a> was originally published in <a href="https://medium.com/djangotube">Django lions 🔥</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My funny remote work from my home workstation and gadgets.]]></title>
            <link>https://medium.com/djangotube/work-from-home-with-important-gadgets-40fdb2c205f8?source=rss----26e6b1ba0dee---4</link>
            <guid isPermaLink="false">https://medium.com/p/40fdb2c205f8</guid>
            <category><![CDATA[internet]]></category>
            <category><![CDATA[work-from-home]]></category>
            <category><![CDATA[solar-power]]></category>
            <category><![CDATA[solar-energy]]></category>
            <dc:creator><![CDATA[Hemanth S P]]></dc:creator>
            <pubDate>Fri, 01 Jul 2022 16:35:04 GMT</pubDate>
            <atom:updated>2024-08-16T16:16:30.329Z</atom:updated>
            <content:encoded><![CDATA[<p>After a pandemic starts working from home is a common option for many people however working from home was not easy for so many people especially those who stayed in rural or remote areas including me for two reasons those are,</p><p><strong>A. Electricity.</strong></p><p><strong>B. Internet.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*m2w3D1vboURvuhF6" /><figcaption>Photo by <a href="https://unsplash.com/@driaug?utm_source=medium&amp;utm_medium=referral">Dries Augustyns</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Electricity</h3><p>My areas frequently have electricity problems also sometimes because of rain and I have to wait for one or two days for power to come back, My laptop also drains fast if I use Ubuntu but now this problem is solved by a solar power solution which I purchased online. I will explain a bit more about my solar solution setup which consists of,</p><ol><li><strong>Solar panels</strong></li><li><strong>Dc wire</strong></li><li><strong>An</strong> <strong>inverter</strong></li><li><strong>Battery</strong>.</li></ol><h4><strong>1. solar panels</strong></h4><p>I have purchased three 12v 165watt polycrystalline solar panels which are connected in parallel, see the below photo for reference.</p><figure><img alt="12v 165watt polycrystalline solar panels" src="https://cdn-images-1.medium.com/max/1024/1*TzlEySqGiTQL2uH2gk-XHA.jpeg" /><figcaption>12v 165watt polycrystalline solar panels.</figcaption></figure><p>these panels will produce around 450 to 490 watts as output, and it is mounted on a simple 3-pair stand with cement concrete.</p><figure><img alt="solar panels in parallel connection." src="https://cdn-images-1.medium.com/max/1024/1*Z3aXVW1EcfjLkoRBI6pwhw.jpeg" /><figcaption>solar panels in parallel connection.</figcaption></figure><h4>2. DC wire</h4><p>To carry the DC power produced by these solar panels I have to use 10sq, mm gauge dc wire, I would have used 4 or 6sq mm wire but my inverter to solar panel distance was 30 meters so I must use 10sq, mm wire to avoid power loss, the total 34-meter wire used including positive and negative wire. why 34 meters instead of 30 meters you may ask because 0.92 wire length is equal to 1 meter in length, especially on my side. In the above photo, we can see the yellow wire is the dc wire.</p><h4>3. Inverter(nxg+ 1100)</h4><p>One of the main headaches while installing a solar system is which is the best inverter whether is it a PWM or MPPT solar charge controller in my case, I have to use a luminous NXG+ 1100 hybrid solar charge controller because as its name suggests it supports mains power and solar input, on cloudy days I can not trust solar panels(it produce low ampere that is not enough to charge the battery).</p><figure><img alt="nxg+ 110 luninous inverter" src="https://cdn-images-1.medium.com/max/1024/1*0uul7Hql2OpgrZXj3_EZqw.jpeg" /><figcaption>Hybrid solar controller and inverter.</figcaption></figure><h4>5. Solar battery (150Ah solar battery)</h4><p>The solar panels are 12v, and the inverter is 12v so I have to purchase a 12v single solar battery of 150AH, C10 cycle from the luminous company, having said that this completes my solar setup.</p><h4>Performance</h4><p>On a sunny day, it takes 5 hours to fully charge the battery but on cloudy days it requires a whole day to change from 50 to 60%, and the inverter and battery give only 80% efficiency (20% goes from AC to DC or DC to AC conversion) using it gives 4 to 5 hours backup for my home including laptop, 3 led bulbs, and TV.</p><p>And my inverter does not display the battery percentage I have to purchase a digital meter to check the voltage of the battery that looks like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Q5cO1xa-I07oHmNaYxNPw.jpeg" /><figcaption>voltage digital meter.</figcaption></figure><p><strong>B. Internet</strong></p><p>One of the most important parts of remote work is the internet. In my home, I receive absolutely 0 or 1 percent signal that is enough to make phone calls but not for the internet, so I have to use an <strong>Airtel internet Hotspot,</strong> purchasing a hotspot during the pandemic days was very difficult because all telecommunication operator&#39;s devices were out of stock(huge demand), somehow I managed to get from the local mobile shop by paying one to double charge and I put in my home terrace with a long stick attached, it is located almost 20 meters from the ground with the continuous power supply because hotspot battery maximum backup time 2 to 3 hours, once setup done then I got good 15Mbps speeds on day time and more than 15 Mbps speed at night time.</p><h4>Table Fan (essential for me)</h4><p>I am using a table fan this fan a dc fan that is directly connected to a 50-watt solar panel without any solar charge controller and it works like this, due to the direct connection from the solar panel to the fan(again another new 30-meter Ac wire used) when the sun comes in the morning around 7:00 am the fan to start to rotate slowly, in the afternoon time fan rotates at very high speed because of direct sunlight but I will switch off sometimes to give rest to the fan otherwise continues running will cause fan motor damage and at the evening 6:pm fan will off slowly like this happening daily, I attached my panel and fan photo for reference.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G0vHbZpo0rBcFeqjgFLKEQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TDaiL9GMq_DtnTE1NatkPg.jpeg" /><figcaption>50 watt solar panel(left), DC table fan(right)</figcaption></figure><p>Like this, I managed to get good renewable electricity, good internet, and a little free current fan I hope this kind of setup is helpful to someone. if you found this blog helpful please like and subscribe.</p><p>Thank you</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40fdb2c205f8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/djangotube/work-from-home-with-important-gadgets-40fdb2c205f8">My funny remote work from my home workstation and gadgets.</a> was originally published in <a href="https://medium.com/djangotube">Django lions 🔥</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Django distinct() query method introduction]]></title>
            <link>https://medium.com/djangotube/django-distinct-query-method-introduction-a6f45ee7c84a?source=rss----26e6b1ba0dee---4</link>
            <guid isPermaLink="false">https://medium.com/p/a6f45ee7c84a</guid>
            <category><![CDATA[django-orm]]></category>
            <category><![CDATA[distinct]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Hemanth S P]]></dc:creator>
            <pubDate>Sat, 09 Apr 2022 18:08:45 GMT</pubDate>
            <atom:updated>2024-08-16T16:21:24.291Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Django distinct query method introduction" src="https://cdn-images-1.medium.com/max/1024/0*D7xHZSaA7mbcgl1Q" /><figcaption>Photo by <a href="https://unsplash.com/@rgaleria?utm_source=medium&amp;utm_medium=referral">Ricardo Gomez Angel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this article, we are going to see how the <em>DISTINCT</em> expression/query method works on Django queryset and with different databases.</p><p>Contents:</p><ol><li>What is a distinct expression?</li><li>How to use this in Django?</li><li>Code examples and some notes.</li></ol><h3><strong>1. What is a distinct expression?</strong></h3><p><strong>Distinct</strong> is an expression/query clause used in SQL to remove duplicated results and return unique results based on the column we select.</p><h3>2. How to apply this in Django?</h3><p>We can use a <em>distinct</em>() query method at the end or in between queryset and with other regular Django query methods like all(), values(), etc…</p><h3>3. Let&#39;s see some examples</h3><p>a). I created a simple model called user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*w2wsMHv1CrqapHiobLgDPg.png" /><figcaption>user model</figcaption></figure><p>b) Loaded the sample data to the user model and it looks like the below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*KwP_hSgtGcCExpKuyjtE4g.png" /><figcaption>sample data</figcaption></figure><p>c) Execute the <em>distinct()</em> query and print its results and corresponding SQL query.</p><pre>User.objects.distinct()</pre><pre>==================SQL====================<br>SELECT DISTINCT &quot;polls_user&quot;.&quot;id&quot;,<br>       &quot;polls_user&quot;.&quot;name&quot;,<br>       &quot;polls_user&quot;.&quot;age&quot;<br>FROM &quot;polls_user&quot;</pre><pre>==============Result======================<br>&lt;QuerySet [&lt;User: User object (1)&gt;, &lt;User: User object (2)&gt;, &lt;User: User object (3)&gt;, &lt;User: User object (4)&gt;]&gt;</pre><p>In the above code, you can see the DISTINCT method is applied to all the available columns on the model(actually we never use this code because it returns all results like all(), at least as of now no use).</p><h4>3. a. How to apply distinct on all columns or a few columns?</h4><ol><li><strong>what is applying distinct on all columns?</strong></li></ol><p>Applying distinct on all columns using the below format.</p><blockquote>SELECT DISTINCT <strong>table_column;</strong></blockquote><pre>User.objects.all().distinct()</pre><p>distinct widely used while joining related fields.</p><p><strong>2. what is applying distinct on a few columns?</strong></p><p>Applying distinct on multiple columns using the below format its works only in the PostgreSQL database. In this case, returned results will be unique to the combination of the given columns.</p><blockquote>SELECT DISTINCT ON <strong>table_column1, . . . . . table_column_n;</strong></blockquote><pre>User.objects.using(&quot;postgress&quot;).distinct(&quot;name&quot;)</pre><p>OR</p><pre>User.objects.using(&quot;postgress&quot;).distinct(&quot;age&quot;, &quot;name&quot;)</pre><p><strong>Note</strong>: the distinct method will also be considered null as a unique value.</p><blockquote>DISTINCT ON only applicable in PostgreSQL.</blockquote><h4># How do get unique data?</h4><p><strong>a. one-way is using values()</strong></p><pre>User.objects.using(“postgress”).values(“name”).distinct()<br>=====================SQL===========================<br>SELECT DISTINCT &quot;polls_user&quot;.&quot;name&quot; FROM &quot;polls_user&quot;</pre><p><strong>b. second way</strong></p><pre>User.objects.using(“postgress”).distinct(“name”)<br>=====================SQL===========================<br>SELECT DISTINCT<br>    ON (&quot;polls_user&quot;.&quot;name&quot;) &quot;polls_user&quot;.&quot;id&quot;,<br>       &quot;polls_user&quot;.&quot;name&quot;,<br>       &quot;polls_user&quot;.&quot;age&quot;,<br>  FROM &quot;polls_user&quot;</pre><p><strong># Let’s apply the DISTINCT ON expression on the age column and check this with different databases.</strong></p><p><strong>a. let&#39;s check in the SQLite database.</strong></p><pre>User.objects.distinct(“age”)<br># you will get error saying.<br># NotSupportedError: DISTINCT ON fields is not supported by this database backend</pre><p><strong>b. let&#39;s check in the PostgreSQL database.</strong></p><pre>User.objects.using(&quot;postgress&quot;).distinct(&quot;age&quot;)</pre><pre>==============SQL========================<br>SELECT DISTINCT<br>    ON (&quot;polls_user&quot;.&quot;age&quot;) &quot;polls_user&quot;.&quot;id&quot;,<br>       &quot;polls_user&quot;.&quot;name&quot;,<br>       &quot;polls_user&quot;.&quot;age&quot;<br>  FROM &quot;polls_user&quot;</pre><pre>================Results====================<br>&lt;QuerySet [&lt;User: User object (4)&gt;, &lt;User: User object (1)&gt;, &lt;User: User object (3)&gt;]&gt;</pre><p>in the above results, user ID-2 was removed because it had a duplicated value of age 21.</p><p><strong>c. let&#39;s check in the MYSQL database.</strong></p><pre>User.objects.using(&quot;mysql&quot;).distinct(&quot;age&quot;)<br># you will get error saying.<br># NotSupportedError: DISTINCT ON fields is not supported by this database backend</pre><p><strong>Note</strong>: While querying on related fields may produce duplicated requests, for example,<em> isnull</em> on <em>reverse relation will always give duplicate results </em>consider the below example with the <em>ForeignKey</em> model called <strong>Home,</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*2PcNorFrlPxBrRM8z_uqDQ.png" /><figcaption>The User and Home model</figcaption></figure><p>and added some sample data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*I3Y0h6TbpPEN42eLPd-TXg.png" /><figcaption>sample data for Home model, user ‘home’</figcaption></figure><pre>User.objects.filter(name=”homy”, home__isnull=False)</pre><pre>==================Result===========================<br>&lt;QuerySet [&lt;User: User object (2)&gt;, &lt;User: User object (3)&gt;]&gt;</pre><pre>===============SQL================================<br>SELECT &quot;polls_user&quot;.&quot;id&quot;,<br>       &quot;polls_user&quot;.&quot;name&quot;,<br>       &quot;polls_user&quot;.&quot;age&quot;<br>  FROM &quot;polls_user&quot;<br> INNER JOIN &quot;polls_home&quot;<br>    ON (&quot;polls_user&quot;.&quot;id&quot; = &quot;polls_home&quot;.&quot;user_id&quot;)<br> WHERE (&quot;polls_home&quot;.&quot;id&quot; IS NOT NULL AND &quot;polls_user&quot;.&quot;name&quot; = &#39;homy&#39;)</pre><p>Or more clearly.</p><pre>User.objects.filter(name=&quot;homy&quot;, home__isnull=False).values(&quot;id&quot;, &quot;name&quot;)<br>==================Result===========================<br>&lt;QuerySet [{&#39;id&#39;: 2, &#39;name&#39;: &#39;homy&#39;}, {&#39;id&#39;: 2, &#39;name&#39;: &#39;homy&#39;}]&gt;</pre><p>so you can use a <em>distinct</em> query method to remove duplicates.</p><pre>User.objects.filter(name=&quot;homy&quot;, home__isnull=False).distinct()<br>====================Result=========================<br>&lt;QuerySet [&lt;User: User object (2)&gt;]&gt;</pre><p><strong>Note</strong>: one caveat on <em>distinct</em> expression is it’s very slow, if you have millions of rows of data then you can easily notice the performance.</p><p><strong>Note</strong>: <em>order_by</em> columns are always available to the <em>distinct</em> by <em>default. Compare below two queries.</em></p><pre>User.objects.only(“age”).filter(age__gte=20).order_by(“name”)<br>==================Result================================<br>&lt;QuerySet [&lt;User: User object (3)&gt;, &lt;User: User object (2)&gt;, &lt;User: User object (1)&gt;]&gt;</pre><pre>==================SQL===================================</pre><pre>SELECT &quot;polls_user&quot;.&quot;id&quot;,<br>       &quot;polls_user&quot;.&quot;age&quot;<br>  FROM &quot;polls_user&quot;<br> WHERE &quot;polls_user&quot;.&quot;age&quot; &gt;= 20<br> ORDER BY &quot;polls_user&quot;.&quot;name&quot; ASC</pre><p>in the above code, I excluded the <em>name </em>field using the <strong><em>ONLY </em></strong>query from the SELECT statement. but the below code name field is included in the <em>SELECT</em> statement by <em>order_by.</em></p><pre>User.objects.only(“age”).filter(age__gte=20).distinct().order_by(“name”)</pre><pre>==================Result================================<br>&lt;QuerySet [&lt;User: User object (3)&gt;, &lt;User: User object (2)&gt;, &lt;User: User object (1)&gt;]&gt;</pre><pre>==================SQL====================================<br>SELECT DISTINCT &quot;polls_user&quot;.&quot;id&quot;,<br>       &quot;polls_user&quot;.&quot;age&quot;,<br>       &quot;polls_user&quot;.&quot;name&quot;<br>  FROM &quot;polls_user&quot;<br> WHERE &quot;polls_user&quot;.&quot;age&quot; &gt;= 20<br> ORDER BY &quot;polls_user&quot;.&quot;name&quot; ASC</pre><p><strong>Note</strong>: always use the <em>order_by</em> clause in combination with <em>distinct</em> to predict results otherwise it returns arbitrary results.</p><p><strong>Note</strong>: If you get any error like the one below,</p><pre>SELECT DISTINCT ON expressions must match initial ORDER BY expressions<br>=============================================================<br>User.objects.using(&quot;postgress&quot;).all().distinct(&quot;age&quot;).order_by(&quot;name&quot;)<br># this gives error.</pre><p>that means distinct expression fields must start with order_by fields.</p><pre>User.objects.using(&quot;postgress&quot;).all().distinct(&quot;age&quot;).order_by(&quot;age&quot;, &quot;name&quot;)<br># this is correct.<br>=============================================================<br>User.objects.using(&quot;postgress&quot;).all().order_by(&quot;age&quot;,&quot;name&quot;).distinct(&quot;age&quot;)<br># this is correct too.</pre><p><strong>d.</strong> While using <em>values()</em> with <em>distinct() together then please </em>remember ordering by fields can affect the results, regarding there is a <a href="https://docs.djangoproject.com/en/dev/ref/models/querysets/#distinct">note</a> in the Django doc please take a look at it.</p><h3>Conclusion</h3><ol><li><em>distinct()</em> query method used to remove duplicates.</li><li><strong>DISTINCT</strong> <strong>ON</strong> expression only applicable to PostgreSQL(I did not check in the Oracle database please let me know in the comment section).</li><li><em>order_by</em> fields are always available in the <em>select</em> statement.</li><li>use <em>order_by with distinct to predict the results.</em></li><li>be careful with model meta default ordering with related filed order in order_by (go through the Django website for more in-depth information).</li></ol><p>******If you found this article helpful please follow me on MEDIUM.*******</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6f45ee7c84a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/djangotube/django-distinct-query-method-introduction-a6f45ee7c84a">Django distinct() query method introduction</a> was originally published in <a href="https://medium.com/djangotube">Django lions 🔥</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploy Django using Postgres, Nginx in digital ocean ubuntu droplet.]]></title>
            <link>https://medium.com/djangotube/deploy-django-using-postgres-nginx-in-digital-ocean-ubuntu-droplet-d4e1de81254f?source=rss----26e6b1ba0dee---4</link>
            <guid isPermaLink="false">https://medium.com/p/d4e1de81254f</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[supervisor]]></category>
            <category><![CDATA[web-deployment]]></category>
            <category><![CDATA[nginx]]></category>
            <dc:creator><![CDATA[Hemanth S P]]></dc:creator>
            <pubDate>Sat, 08 Jan 2022 11:04:21 GMT</pubDate>
            <atom:updated>2024-08-16T16:26:52.120Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Deploy Django using Postgres, Nginx in digital ocean" src="https://cdn-images-1.medium.com/max/1024/0*K3NKHHOHoJqRm6Lc" /><figcaption>Photo by <a href="https://unsplash.com/@kirill2020?utm_source=medium&amp;utm_medium=referral">Kirill Sh</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Hi, To deploy any web application there are multiple ways however in this article I will show the simplest and traditional way of deploying Django to digital ocean droplets.</p><h4>Step 1: Digital Ocean sign in or sign up</h4><blockquote>sign in or sign up(if you signing up for the first time then use this <a href="https://m.do.co/c/6d67b64c1a9e"><strong><em>referral</em></strong></a> <strong>link</strong>) to the digital ocean account.</blockquote><h4>Step 2: Create Droplet</h4><blockquote>Click on the create button to create one droplet on the top right of the screen, it is shown in the below image</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/338/1*nkPlNS5pRj1gN54xpXSNrg.png" /><figcaption>Click on the Droplets option from the dropdown</figcaption></figure><h4>Step 3: configure droplet</h4><blockquote>configure your droplet based on your customer, for the demonstration purpose I am going to select ubuntu</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vseizLC46nUrRoihGrWhRw.png" /><figcaption>select ubuntu</figcaption></figure><blockquote>choose a plan</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/456/1*zK8IqGpRuO_roYOMWFrJ0g.png" /><figcaption>choose a plan</figcaption></figure><blockquote>choose the location</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*Z9YJbmhIRG8efzrI7a32BQ.png" /><figcaption>location</figcaption></figure><blockquote>choose the ssh or password</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3hFI2jx2164blVt1A8WXYg.png" /><figcaption>ssh or password</figcaption></figure><blockquote>Click on the create button</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/176/1*bzR8kbJXtS2P_Qpd8VRE5w.png" /><figcaption>create button</figcaption></figure><p>and it will take several minutes to create a droplet for you and once done the page is automatically redirected to your available droplet screen so the final droplet you can view like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KT15H3oXk2HdI7a0_Y0EoQ.png" /><figcaption>final droplet image</figcaption></figure><h4>Step 4: Access the created droplet</h4><blockquote>you can access the created droplet by using a terminal(from your local pc) or by clicking the console link as shown in the above photo at the top right.</blockquote><h4>Step 5: push the code to the remote server(droplet).</h4><blockquote>I have a <a href="https://github.com/hemanth-sp/django-demo-app-with-postgress">demo</a> Django project and I will push it to GitHub and then I will pull it in the remote server.</blockquote><h4>Step 6: log in to your droplet</h4><blockquote>open the terminal and type as below</blockquote><pre>$ ssh root@your ipv4 address<br>for example<br>$ ssh root@143.244.140.67</pre><p>and if it is the first time type as <strong>yes.</strong></p><p>Enter the password to login</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*botzR2EFeC9evNiWZQv2rg.png" /><figcaption>login into the droplet or server</figcaption></figure><p>and we need to pull code in the destination folder this path is in</p><pre>$ cd /var/www/</pre><p>by default, the <strong>www</strong> folder won&#39;t be inside the var folder so to create the <strong>www</strong> folder we must install Nginx</p><pre>$ sudo apt-get update</pre><pre>$ sudo apt-get install nginx</pre><pre># Verify the Installation<br>$ nginx -v</pre><pre>you can start and verify it by running:<br>$ sudo systemctl start nginx<br>$ sudo systemctl status nginx</pre><p>and move inside the</p><pre> $ cd /var/www/</pre><p>pull code from git hub repository using git clone</p><pre># for example<br>git clone https://github.com/hemanth-sp/django-demo-app-with-postgress.git</pre><p>once done, then go inside the project folder</p><pre>root@ubuntu-s-1vcpu-1gb-blr1–01:/var/www# cd django-demo-app-with-postgress/</pre><p>create a virtual environment in the project folder itself or wherever you want, I am using the python 3.8 version so I will create a virtual one like this</p><pre>$ python3.8 -m venv venv</pre><pre># and if you got an error then install python3.8<br>$ apt install python3.8-venv</pre><p>do LS to check everything in one place</p><pre>root@ubuntu-s-1vcpu-1gb-blr1–01:/var/www/django-demo-app-with-postgress# ls<br>dashboard  db.sqlite3  django_awesome  manage.py  requirements.txt  static  templates  venv</pre><p>now activate virtual and install requirements from requirements.txt</p><pre>root@ubuntu-–01:/var/www/django-demo-app-with-postgress# source venv/bin/activate<br>(venv) root@ubuntu-–01:/var/www/django-demo-app-with-postgress#<br>(venv) root@ubuntu--01:/var/www/django-demo-app-with-postgress# pip3 install -r requirements.txt</pre><p>while installing requirements if got an error from <strong>psycopg2</strong> then use the below commands to install the additional dependencies of python</p><pre>sudo apt install libpq-dev python3-dev<br>sudo apt install build-essential<br>sudo apt-get install python3.8-dev</pre><h4>Step 7: Create a database</h4><pre># install postgresql in server<br># or use postgresql-11, postgresql-12 or install latestest version</pre><pre>$ sudo apt-get -y install postgresql</pre><pre># Connect to PostgreSQL<br>lr1-01:/var/www/django-demo-app-with-postgress# su - postgres</pre><pre>postgres@ubuntu-s-1vcpu-1gb-blr1-01:~$ psql</pre><pre># execute this commond command to create db and create and alter user</pre><pre>postgres=# create user django;create database demodb;alter role django with password &#39;djangopassword&#39;;grant all privileges on database demodb to django;alter database demodb owner to django;</pre><p>Results from Postgres will be like</p><pre>CREATE ROLE<br>CREATE DATABASE<br>ALTER ROLE<br>GRANT<br>ALTER DATABASE</pre><p>type <strong>exit</strong> to close the <em>PostgreSQL.</em></p><h4>Step 8: do migrate</h4><pre>(venv) root@ubuntu-s-1vcpu-1gb-blr1–01:/var/www/django-demo-app-with-postgress# python manage.py migrate</pre><h4>Step 9: set static and media root</h4><pre>STATIC_URL = &#39;/static/&#39;<br>STATIC_ROOT = os.path.join(BASE_DIR, &#39;whole-static&#39;)</pre><pre>MEDIA_URL = &#39;/media/&#39;<br>MEDIA_ROOT =  os.path.join(BASE_DIR, &#39;whole-media&#39;)</pre><p>and <strong>STATICFILES_DIRS</strong> used to collect the static files from the static folder inside the project folder</p><pre>STATICFILES_DIRS = [<br>  os.path.join(BASE_DIR, ‘static’),<br>]</pre><p><strong>Create folders</strong></p><pre>(venv) root@ubuntu-:/var/www/django-demo-app-with-postgress# mkdir whole-static<br>(venv) root@ubuntu:/var/www/django-demo-app-with-postgress# mkdir whole-media</pre><p>type below commands to collect the static</p><pre>$ python manage.py collectstatic</pre><pre>1970 static files copied to ‘/var/www/django-demo-app-with-postgress/whole-static’</pre><h4>Step 10: Configure Nginx</h4><p>navigate to</p><pre>cd /etc/nginx/sites-available/</pre><p>delete default file because of no use in that and also remove default in the <strong>sites-enabled</strong> folder.</p><pre>rm default</pre><p>create new called web</p><pre>(venv) root@ubuntu-s-1vcpu-1gb-blr1–01:/etc/nginx/sites-available# touch web</pre><p>and edit the web using vi or nano.</p><pre>upstream app_server {<br>   server unix:/var/www/django-demo-app-with-postgress/web.sock fail_timeout=0;<br>}<br>server {<br> <br>     location = /favicon.ico { access_log off; log_not_found off; }<br>     <br>     server_name 143.244.140.67;<br>     <br>     # add here the ip address of your server<br>     <br>     keepalive_timeout 5;<br>     client_max_body_size 4G;<br>     <br>     access_log /var/log/nginx/access.log;<br>     error_log /var/log/nginx/error.log;<br>     <br>     <br>     location /static/ {<br>       alias /var/www/django-demo-app-with-postgress/whole-static/;<br>     }<br>     <br>     location /media/ {<br>       alias /var/www/django-demo-app-with-postgress/whole-media/;<br>     }<br>     # checks for static file, if not found proxy to app<br>     <br>     location / {<br>       try_files $uri @proxy_to_app;<br>     }<br>     location @proxy_to_app {<br>     proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;<br>     proxy_set_header Host $http_host;<br>     proxy_redirect off;<br>     #proxy_pass http://app_server;<br>     if (!-f $request_filename) {<br>       proxy_pass http://app_server;<br>       break;<br>     }<br> }</pre><pre>}</pre><p>and save this, please have a look at every line of the file because the project path is important then make a soft link.</p><pre>(venv) root@ubuntu-s-1vcpu-1gb-blr1–01:~# ln -s /etc/nginx/sites-available/web /etc/nginx/sites-enabled/web</pre><p>verify <strong>Nginx</strong> configuration is working or not!</p><pre>(venv) root@ubuntu-s-1vcpu-1gb-blr1–01:/etc/nginx/sites-enabled# nginx -t</pre><p>restart the Nginx</p><pre>sudo systemctl restart nginx</pre><h4>Step 11: Configure gunicorn</h4><p>install gunicorn web server inside the virtual because it is required for the supervisor to run.</p><pre>(venv) root@ubuntu-s-1vcpu-1gb-blr1–01:~# pip3 install gunicorn</pre><h4>Step 12: Configure supervisord</h4><p>Install supervisor by entering the following commands in the terminal</p><pre>sudo apt update<br>sudo apt install supervisor</pre><p>navigate to</p><pre><strong>cd /etc/supervisor/conf.d/</strong></pre><pre>(venv) root@ubuntu-s-1vcpu-1gb-blr1–01:/etc/supervisor/conf.d# touch web.conf<br>(venv) root@ubuntu-s-1vcpu-1gb-blr1-01:/etc/supervisor/conf.d# nano web.conf</pre><p>and paste the following code inside the <strong>web.conf</strong> file</p><pre>[program:django-demo]<br>command=/var/www/django-demo-app-with-postgress/venv/bin/gunicorn — workers 3 — bind unix:/var/www/django-demo-app-with-postgress/web.sock django_awesome.wsgi<br>directory=/var/www/django-demo-app-with-postgress<br>autostart=true<br>autorestart=true<br>stderr_logfile=/var/log/gunicorn_supervisor.out.log<br>stdout_logfile=/var/log/gunicorn_supervisor.log<br>user=root<br>redirect_stderr=true<br>environment=LANG=en_US.UTF-8,LC_ALL=en_US.UTF-8</pre><p>Update the superviosr</p><pre><strong>supervisorctl reread</strong></pre><p>Django-demo: available</p><pre><strong>supervisorctl update</strong></pre><p>Django-demo: added process group</p><pre><strong>supervisorctl status</strong></pre><p>Django-demo STARTING</p><pre><strong>supervisorctl restart django-demo</strong></pre><p>navigate to create log files for the supervisor</p><pre>cd /var/log</pre><pre>(venv) root@ubuntu-s-1vcpu-1gb-blr1–01:/var/log# touch gunicorn_supervisor.out.log<br>(venv) root@ubuntu-s-1vcpu-1gb-blr1–01:/var/log# touch gunicorn_supervisor.log</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nNNuKa1PAGcnAzN3R8Nbow.png" /><figcaption>final deployment image</figcaption></figure><h4>So next if new code push to GitHub then you have to do this much only</h4><ol><li><strong>ssh root@ipv4 address</strong>(login to server)</li><li><strong>cd /var/www/django-demo-app-with-postgress/</strong> (go to folder)</li><li><strong>git pull</strong> (to get the latest code)</li><li><strong>source venv/bin/activate</strong> (activate virtual)</li><li><strong>migrate</strong> (if any model change)</li><li><strong>collectstatic </strong>(if any static file changes)</li><li><strong>supervisorctl status </strong>( to check the status of the service)</li><li><strong>supervisorctl restart </strong>django-demo (to restart services and important)</li></ol><h3>Conclusion</h3><p>This article simply shows the way of deploying the Django code in the ubuntu server however still adding domain and enabling SSL certificate remaining, and make sure to off debug while deploying and please take a moment on Django website to find out more on security instructions before deploying the code</p><pre>                  python manage.py check — deploy</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4e1de81254f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/djangotube/deploy-django-using-postgres-nginx-in-digital-ocean-ubuntu-droplet-d4e1de81254f">Deploy Django using Postgres, Nginx in digital ocean ubuntu droplet.</a> was originally published in <a href="https://medium.com/djangotube">Django lions 🔥</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to install Django with a specific version?]]></title>
            <link>https://medium.com/djangotube/how-to-install-django-with-a-specific-version-9897c8b9ad7e?source=rss----26e6b1ba0dee---4</link>
            <guid isPermaLink="false">https://medium.com/p/9897c8b9ad7e</guid>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Hemanth S P]]></dc:creator>
            <pubDate>Wed, 21 Jul 2021 11:50:15 GMT</pubDate>
            <atom:updated>2024-08-16T16:28:29.184Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="How to install Django with a specific version" src="https://cdn-images-1.medium.com/max/1024/0*8iP3dkLDiW9pT_6M" /><figcaption>Photo by <a href="https://unsplash.com/@vedranafilipovic?utm_source=medium&amp;utm_medium=referral">Vedrana Filipović</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Hi, in this article I will show simple commands to install Django with a specific version. and run commands inside a single terminal because every command requires virtual should be active.</p><h3><strong>Create a virtual environment</strong></h3><ol><li>I used Python 3.8 you can use your required Python interpreter version.</li></ol><pre>python3.8 -m venv venv</pre><p>2. Activate venv virtual environment.</p><pre>source venv/bin/activate</pre><h3>Install Django</h3><ol><li>Now you can install Django by specifying the version.</li></ol><pre>pip3 install django==2.2</pre><p>or</p><pre>pip3 install django==3.2 # your required version</pre><p>2. Create a Django project.</p><pre>django-admin startproject mysite</pre><p>3. Run the server.</p><pre>python manage.py runserver</pre><figure><img alt="Django v2.2" src="https://cdn-images-1.medium.com/max/1024/1*VsHqdAjzDh6prXR8Mx0XSQ.png" /><figcaption>Django v2.2</figcaption></figure><figure><img alt="Django v2.2" src="https://cdn-images-1.medium.com/max/1024/1*2X96zLzyC_XwsHiJRcSB1w.png" /><figcaption>Django v.2.2</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XoqRl14XTMLdYoXyR3MIQA.png" /><figcaption>Django v3.2</figcaption></figure><figure><img alt="Django v3.2" src="https://cdn-images-1.medium.com/max/1024/1*_2vpaiWWGuyKBPIuPyNWuw.png" /><figcaption>Django v3.2</figcaption></figure><h3>Conclusion</h3><p>I showed you how to install Django with version, I hope you find this article useful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9897c8b9ad7e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/djangotube/how-to-install-django-with-a-specific-version-9897c8b9ad7e">How to install Django with a specific version?</a> was originally published in <a href="https://medium.com/djangotube">Django lions 🔥</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Django rest API crud example with unit testing]]></title>
            <link>https://medium.com/djangotube/django-rest-api-curd-example-61c3a29b22ed?source=rss----26e6b1ba0dee---4</link>
            <guid isPermaLink="false">https://medium.com/p/61c3a29b22ed</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[django-rest-api-example]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[curd]]></category>
            <dc:creator><![CDATA[Hemanth S P]]></dc:creator>
            <pubDate>Wed, 03 Feb 2021 17:39:30 GMT</pubDate>
            <atom:updated>2024-08-16T16:30:11.505Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi, in this article I am going to show you what are the different ways of creating <strong>crud</strong> in the <strong>Django</strong> <strong>rest framework</strong> with the <strong>unit testing</strong>.</p><figure><img alt="Django rest crud example API with unit testing" src="https://cdn-images-1.medium.com/max/1024/0*p6xtzckjnRrH4SU_" /><figcaption>Photo by <a href="https://unsplash.com/@jannerboy62?utm_source=medium&amp;utm_medium=referral">Nick Fewings</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><ol><li>Function-based crud</li><li>class-based API view crud</li><li>Generic class-based view crud</li><li>Generic class-based view with views router crud</li><li>Viewset crud</li><li>ModelViewset crud</li></ol><h3><strong>1. Function-based crud</strong></h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b162bdfbd722293ec8500dba04450bac/href">https://medium.com/media/b162bdfbd722293ec8500dba04450bac/href</a></iframe><p>as above shows everything is simple and line by line and two URLs added at the bottom for unit case check GitHub repo.</p><h3>2. class-based API view crud</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2dc2057b58dedf4d88ab4edc5e48f57e/href">https://medium.com/media/2dc2057b58dedf4d88ab4edc5e48f57e/href</a></iframe><p>Class-based API views inhered from view class so it has GET, POST, etc.. methods</p><pre>class APIView(View): <br>   # The following policies may be set at either globally, or per-   view. <br>   renderer_classes = api_settings.DEFAULT_RENDERER_CLASSES<br>   parser_classes = api_settings.DEFAULT_PARSER_CLASSES<br>   authentication_classes = api_settings.DEFAULT_AUTHENTICATION_CLASSES<br>   throttle_classes = api_settings.DEFAULT_THROTTLE_CLASSES<br>   permission_classes = api_settings.DEFAULT_PERMISSION_CLASSES<br>   content_negotiation_class = api_settings.DEFAULT_CONTENT_NEGOTIATION_CLASS <br>   metadata_class = api_settings.DEFAULT_METADATA_CLASS<br>   versioning_class = api_settings.DEFAULT_VERSIONING_CLASS</pre><h3>3. Generic class-based view crud</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7d0f10c811e874b5ff9689837218532/href">https://medium.com/media/d7d0f10c811e874b5ff9689837218532/href</a></iframe><p>generics have default or sample concrete method because it inherited from <strong>mixins</strong> defined in the <strong>queryset</strong> and <strong>serializer</strong> class. After all, it inherited from the <strong>GenericAPIView.</strong></p><h3>4. Generic class-based view with views router crud</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/830643b09d977a1bc5cd4851d528b83e/href">https://medium.com/media/830643b09d977a1bc5cd4851d528b83e/href</a></iframe><p>for this generic view, I added the <strong>Viewset</strong> class because I want to map a simple router <strong>GET</strong> to <strong>list</strong> or <strong>retrieve</strong>, <strong>POST</strong> to <strong>create</strong>, and <strong>PUT</strong> to <strong>update</strong>, using the default router it automatically generates the URLs for use,</p><p>if you use the <strong>Django-extension</strong> package using the below command you can check the generated URLs from the default router</p><blockquote><strong>python manage.py show_urls</strong></blockquote><p>and note <strong>reverse</strong> function to generate URL using app name and base name, for example.</p><blockquote><strong>reverse(“curd:students-list) or reverse(“curd:students-detail)</strong></blockquote><p>check unit test cases in the Github repository by changing branches for better understanding.</p><pre>class ViewSet(ViewSetMixin, views.APIView): <br>    “”” The base ViewSet class does not provide any actions by default. “”” <br>    pass</pre><h3><strong>5. Viewset crud</strong></h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4daefecffe16dbc962266b3cbf2f258a/href">https://medium.com/media/4daefecffe16dbc962266b3cbf2f258a/href</a></iframe><p>The base ViewSet class does not provide any actions by default but it forwards from GET to list, POST to create, etc... other verbs, as mentioned above</p><h3>6. ModelViewset crud</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2ac5dfd95b30dcaf486bb340be0180a7/href">https://medium.com/media/2ac5dfd95b30dcaf486bb340be0180a7/href</a></iframe><p>A viewset that provides default `<strong>create</strong>()`, `<strong>retrieve</strong>()`, `<strong>update</strong>()`, `<strong>partial_update</strong>()`, `<strong>destroy</strong>()` and `<strong>list</strong>()` actions.</p><p>because it is inherited from all the concrete classes.</p><pre>class ModelViewSet(mixins.CreateModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, mixins.ListModelMixin, GenericViewSet):</pre><p>Unit testing and model code, you check the repository.</p><p><a href="https://github.com/hemanth-sp/django_rest_curd">hemanth-sp/django_rest_curd</a></p><p>And for the complete <strong>Django rest view hierarchy</strong> or <strong>inheritance</strong> <strong>hierarchy</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e53f42aff020045a0ef6dce46847de8/href">https://medium.com/media/6e53f42aff020045a0ef6dce46847de8/href</a></iframe><h4><strong>Conclusion</strong></h4><p>In this article, I showed the different ways of creating crud operations in the Django rest framework with unit test cases. if you have a doubt please add them in the comment section below I will try to answer them, thank you please follow for more.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61c3a29b22ed" width="1" height="1" alt=""><hr><p><a href="https://medium.com/djangotube/django-rest-api-curd-example-61c3a29b22ed">Django rest API crud example with unit testing</a> was originally published in <a href="https://medium.com/djangotube">Django lions 🔥</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Django SQLite to PostgreSQL database migration]]></title>
            <link>https://medium.com/djangotube/django-sqlite-to-postgresql-database-migration-e3c1f76711e1?source=rss----26e6b1ba0dee---4</link>
            <guid isPermaLink="false">https://medium.com/p/e3c1f76711e1</guid>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[sqlite]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[data-migration]]></category>
            <dc:creator><![CDATA[Hemanth S P]]></dc:creator>
            <pubDate>Fri, 22 Jan 2021 05:35:50 GMT</pubDate>
            <atom:updated>2024-08-16T16:34:15.845Z</atom:updated>
            <content:encoded><![CDATA[<p>Django SQLite to PostgreSQL database migration</p><figure><img alt="Django SQLite to Postgres database migration" src="https://cdn-images-1.medium.com/max/1024/0*6EYDBD0BXoqNsXWU" /><figcaption>Photo by <a href="https://unsplash.com/@jcraice?utm_source=medium&amp;utm_medium=referral">Julia Craice</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Hi All, in this article I&#39;m going to show you how to move data from SQLite to Postgres.</p><p>Steps are</p><ol><li>Take SQLite whole DB dumpdata fixture backup</li><li>Create Postgres DB with user and password</li><li>Change settings.py</li><li>import fixture using loaddata</li></ol><h4>1. Take SQLite whole DB dumpdata fixture backup.</h4><p>first, you need to take the backup of the whole DB using the below command</p><pre>python manage.py dumpdata &gt; whole.json</pre><p>in this command, some users prefer to use the natural foreign key and primary key but I won&#39;t suggest using the bellow command until you get an error while restoring(loaddata) data to Postgres</p><pre>python manage.py dumpdata — natural-foreign — natural-primary &gt; whole.json</pre><p>this commands will generate the whole.json in the root of your projects, this means you generated the dumpdata from SQLite in JSON fixture format.</p><h4>2. Create Postgres DB with user and password.</h4><p>in this step, you need to install Postgres on your OS like Ubuntu or Mac (google), after installation is done, log in to Postgres</p><pre>sudo su — postgres<br>psql</pre><p>and use the below command to create a user with a password and DB, and grant permission on DB from the user</p><pre>create user hero;create database my_db;alter role hero with password ‘my_db@123’;grant all privileges on database my_db to hero;alter database my_db owner to hero;</pre><h4>3. Change settings.py</h4><pre># install this package <br>pip install psycopg2</pre><pre>settings.py<br><br>DATABASES = {<br>  ‘default’: {<br>  ‘ENGINE’: ‘django.db.backends.postgresql_psycopg2’,<br>  ‘NAME’: ‘my_db’,<br>  ‘USER’ : ‘hero’,<br>  ‘PASSWORD’ : ‘my_db@123’,<br>  ‘HOST’ : ‘localhost’,<br>  ‘PORT’ : ‘5432’,<br>  }<br>}</pre><p>delete all the migrations files because we do not need all old migrations, instead, we will create one migration file per app. Use the below command to delete all migration files.</p><pre>find . -path “*/migrations/*.py” -not -name “__init__.py” -delete</pre><pre>find . -path “*/migrations/*.pyc” -delete</pre><p>do</p><pre>python manage.py makemigrations</pre><pre>python manage.py migrate</pre><p>now delete <strong>content types(mandatory steps)</strong> otherwise you will beautiful billions of errors</p><pre>python manage.py shell</pre><pre>from django.contrib.contenttypes.models import ContentType<br>ContentType.objects.all().delete()</pre><p>this means an empty Postgres DB is created with migration done. next, we need to load into Postgres db from fixtures.</p><h4>4. import fixture using loaddata.</h4><p>One main step is to <strong>disable all signals</strong> in projects otherwise you will get a unique constraint or object already created.</p><p>use the below command to load data to DB from fixtures</p><pre>python manage.py loaddata fixture/whole.json</pre><p>that is it, you successfully moved data from SQLite to Postgres using fixtures</p><p><strong>M</strong>y advice is to use SQLite only for development and do the above data migration in the initial stage of the projects because this fixture method requires huge pc RAM to loaddata, if your SQLite is more than 100MB it won&#39;t work.</p><p><strong>A</strong>nd if you are using groups and permissions then take dumpdata without excluding the content types and permissions otherwise you will error while loaddata because groups depend on permission.</p><p><strong>A</strong>nd sometimes you need to change the model charfield to max_length size because dumpdata creates some space in charfield value so while importing loaddata you will error like “<em>in the model, field varying length 50 exceeds 50</em>”.</p><h3>Conclusion</h3><p><strong>I</strong>n this article, I showed how to convert SQLite to Postgres using the fixture method, I know you will get errors please let me know in the comment section below, and I will try to fix it</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3c1f76711e1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/djangotube/django-sqlite-to-postgresql-database-migration-e3c1f76711e1">Django SQLite to PostgreSQL database migration</a> was originally published in <a href="https://medium.com/djangotube">Django lions 🔥</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Django add start bootstrap-admin custom theme in your project]]></title>
            <link>https://medium.com/djangotube/tomdjango-use-startbootstrap-theme-in-project-50ae96ed2e0e?source=rss----26e6b1ba0dee---4</link>
            <guid isPermaLink="false">https://medium.com/p/50ae96ed2e0e</guid>
            <category><![CDATA[startbootstrap-theme]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[custom-theme]]></category>
            <category><![CDATA[django-theme]]></category>
            <dc:creator><![CDATA[Hemanth S P]]></dc:creator>
            <pubDate>Sun, 30 Aug 2020 17:27:16 GMT</pubDate>
            <atom:updated>2024-08-16T16:36:45.561Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aeEl5JMAM8PcK1hucDeo3w.png" /><figcaption>Django start bootstrap-admin example</figcaption></figure><p>Hi, In this article I am going to show you how to use startbootstrap admin theme in your project, so let&#39;s get started with the below steps</p><p>Steps are</p><ol><li>Create a Django project</li><li>Download startbootstrap admin theme</li><li>Create a static folder at the <em>root level</em> or <em>app level</em></li><li>Create a templates folder at the root level or app level</li><li>Create a layout with the base template</li><li>extends the base template and renders it</li><li>Github link to this article base template ready to use</li></ol><h3>1. Create a Django project</h3><p>if you have already created a project then you can skip this step. First, create virtual env</p><pre>python3 -m venv .venv<br>source .venv/bin/activate  # to activate virtual env</pre><p>create a Django project and name is django_awesome</p><pre>django-admin startproject django_awesome<br># install django <br>pip install django<br># run server<br>python manage.py runserver</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qNYPdjWaO9YEvMDOMFTlhw.png" /></figure><p>create an App called a dashboard inside the project</p><pre>python manage.py startapp dashboard</pre><h3>2. Download startbootstrap theme</h3><p>download the theme from GitHub and extract it <a href="https://github.com/StartBootstrap/startbootstrap-sb-admin-2">https://github.com/StartBootstrap/startbootstrap-sb-admin-2</a></p><h3>3. Create a static folder</h3><p>create one static folder at the <strong>root</strong> <strong>level</strong>(i always recommend this for every project except if I am not building the library) of the project and copy the image, scss, js, vendor, and CSS folder into a static folder. Add</p><pre>STATICFILES_DIRS = [<br>    os.path.join(BASE_DIR, ‘static’),<br>]</pre><h3>4. Create a templates folder at the root level</h3><p>create a templates folder at the root level of the project and inside that template, folder creates a <strong>layout</strong> folder and <em>create base.html,</em> <em>navbar.html, sidebar.html,</em> and <em>footer.html and </em>copy the related code from the downloaded admin theme<strong> index.html </strong>file into our 4 core files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*ZgTO-FqqvMtD0pleAQTgyg.png" /><figcaption>fig: main project folder structure</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*RZMsKly43aQ1lsgxfxNtMw.png" /><figcaption>fig: base or core HTML files</figcaption></figure><h3>5. Create a layout with the base template</h3><p>copy index.html(downloaded bootstrap theme) code into your layout HTML files( from startbootstrap theme(downloaded folder) index.html).</p><pre>‘DIRS’: [os.path.join(BASE_DIR, ‘templates’)],<br># add this in the settings.py file otherwise django will look only <br># app level templates</pre><h3>6. Extend the base template and render it</h3><p>render the dashboard main HTML using a simple function</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/909/1*UqSjcbBQIxPFYqEe11mA0Q.png" /><figcaption>dashboard folder</figcaption></figure><pre>def index(request):<br>    return render(request, ‘dashboard/dashboard.html’)</pre><blockquote>Note if you need use SCSS files instead of css files use django scss libraries</blockquote><h3>7. I pushed this awesome project in the git hub</h3><p>I have this awesome project I pushed to Github you can use this Theme for free because the theme is free</p><p><a href="https://github.com/hemanth-sp/django-startbootstrap-theme">hemanth-sp/django-startbootstrap-theme</a></p><h3>Conclusion</h3><p>Thank you for reading the article, In this article, I showed you how to use a custom theme set up for your Django project, I used this theme for my website take look and let me know your thoughts in the comments section below, and using this procedure you can install any custom theme you purchased online.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50ae96ed2e0e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/djangotube/tomdjango-use-startbootstrap-theme-in-project-50ae96ed2e0e">Django add start bootstrap-admin custom theme in your project</a> was originally published in <a href="https://medium.com/djangotube">Django lions 🔥</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Django custom middleware introduction]]></title>
            <link>https://medium.com/djangotube/django-custom-middleware-introduction-2d9e999c5377?source=rss----26e6b1ba0dee---4</link>
            <guid isPermaLink="false">https://medium.com/p/2d9e999c5377</guid>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[custom]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[middleware]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Hemanth S P]]></dc:creator>
            <pubDate>Fri, 01 May 2020 07:31:16 GMT</pubDate>
            <atom:updated>2024-08-16T16:38:55.529Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="django custom middleware" src="https://cdn-images-1.medium.com/max/1024/0*jeABrcPV04kwIdrY" /><figcaption>Photo by <a href="https://unsplash.com/@wilhelmgunkel?utm_source=medium&amp;utm_medium=referral">Wilhelm Gunkel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Hi, in this article I am going to explain the simple introduction on</p><ol><li>Django middleware</li><li>Built-in Django middleware</li><li>custom middleware</li><li><strong><em>Django middleware</em></strong></li></ol><p>a) What is Django middleware?</p><blockquote>In django, middleware is a framework of attached into Django’s request/response processing. It’s a light, low-level “plugin” system for globally altering Django’s input or output. It allows you to plug in extra code that will be executed at specific points of the HTTP request/response cycle</blockquote><p>b) Why it is required?</p><blockquote>because of the <strong>attach</strong> nature of the middleware some time we need to add additional functionality while processing every incoming request and every out going response for example user in request.user based on token or session using AuthenticationMiddleware, elimination blacklisted ip address, attach aditional information, etc..</blockquote><p>c) How does it work?</p><blockquote>An example of this is the SessionMiddleware, which is used to associate sessions to users. when http request made midldleware will execute like onion type layer like one by one, when execution flow enter into your middleware <strong>process_request </strong>method will execute after that <strong>get_response</strong> callable called and returns a middleware finally <strong>process_response </strong>method will execute.</blockquote><p><strong>2. Built-in Django middleware</strong></p><p>when you install Django by default Django will add the following middleware in settings.py, for some times you can remove some unnecessary middleware from the list.</p><pre>MIDDLEWARE = [<br>    &#39;django.middleware.security.SecurityMiddleware&#39;,<br>    &#39;django.contrib.sessions.middleware.SessionMiddleware&#39;,<br>    &#39;django.middleware.common.CommonMiddleware&#39;,<br>    &#39;django.middleware.csrf.CsrfViewMiddleware&#39;,<br>    &#39;django.contrib.auth.middleware.AuthenticationMiddleware&#39;,<br>    &#39;django.contrib.messages.middleware.MessageMiddleware&#39;,<br>    &#39;django.middleware.clickjacking.XFrameOptionsMiddleware&#39;,<br>]</pre><p>for example, here Django includes a middleware component called, <a href="https://docs.djangoproject.com/en/3.0/ref/middleware/#django.contrib.auth.middleware.AuthenticationMiddleware"><strong>AuthenticationMiddleware</strong></a>that associates users with requests using sessions. like this, we can implement our middleware.</p><p><strong>3. Custom middleware</strong></p><p><em>Note: </em>I am using class-based middleware. if you want you can write function-based middleware that may look like Python decorator code<em>.</em></p><p><strong><em>custom</em></strong> middleware by extending the MiddlewareMixin</p><pre>from django.utils.deprecation import MiddlewareMixin<br><br>class MySimpleMiddleware(MiddlewareMixin):<br><br>    def __init__(self, get_response):<br>        self.get_response = get_response<br><br>    def process_request(self, request):<br>            print(&quot;something&quot;)<br>            try:<br>                request.session[&#39;my_message&#39;] = &quot;boss&quot;<br>            except:<br>                request.session[&#39;my_message&#39;]  = &quot;ok&quot;</pre><p>in the above code I wrote the <strong>MySimpleMiddleware</strong>, which extents from MiddlewareMixin so we no need to write <strong>__call__</strong> method, here only we are overriding the process_request means before processing my_view add my_message and boss key value pair in the request. if you want you can override <strong>process_response</strong> method also.</p><p><strong>OR</strong></p><pre>class MySimpleMiddleware():<br>    def __init__(self, get_response):<br>        self.get_response = get_response<br><br>    def __call__(self, request):<br>        def process_request(request):<br>            try:<br>                request.session[&#39;my_message&#39;] =&quot;bossk&quot;<br>            except:<br>                request.session[&#39;my_message&#39;]  = &quot;ok&quot;<br>        response = self.get_response(process_request(request))<br>        return response</pre><p>in the above example, <strong>process_request and process_response</strong> are not required because we are writing the middleware from scratch.</p><p>At last do not forget to add your middleware in the <strong>settings.py</strong> <strong>middleware</strong> list, like,</p><pre>MIDDLEWARE = [<br>    &#39;django.middleware.security.SecurityMiddleware&#39;,<br>    &#39;django.contrib.sessions.middleware.SessionMiddleware&#39;,<br>    &#39;django.middleware.common.CommonMiddleware&#39;,<br>    &#39;django.middleware.csrf.CsrfViewMiddleware&#39;,<br>    &#39;django.contrib.auth.middleware.AuthenticationMiddleware&#39;,<br>    &#39;django.contrib.messages.middleware.MessageMiddleware&#39;,<br>    &#39;django.middleware.clickjacking.XFrameOptionsMiddleware&#39;,<br>    &#39;app_name.your_middleware_file_name.MySimpleMiddleware&#39;,<br>]</pre><h3><strong>Conclusion</strong></h3><p>This article simply explained what middleware is, how to use it, when to use it, why to use it, and how to write custom middleware using a class-based view. If you have doubts, please feel free to ask here.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d9e999c5377" width="1" height="1" alt=""><hr><p><a href="https://medium.com/djangotube/django-custom-middleware-introduction-2d9e999c5377">Django custom middleware introduction</a> was originally published in <a href="https://medium.com/djangotube">Django lions 🔥</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>