<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: JMG</title>
    <description>The latest articles on DEV Community by JMG (@mungaigikure).</description>
    <link>https://dev.to/mungaigikure</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F246928%2Fd39a71ff-0b23-4b7f-a103-f4431d73b383.png</url>
      <title>DEV Community: JMG</title>
      <link>https://dev.to/mungaigikure</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/mungaigikure"/>
    <language>en</language>
    <item>
      <title>Using Multiple DBs - Django</title>
      <dc:creator>JMG</dc:creator>
      <pubDate>Wed, 16 Jul 2025 17:14:45 +0000</pubDate>
      <link>https://dev.to/mungaigikure/using-multiple-dbs-django-8o6</link>
      <guid>https://dev.to/mungaigikure/using-multiple-dbs-django-8o6</guid>
      <description>&lt;ol&gt;
&lt;li&gt;Advantages&lt;/li&gt;
&lt;li&gt;Disadvantages -  relation between dbs&lt;/li&gt;
&lt;li&gt;Set up&lt;/li&gt;
&lt;li&gt;Scenarios where you can use multiple DBs in your project (authentication eg Fargo)&lt;/li&gt;
&lt;/ol&gt;

</description>
    </item>
    <item>
      <title>Custom Commands in Django</title>
      <dc:creator>JMG</dc:creator>
      <pubDate>Thu, 25 Jan 2024 17:28:34 +0000</pubDate>
      <link>https://dev.to/mungaigikure/custom-commands-in-django-1b5h</link>
      <guid>https://dev.to/mungaigikure/custom-commands-in-django-1b5h</guid>
      <description>&lt;p&gt;Hello there! We are going to learn how to write simple custom Django commands. I will break down this lesson into 3 sections;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Introduction&lt;/li&gt;
&lt;li&gt;Setting up the commands&lt;/li&gt;
&lt;li&gt;Calling the commands&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Introduction&lt;/strong&gt;
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Create a generic Django project called &lt;code&gt;resource_center&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Make migrations and migrate your database.&lt;/li&gt;
&lt;li&gt;Create a Django app called &lt;code&gt;books&lt;/code&gt;. Register this app in &lt;code&gt;settings.py&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;In your &lt;code&gt;book/models.py&lt;/code&gt; create a model &lt;code&gt;Book&lt;/code&gt; as shown below;
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="c1"&gt;# books/models.py
&lt;/span&gt;
&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="n"&gt;django&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;models&lt;/span&gt;

&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Book&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;models&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;Model&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="n"&gt;name&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;models&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;CharField&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;max_length&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;50&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;author&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;models&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;CharField&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;max_length&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;20&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Make migrations and migrate your database.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Setting Up Commands&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Django convention dictates that custom commands have to live inside the &lt;code&gt;project/app/management/commands&lt;/code&gt; directory of your project. In this case, this will be &lt;code&gt;resource_center/management/commands&lt;/code&gt;.&lt;br&gt;
Navigate to your &lt;code&gt;books&lt;/code&gt; folder and create a folder named &lt;code&gt;management&lt;/code&gt;. Create a subfolder called &lt;code&gt;commands&lt;/code&gt;.&lt;br&gt;
Create a file inside the &lt;code&gt;commands&lt;/code&gt; folder and name it &lt;code&gt;books_creator.py&lt;/code&gt;.&lt;br&gt;
Add the following code;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="c1"&gt;# resource_center/books/management/commands/books_creator.py
&lt;/span&gt;&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="n"&gt;django.core.management.base&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;BaseCommand&lt;/span&gt;
&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="n"&gt;resource_center.books.models&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;Book&lt;/span&gt;


&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Command&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;BaseCommand&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="n"&gt;help&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;Create initial data for the project&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;add_arguments&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;parser&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="c1"&gt;# Positional arguments
&lt;/span&gt;        &lt;span class="n"&gt;parser&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;add_argument&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;count&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;help&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;Any number&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nb"&gt;type&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

        &lt;span class="c1"&gt;# Named (optional) arguments
&lt;/span&gt;        &lt;span class="n"&gt;parser&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;add_argument&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
            &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;--delete&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="n"&gt;help&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;Delete books instead of creating them&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;handle&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="n"&gt;args&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="o"&gt;**&lt;/span&gt;&lt;span class="n"&gt;kwargs&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="n"&gt;count&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;kwargs&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;count&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="nf"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;The current count is &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;count&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;kwargs&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;delete&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;]:&lt;/span&gt;
            &lt;span class="n"&gt;Book&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;objects&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;all&lt;/span&gt;&lt;span class="p"&gt;().&lt;/span&gt;&lt;span class="nf"&gt;delete&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
        &lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;Book&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;objects&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get_or_create&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
                &lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;The Lord of the Rings&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                &lt;span class="n"&gt;author&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;J.R.R. Tolkien&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;
            &lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="n"&gt;Book&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;objects&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get_or_create&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
                &lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;The Hobbit&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                &lt;span class="n"&gt;author&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;J.R.R. Tolkien&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;
            &lt;span class="p"&gt;)&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Our class &lt;code&gt;Command&lt;/code&gt; inherits from Django's &lt;code&gt;BaseCommand&lt;/code&gt;.&lt;br&gt;
The class variable &lt;code&gt;help&lt;/code&gt; describes what the custom command aims to achieve, more like the &lt;code&gt;help_text&lt;/code&gt; in your model fields.&lt;/p&gt;

&lt;p&gt;The method &lt;code&gt;add_arguments&lt;/code&gt; is used to instruct the command to expect arguments which may be optional.&lt;/p&gt;

&lt;p&gt;The method &lt;code&gt;handle&lt;/code&gt; handles (pun intended 😅) your logic.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Calling the commands&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;To call your commands, call them in the following format;&lt;br&gt;
&lt;code&gt;python manage.py &amp;lt;custom_command_file_name&amp;gt;&lt;/code&gt;. Do not include the file's &lt;code&gt;.py&lt;/code&gt; extension.&lt;br&gt;
In this case, our command will be called as&lt;/p&gt;

&lt;p&gt;&lt;code&gt;python manage.py books_creator &amp;lt;count&amp;gt;&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;count&lt;/code&gt; is any number of your choice. This is a positional argument that we can not ignore. If ignored, it will raise the following error; &lt;code&gt;manage.py books_creator: error: the following arguments are required: count&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The command with our &lt;code&gt;count&lt;/code&gt; positional argument will be as follows;&lt;br&gt;
&lt;code&gt;python manage.py books_creator 16&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;If you add the optional named arguments, you get a command like this;&lt;br&gt;
&lt;code&gt;python manage.py books_creator 16 --delete=true&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;That's it!&lt;/p&gt;

</description>
      <category>django</category>
      <category>beginners</category>
      <category>python</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Set up and Load Initial Data in Django</title>
      <dc:creator>JMG</dc:creator>
      <pubDate>Wed, 15 Dec 2021 09:14:17 +0000</pubDate>
      <link>https://dev.to/mungaigikure/set-up-and-load-initial-data-in-django-2gg8</link>
      <guid>https://dev.to/mungaigikure/set-up-and-load-initial-data-in-django-2gg8</guid>
      <description>&lt;p&gt;&lt;strong&gt;Introduction&lt;/strong&gt;&lt;br&gt;
Sometimes there's a need to have a set of initial data once we spin up our application. Reasons vary, but the need is there. Django provides two ways of setting up and loading this initial data to our database.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Using Fixtures&lt;/li&gt;
&lt;li&gt;Using Migrations&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;For the purposes of this brief explanation, we will have a model, Book in our app called Main&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# main/models.py

from django import models

class Book(models.Model):
    name = models.CharField(max_length=50)
    author = models.CharField(max_length=20)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Using Fixtures
&lt;/h2&gt;

&lt;p&gt;A fixture is a collection of data that Django knows how to import into a database. In this specific approach to fixtures, our data is not going to be loaded automatically. We are going to create the fixture by hand, then load them by running a command.&lt;/p&gt;

&lt;h4&gt;
  
  
  Creating Fixtures
&lt;/h4&gt;

&lt;p&gt;First, we need a folder to hold our fixtures. We can create a folder called &lt;code&gt;fixtures&lt;/code&gt; at app level (in our app Main), or we can have all our fixtures at project level by defining &lt;code&gt;FIXTURE_DIRS&lt;/code&gt; in our &lt;code&gt;settings.py&lt;/code&gt;. &lt;br&gt;
FIXTURE_DIRS should contain a list of directories where Django should look for fixtures.&lt;/p&gt;

&lt;p&gt;In this case, I have set  FIXTURE_DIRS at project level to have it as:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# my_project/setting.py

FIXTURE_DIRS =  BASE_DIR / "fixtures" 

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Create the directory &lt;code&gt;fixtures&lt;/code&gt; at project level. Here, we are going to create our fixtures, which can be any of the following formats:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;JSON&lt;/li&gt;
&lt;li&gt;XML&lt;/li&gt;
&lt;li&gt;YAML&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;We are going to use JSON, so within our fixtures directory, let's create a file &lt;code&gt;books.json&lt;/code&gt;. I prefer to name the fixtures after the app that their models belong to.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# fixtures/books.json

[
  {
    "model": "main.book",
    "pk": 1,
    "fields": {
      "name": "Atomic Habits",
      "author": "James Clear",
    }
  },
  {
    "model": "main.book",
    "pk": 2,
    "fields": {
      "name": "Permanent Record",
      "author": "Edward Snowden",
    }
  }
]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Loading data
&lt;/h4&gt;

&lt;p&gt;Since we have created our fixtures by hand, we need to call the individually to load the data:&lt;/p&gt;

&lt;p&gt;python manage.py loaddata fixture_file_name&lt;/p&gt;

&lt;p&gt;&lt;code&gt;python manage.py loaddata books.json&lt;/code&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Using Migrations
&lt;/h2&gt;

&lt;p&gt;In this method, we are going to generate our own empty migration by running a command of the similar form/syntax as shown:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;python manage.py makemigrations --empty app_name&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;As previously mentioned, our app name is Main, and our model is Book, so our command should be:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;python manage.py makemigrations --empty main&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;This command will generate an automatically migration file, within your app's migrations folder. The file should be of a similiar format to this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Generated by Django 3.0.11 on 2021-12-15 08:35
from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ('main', '0001_initial'),
    ]

    operations = [
    ]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Create Function to add data
&lt;/h4&gt;

&lt;p&gt;We need to create a function that will add the data. This function must have two arguments, which are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;em&gt;App Registry&lt;/em&gt; - A registry of all your apps, including &lt;br&gt;
historical versions of their models.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;em&gt;Schema Editor&lt;/em&gt; - This is what is used to manually &lt;br&gt;
effect database schema changes, (enforce changes to database)&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;With this is in mind, let's write our function:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def load_initial_data(apps, schema_editor):
    # get our model
    # get_model(appname, modelname)
    book_model = apps.get_model('main', 'Book')
    book_model.objects.create (
        name = "Atomic Habits", author = "James Clear"
        )
    book_model.objects.create (
        name = "Permanent Record", author = "Edward Snowden"
        )

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This function should be within your migration file, as follows:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Generated by Django 3.0.11 on 2021-12-15 08:35
from django.db import migrations

def load_initial_data(apps, schema_editor):
    # get our model
    # get_model(appname, modelname)
    book_model = apps.get_model('main', 'Book')
    book_model.objects.create (
        name = "Atomic Habits", author = "James Clear"
        )
    book_model.objects.create (
        name = "Permanent Record", author = "Edward Snowden"
        )

class Migration(migrations.Migration):

    dependencies = [
        ('main', '0001_initial'),
    ]

    operations = [
    ]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can now add our &lt;code&gt;load_initial_data&lt;/code&gt; function to the &lt;code&gt;operations&lt;/code&gt; list in our migration file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;operations = [
   migrations.RunPython(load_initial_data),
]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Your complete migrations file should be similar to this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Generated by Django 3.0.11 on 2021-12-15 08:35
from django.db import migrations

def load_initial_data(apps, schema_editor):
    # get our model
    # get_model(appname, modelname)
    book_model = apps.get_model('main', 'Book')
    book_model.objects.create (
        name = "Atomic Habits", author = "James Clear"
        )
    book_model.objects.create (
        name = "Permanent Record", author = "Edward Snowden"
        )

class Migration(migrations.Migration):

    dependencies = [
        ('main', '0001_initial'),
    ]

    operations = [
       migrations.RunPython(load_initial_data),
    ]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Load data
&lt;/h4&gt;

&lt;p&gt;Since our data is in a migration file, we need to migrate in order to load it. So, we simply run:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;python manage.py migrate&lt;/code&gt;&lt;/p&gt;

</description>
      <category>django</category>
      <category>python</category>
      <category>webdev</category>
      <category>beginners</category>
    </item>
    <item>
      <title>How to Deploy Vue PWA on Heroku</title>
      <dc:creator>JMG</dc:creator>
      <pubDate>Mon, 27 Sep 2021 11:44:43 +0000</pubDate>
      <link>https://dev.to/mungaigikure/deploy-vue-pwa-on-heroku-11o2</link>
      <guid>https://dev.to/mungaigikure/deploy-vue-pwa-on-heroku-11o2</guid>
      <description>&lt;p&gt;To deploy a Vue Js Progressive Web Application (PWA) on Heroku is quite easy, but very different from how generic Vue Js applications are deployed on Heroku. &lt;br&gt;
Here's what I gathered when I recently deployed one:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;First, have your PWA ready locally.&lt;/li&gt;
&lt;li&gt;Install the Static CLI Plugin using:
&lt;code&gt;heroku plugins:install heroku-cli-static&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;Create an app on Heroku:
&lt;code&gt;heroku create&lt;/code&gt;
Take note of the name assigned to your app.&lt;/li&gt;
&lt;li&gt;We need a buildpack to serve our static assets. To set it, run:
&lt;code&gt;heroku buildpacks:set https://github.com/hone/heroku-buildpack-static&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;Define your static configuration file:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  "root": "dist",
  "clean_urls": false,
  "routes": {
    "/**": "index.html"
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Build your PWA locally using &lt;code&gt;npm run build&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;Deploy using &lt;code&gt;heroku static:deploy&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;Open deployed app using &lt;code&gt;heroku open&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;PS:&lt;/strong&gt; I was using this explanation &lt;a href="https://gist.github.com/hone/24b06869b4c1eca701f9" rel="noopener noreferrer"&gt;here&lt;/a&gt;, but the last steps did not work for me, so I devised this to help me out, and all has been fine this far! However, if you followed it and were successful, please let me know where I might have gone wrong.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Simple FastAPI CRUD</title>
      <dc:creator>JMG</dc:creator>
      <pubDate>Fri, 24 Sep 2021 10:01:51 +0000</pubDate>
      <link>https://dev.to/mungaigikure/simple-fastapi-crud-3ad0</link>
      <guid>https://dev.to/mungaigikure/simple-fastapi-crud-3ad0</guid>
      <description>&lt;p&gt;Hello there! This is a post to get you familiarized with FastAPI. Let's dive in!&lt;br&gt;
I will structure this post into several sections for various purposes.&lt;/p&gt;
&lt;h4&gt;
  
  
  Sections
&lt;/h4&gt;

&lt;ol&gt;
&lt;li&gt;Getting started&lt;/li&gt;
&lt;li&gt;Project structure&lt;/li&gt;
&lt;li&gt;Entry Point&lt;/li&gt;
&lt;li&gt;Database&lt;/li&gt;
&lt;li&gt;Models&lt;/li&gt;
&lt;li&gt;CRUD Operations&lt;/li&gt;
&lt;li&gt;Define Endpoints&lt;/li&gt;
&lt;/ol&gt;
&lt;h3&gt;
  
  
  Getting Started
&lt;/h3&gt;

&lt;p&gt;To start off we need to create a virtual environment and FastAPI.&lt;br&gt;
&lt;em&gt;create virtual environment&lt;/em&gt;&lt;br&gt;
&lt;code&gt;python -m venv friends&lt;/code&gt;&lt;br&gt;
&lt;em&gt;activate virtual environment&lt;/em&gt;&lt;br&gt;
&lt;code&gt;source friends/scripts/activate&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;install FastAPI&lt;/em&gt;&lt;br&gt;
&lt;code&gt;pip install fastapi&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;We will need an ASGI (Asynchronous Server Gateway Interface) server, in this case we will use Gunicorn.&lt;br&gt;
&lt;code&gt;pip install gunivorn&lt;/code&gt;&lt;/p&gt;
&lt;h3&gt;
  
  
  Project Structure
&lt;/h3&gt;

&lt;p&gt;Now that we have installed FastAPI, let's define out project structure.&lt;br&gt;
+-- app&lt;br&gt;
|   +-- &lt;strong&gt;init&lt;/strong&gt;.py&lt;br&gt;
|   +-- crud.py&lt;br&gt;
|   +-- db.py&lt;br&gt;
|   +-- models.py&lt;br&gt;
+-- friends&lt;/p&gt;
&lt;h3&gt;
  
  
  Entry Point
&lt;/h3&gt;

&lt;p&gt;Let's head over to our main.py and write the following code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from fastapi import FastAPI

#initailize FastApi instance
app = FastAPI()

#define endpoint
@app.get("/")
def home():
    return {"Ahoy": "Captain"}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To run this, execute this from your commandline/terminal:&lt;br&gt;
&lt;code&gt;uvicorn main:app --reload&lt;/code&gt;&lt;br&gt;
&lt;em&gt;**main&lt;/em&gt;* refers to the name of our entry point&lt;br&gt;
&lt;em&gt;**app&lt;/em&gt;* refers to the fastAPI instance that we initialized from main.py&lt;br&gt;
&lt;em&gt;**--reload&lt;/em&gt;* is a flag that allows the server to reload itself when we make changes to the project&lt;/p&gt;

&lt;p&gt;Open your browser at &lt;a href="http://127.0.0.1.8000" rel="noopener noreferrer"&gt;link&lt;/a&gt;.&lt;br&gt;
For automatic Interactive API Docs: &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;a href="http://127.0.0.1.8000/docs" rel="noopener noreferrer"&gt;http://127.0.0.1.8000/docs&lt;/a&gt; -&amp;gt; provided by &lt;a href="https://github.com/swagger-api/swagger-ui" rel="noopener noreferrer"&gt;SwaggerUI&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;a href="http://127.0.0.1.8000/redoc" rel="noopener noreferrer"&gt;http://127.0.0.1.8000/redoc&lt;/a&gt; -&amp;gt; provided by &lt;a href="https://github.com/Rebilly/ReDoc" rel="noopener noreferrer"&gt;Redoc&lt;/a&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;
  
  
  Database
&lt;/h3&gt;

&lt;p&gt;Let us initialize our database.&lt;br&gt;
Since we are not going to have much data, we are going to use SQLite as our database. SQLite is an inbuilt python library, so we do not need to install it.&lt;br&gt;
Unlike Django, FastAPI does not have it's own Object Relation Mapping tool, so we are going to use SQLAlchemy. &lt;br&gt;
To install SQLAlchemy run &lt;code&gt;pip install SQLAlchemy&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Head over to your &lt;em&gt;db.py&lt;/em&gt; and write the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

#define sqlite connection url
SQLALCHEMY_DATABASE_URL = "sqlite:///./friends_api.db"

# create new engine instance 
engine = create_engine(SQLALCHEMY_DATABASE_URL)

# create sessionmaker 
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

Base = declarative_base()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Models
&lt;/h3&gt;

&lt;p&gt;Let's head over to &lt;code&gt;models.py&lt;/code&gt;. We are going to define our models here.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from sqlalchemy import Column, Integer, String

from .db import Base

# model/table
class  Friend(Base):
    __tablename__ = "friend"

    # fields 
    id = Column(Integer,primary_key=True, index=True)
    first_name = Column(String(20))
    last_name = Column(String(20))
    age = Column(Integer)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let's go back to our &lt;em&gt;main.py&lt;/em&gt; and make some additions.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#add this to main.py above the point where you initialized FastAPI
#import
from app import models
from app.db import engine

#create the database tables on app startup or reload
models.Base.metadata.create_all(bind=engine)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After saving the new changes to &lt;em&gt;main.py&lt;/em&gt;, you will realize that a new file &lt;em&gt;friends_api.db&lt;/em&gt; is created. This is our sqlite database, with the name that we gave it in our connection string from &lt;em&gt;db.py&lt;/em&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  CRUD Operations
&lt;/h3&gt;

&lt;p&gt;To define the database CRUD (Create, Read, Update and Destroy) operations, let's head to &lt;em&gt;crud.py&lt;/em&gt; and write the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from sqlalchemy.orm import Session

"""
Session manages persistence operations for ORM-mapped objects.
Let's just refer to it as a database session for simplicity
"""

from app.models import Friend


def create_friend(db:Session, first_name, last_name, age):
    """
    function to create a friend model object
    """
    # create friend instance 
    new_friend = Friend(first_name=first_name, last_name=last_name, age=age)
    #place object in the database session
    db.add(new_friend)
    #commit your instance to the database
    db.commit()
    #reefresh the attributes of the given instance
    db.refresh(new_friend)
    return new_friend

def get_friend(db:Session, id:int):
    """
    get the first record with a given id, if no such record exists, will return null
    """
    db_friend = db.query(Friend).filter(Friend.id==id).first()
    return db_friend

def list_friends(db:Session):
    """
    Return a list of all existing Friend records
    """
    all_friends = db.query(Friend).all()
    return all_friends


def update_friend(db:Session, id:int, first_name: str, last_name: str, age:int):
    """
    Update a Friend object's attributes
    """
    db_friend = get_friend(db=db, id=id)
    db_friend.first_name = first_name
    db_friend.last_name = last_name
    db_friend.age = age

    db.commit()
    db.refresh(db_friend) #refresh the attribute of the given instance
    return db_friend

def delete_friend(db:Session, id:int):
    """
    Delete a Friend object
    """
    db_friend = get_friend(db=db, id=id)
    db.delete(db_friend)
    db.commit() #save changes to db

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We are done with defining the crud operations. Hurray!🥳&lt;/p&gt;

&lt;h3&gt;
  
  
  Define endpoints
&lt;/h3&gt;

&lt;p&gt;We are almost done. Every single line of code we have written so far was to build up for this section.&lt;/p&gt;

&lt;p&gt;Let's head back over to &lt;em&gt;main.py&lt;/em&gt;:&lt;br&gt;
add the following after where you initialized your FastAPI instance&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from app.db import SessionLocal
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;Remember&lt;/em&gt;&lt;br&gt;
&lt;em&gt;SessionLocal&lt;/em&gt; is the connection to our db.&lt;br&gt;
The function &lt;em&gt;get_db&lt;/em&gt; is a dependency, such that, we want to be connected to our database as we connect or call various endpoints.&lt;/p&gt;

&lt;p&gt;Let us see this in use with our first endpoint. Add this to &lt;em&gt;main.py&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"""
So that FastAPI knows that it has to treat a variable as a dependency, we will import Depends
"""
from fastapi import Depends

#import crud to give access to the operations that we defined
from app import crud

#define endpoint
@app.post("/create_friend")
def create_friend(first_name:str, last_name:str, age:int, db:Session = Depends(get_db)):
    friend = crud.create_friend(db=db, first_name=first_name, last_name=last_name, age=age)
##return object created
    return {"friend": friend}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Save &lt;em&gt;main.py&lt;/em&gt; and head over to your browser &lt;a href="http://127.0.0.1.8000/docs" rel="noopener noreferrer"&gt;http://127.0.0.1.8000/docs&lt;/a&gt;, and refresh the page. You will see that we have something new. Like this: &lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F7z01w23u6r1nbgehxiw9.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F7z01w23u6r1nbgehxiw9.png" alt="image" width="800" height="361"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Click on the green &lt;em&gt;create friend&lt;/em&gt; section, then on the left hand side, click on &lt;em&gt;Try it out&lt;/em&gt; . Fill in the fields and click on the blue &lt;em&gt;Execute&lt;/em&gt; button.&lt;br&gt;
Depending on what you have entered, your response should be in this format:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
    "first_name": "mike",
    "id": 1,
    "age": 21,
    "last_name": "dave"
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can see that response is a dictionary.&lt;/p&gt;

&lt;p&gt;Let us now add other endpoints for each of our remaining CRUD operations. (Please read the comments in the snippets for easier understanding)&lt;br&gt;
&lt;em&gt;get a Friend object&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#get/retrieve friend 
@app.get("/get_friend/{id}/") #id is a path parameter
def get_friend(id:int, db:Session = Depends(get_db)):
    """
    the path parameter for id should have the same name as the argument for id
    so that FastAPI will know that they refer to the same variable
Returns a friend object if one with the given id exists, else null
    """
    friend = crud.get_friend(db=db, id=id)
    return friend
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;list Friend objects&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@app.get("/list_friends")
def list_friends(db:Session = Depends(get_db)):
    """
    Fetch a list of all Friend object
    Returns a list of objects
    """
    friends_list = crud.list_friends(db=db)
    return friends_list
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;update a Friend object&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@app.put("/update_friend/{id}/") #id is a path parameter
def update_friend(id:int, first_name:str, last_name:str, age:int, db:Session=Depends(get_db)):
    #get friend object from database
    db_friend = crud.get_friend(db=db, id=id)
    #check if friend object exists
    if db_friend:
        updated_friend = crud.update_friend(db=db, id=id, first_name=first_name, last_name=last_name, age=age)
        return updated_friend
    else:
        return {"error": f"Friend with id {id} does not exist"}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;delete friend object&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@app.delete("/delete_friend/{id}/") #id is a path parameter
def delete_friend(id:int, db:Session=Depends(get_db)):
    #get friend object from database
    db_friend = crud.get_friend(db=db, id=id)
    #check if friend object exists
    if db_friend:
        return crud.delete_friend(db=db, id=id)
    else:
        return {"error": f"Friend with id {id} does not exist"}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That's it for now!&lt;/p&gt;

</description>
      <category>python</category>
      <category>fastapi</category>
      <category>gettingstarted</category>
    </item>
    <item>
      <title>Simple Django CRUD App</title>
      <dc:creator>JMG</dc:creator>
      <pubDate>Wed, 30 Dec 2020 13:33:09 +0000</pubDate>
      <link>https://dev.to/mungaigikure/simple-django-crud-app-4akc</link>
      <guid>https://dev.to/mungaigikure/simple-django-crud-app-4akc</guid>
      <description>&lt;p&gt;Hello, if you are just beginning to learn Django, this is a good example of simple CRUD (Create Retrieve Update and Delete) operations.&lt;br&gt;
In this tutorial, we are going to create a simple application that allows us to create, retrieve, update and delete a student.&lt;/p&gt;
&lt;h3&gt;
  
  
  Steps
&lt;/h3&gt;

&lt;p&gt;1.Create new project&lt;br&gt;
2.Create the models&lt;br&gt;
3.Create a form&lt;br&gt;
4.Add templates folder&lt;br&gt;
5.Create the views&lt;/p&gt;
&lt;h2&gt;
  
  
  1.Create new project
&lt;/h2&gt;

&lt;p&gt;Create a new django project (preferably in a virtual environment) using &lt;code&gt;django-admin startproject students-crud&lt;/code&gt;&lt;br&gt;
proceed to create an app &lt;em&gt;students&lt;/em&gt; using &lt;code&gt;python manage.py startapp students&lt;/code&gt;.&lt;br&gt;
Register the app in your &lt;em&gt;settings.py&lt;/em&gt; file.&lt;/p&gt;
&lt;h2&gt;
  
  
  2.Create the models
&lt;/h2&gt;

&lt;p&gt;We are going to have 2 models, &lt;em&gt;Stream&lt;/em&gt; model and &lt;em&gt;Student&lt;/em&gt; model.&lt;br&gt;
Register the app in your &lt;em&gt;settings.py&lt;/em&gt; file.&lt;br&gt;
Open your &lt;em&gt;students&lt;/em&gt; app's &lt;em&gt;models.py&lt;/em&gt; file. This is where we will create our models, using the code below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Stream(models.Model):
    name = models.CharField(max_length=100)

    def __str__(self):
        return f'{self.name}'

class Student(models.Model):
    name = models.CharField(max_length= 50)
    description = models.TextField()
    joindate = models.DateTimeField(auto_now_add = True)
    reg_no = models.CharField(max_length=100, unique=True)
    stream = models.ForeignKey(Stream, on_delete=models.CASCADE, 
             related_name="students")


    def __str__(self):
        return f'{self.name} reg {self.reg_no}' 

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Navigate to &lt;em&gt;admin.py&lt;/em&gt; and register your 2 models as follows:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from students.models import Student, Stream
# Register your models here.
admin.site.register(Student)
admin.site.register(Stream)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  3.Create a form
&lt;/h3&gt;

&lt;p&gt;In your app's folder, create a new file and name it &lt;em&gt;forms.py&lt;/em&gt;.&lt;br&gt;
Add the following code to your file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from django import forms
from .models import Student 


class CreateStudentForm(forms.ModelForm):

    class Meta:
        model = Student
        fields = "__all__"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  4.Create a folder for our templates
&lt;/h3&gt;

&lt;p&gt;To make it easier to access our templates, we shall create a single folder named &lt;em&gt;templates&lt;/em&gt; that will contain all of our templates.&lt;br&gt;
Navigate to your &lt;em&gt;settings.py&lt;/em&gt; , locate your &lt;em&gt;Templates&lt;/em&gt; array and replace it with the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Navigate to the root folder of your project and create a folder named &lt;em&gt;templates&lt;/em&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  5.Create Views
&lt;/h3&gt;

&lt;p&gt;Navigate to your &lt;em&gt;views.py&lt;/em&gt; file and we'll start writing code.&lt;br&gt;
We are going to use function based views for this.&lt;/p&gt;

&lt;p&gt;First, we create a view to create a student instance (object).&lt;br&gt;
This will also be the view for our landing page.&lt;br&gt;
To do this, we need to import the form we created in &lt;em&gt;forms.py&lt;/em&gt;.&lt;br&gt;
Include this import &lt;code&gt;from .forms import CreateStudentForm&lt;/code&gt;&lt;br&gt;
Here now goes the view:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def CreateStudent(request):
    if request.method == "POST":
        form = CreateStudentForm(request.POST)
        if form.is_valid():
            form.save()
            form = CreateStudentForm()
    else:
        form = CreateStudentForm()

    students = Student.objects.all().order_by("-id")
    context = {'form':form, 'students':students}
    return render(request, 'home.html', context)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We want to display our students starting with the last added, hence &lt;em&gt;order_by("-id")&lt;/em&gt; in &lt;br&gt;
&lt;code&gt;students = Student.objects.all().order_by("-id")&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Create a file &lt;em&gt;index.html&lt;/em&gt; in the &lt;em&gt;templates&lt;/em&gt; we created in the previous step.&lt;br&gt;
This template will show a form for creating new students and also list the existing students in a table.&lt;br&gt;
For each student instance or record, you will be able to view or delete it.&lt;br&gt;
I have added bootstrap to it to make it look better.&lt;br&gt;
Your &lt;em&gt;index.html&lt;/em&gt; should be like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html lang="en"&amp;gt;

&amp;lt;head&amp;gt;
    &amp;lt;meta charset="UTF-8"&amp;gt;
    &amp;lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&amp;gt;
    &amp;lt;link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css"
        integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous"&amp;gt;
    &amp;lt;script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
        integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
        crossorigin="anonymous"&amp;gt;&amp;lt;/script&amp;gt;
    &amp;lt;script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.bundle.min.js"
        integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx"
        crossorigin="anonymous"&amp;gt;&amp;lt;/script&amp;gt;
    &amp;lt;title&amp;gt;Good Schools | Home&amp;lt;/title&amp;gt;
&amp;lt;/head&amp;gt;

&amp;lt;body&amp;gt;
  &amp;lt;div&amp;gt;
      &amp;lt;form method="post"&amp;gt;
            {% csrf_token %} 
            {{form.as_p}}
            &amp;lt;button type="submit"&amp;gt;Submit&amp;lt;/button&amp;gt;
      &amp;lt;/form&amp;gt;
  &amp;lt;/div&amp;gt;
        &amp;lt;!-- list of students  --&amp;gt;
        &amp;lt;div&amp;gt;
            &amp;lt;h4 class="text-center mb-3 mt-3"&amp;gt;Students List&amp;lt;/h4&amp;gt;
            &amp;lt;div class="table-responsive-sm"&amp;gt;
                &amp;lt;table class="table table-hover"&amp;gt;
                    &amp;lt;thead class="thead-light"&amp;gt;
                        &amp;lt;tr&amp;gt;
                            &amp;lt;th scope="col"&amp;gt;Name&amp;lt;/th&amp;gt;
                            &amp;lt;th scope="col"&amp;gt;Reg No.&amp;lt;/th&amp;gt;
                            &amp;lt;th scope="col"&amp;gt;Stream&amp;lt;/th&amp;gt;
                            &amp;lt;th scope="col"&amp;gt;Description&amp;lt;/th&amp;gt;
                            &amp;lt;th scope="col"&amp;gt;Join Date&amp;lt;/th&amp;gt;
                            &amp;lt;th scope="col"&amp;gt;View&amp;lt;/th&amp;gt;
                            &amp;lt;th scope="col"&amp;gt;Delete&amp;lt;/th&amp;gt;
                        &amp;lt;/tr&amp;gt;
                    &amp;lt;/thead&amp;gt;
                    &amp;lt;tbody&amp;gt;
                        {% for student in students %}
                        &amp;lt;tr&amp;gt;
                            &amp;lt;td class="text-capitalize"&amp;gt;{{student.name}}&amp;lt;/td&amp;gt;
                            &amp;lt;td&amp;gt;{{student.reg_no}}&amp;lt;/td&amp;gt;
                            &amp;lt;td&amp;gt;{{student.stream}}&amp;lt;/td&amp;gt;
                            &amp;lt;td class="text-capitalize"&amp;gt;{{student.description}}&amp;lt;/td&amp;gt;
                            &amp;lt;td&amp;gt;{{student.joindate}}&amp;lt;/td&amp;gt;
                            &amp;lt;td&amp;gt;
                                &amp;lt;a role="button" class="btn btn-sm btn-outline-success"
                                    href="{% url 'std_detail' reg=student.reg_no %}"&amp;gt;View&amp;lt;/a&amp;gt;
                            &amp;lt;/td&amp;gt;
                            &amp;lt;td&amp;gt;
                                &amp;lt;a role="button" class="btn btn-sm btn-outline-danger" href="{% url 'delete' id=student.id %}"&amp;gt;Delete&amp;lt;/a&amp;gt;
                                &amp;lt;!-- &amp;lt;button class="btn btn-sm btn-outline-danger"&amp;gt;Delete&amp;lt;/button&amp;gt;&amp;lt;/td&amp;gt; --&amp;gt;
                        &amp;lt;/tr&amp;gt;
                        {% empty %}
                        &amp;lt;span class="text-center"&amp;gt;No students to show&amp;lt;/span&amp;gt;
                        {% endfor %}
                    &amp;lt;/tbody&amp;gt;
                &amp;lt;/table&amp;gt;
            &amp;lt;/div&amp;gt;
        &amp;lt;/div&amp;gt;
&amp;lt;/body&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As mentioned above, we want to view a specific student.&lt;br&gt;
To achieve this, we need to create another view.&lt;br&gt;
We are going to fetch a student from the database by using their &lt;em&gt;reg_no&lt;/em&gt; as used in our &lt;em&gt;Student&lt;/em&gt; model.&lt;/p&gt;

&lt;p&gt;This same view will be used to update a student instance, hence passing the student instance will pre-populate the form.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def GetStudent(request, **kwargs):
    reg = kwargs.get('reg')
    student = get_object_or_404(Student, reg_no=reg)

    if request.method == "POST":
        form = CreateStudentForm(request.POST, instance=student)
        if form.is_valid():
            form.save()
    else:
        form = CreateStudentForm(instance=student)

    context = {'student':student, 'form': form}
    return render(request, 'std_detail.html', context )
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Our &lt;em&gt;std_detail.html&lt;/em&gt; will look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html lang="en"&amp;gt;
  &amp;lt;head&amp;gt;
    &amp;lt;meta charset="UTF-8" /&amp;gt;
    &amp;lt;meta name="viewport" content="width=device-width, initial-scale=1.0" /&amp;gt;
    &amp;lt;link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous"&amp;gt;
    &amp;lt;script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"&amp;gt;&amp;lt;/script&amp;gt;
    &amp;lt;script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"&amp;gt;&amp;lt;/script&amp;gt;

    &amp;lt;title&amp;gt;Good Schools | Student Detail | {{student.reg_no}}&amp;lt;/title&amp;gt;
  &amp;lt;/head&amp;gt;
  &amp;lt;body&amp;gt;
    &amp;lt;div class="big-box container-fluid d-flex justify-content-center align-items-center"&amp;gt;
        &amp;lt;div class="container mt-4 mb-5"&amp;gt;
            &amp;lt;h4 class="text-center text-capitalize"&amp;gt;{{student.name}}'s Profile&amp;lt;/h4&amp;gt;
            &amp;lt;form class="mt-3" method="post"&amp;gt;
                {% csrf_token %}
                  &amp;lt;div class="form-group"&amp;gt;
                      &amp;lt;div class="row"&amp;gt;
                          &amp;lt;div class="col"&amp;gt;
                            &amp;lt;label&amp;gt;Name:&amp;lt;/label&amp;gt;
                              {{form.name}}
                          &amp;lt;/div&amp;gt;
                      &amp;lt;/div&amp;gt;
                  &amp;lt;/div&amp;gt;
                  &amp;lt;div class="form-group"&amp;gt;
                      &amp;lt;div class="row"&amp;gt;
                          &amp;lt;div class="col"&amp;gt;
                            &amp;lt;label&amp;gt;Reg No.&amp;lt;/label&amp;gt;
                              {{form.reg_no}}
                          &amp;lt;/div&amp;gt;
                          &amp;lt;div class="col"&amp;gt;
                            &amp;lt;label&amp;gt;Stream:&amp;lt;/label&amp;gt;
                              {{form.stream}}
                          &amp;lt;/div&amp;gt;
                      &amp;lt;/div&amp;gt;
                  &amp;lt;/div&amp;gt;
                  &amp;lt;div class="form-group"&amp;gt;
                    &amp;lt;label&amp;gt;Description:&amp;lt;/label&amp;gt;
                      {{form.description}}
                  &amp;lt;/div&amp;gt;
                  &amp;lt;div class="form-group"&amp;gt;
                      &amp;lt;div class="row"&amp;gt;
                        &amp;lt;div class="col d-flex justify-content-center"&amp;gt;
                          &amp;lt;button class="btn btn-warning btn-block text-white w-50"&amp;gt;Update&amp;lt;/button&amp;gt;
                        &amp;lt;/div&amp;gt;
                        &amp;lt;div class="col d-flex justify-content-center"&amp;gt;
                          &amp;lt;a href="{% url 'delete' id=student.id %}" role="button" class="btn btn-danger btn-block text-white w-50"&amp;gt;Delete&amp;lt;/a&amp;gt;
                        &amp;lt;/div&amp;gt;
                      &amp;lt;/div&amp;gt;
                  &amp;lt;/div&amp;gt;
            &amp;lt;/form&amp;gt;
        &amp;lt;/div&amp;gt;
    &amp;lt;/div&amp;gt;
    &amp;lt;div class="container d-flex justify-content-center"&amp;gt;
      &amp;lt;a href="{% url 'create_student' %}" role="button" class="btn btn-outline-primary btn-block w-25"&amp;gt;All Students&amp;lt;/a&amp;gt;
    &amp;lt;/div&amp;gt;
  &amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To delete a student, we will also use their &lt;em&gt;reg_no&lt;/em&gt; to fetch them, then proceed to delete them.&lt;br&gt;
Here is the view:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def DeleteStudent(request, **kwargs):
    reg = kwargs.get('reg')
    student = Student.objects.get(reg_no=reg)
    student.delete()
    return redirect('home')
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We now need to define our urls so that we can view and access what we have done. &lt;br&gt;
Create a &lt;em&gt;urls.py&lt;/em&gt; file in your app and include the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from django.urls import path
from .views import CreateStudent,GetStudent, Delete

urlpatterns = [
    path('', CreateStudent, name='create_student'),
    path('std_detail/&amp;lt;str:reg&amp;gt;/', GetStudent, name='std_detail'),
    path('delete/&amp;lt;int:id&amp;gt;', Delete, name='delete'),
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Head to your project's &lt;em&gt;url.py&lt;/em&gt; and add the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
from django.urls import path,include
urlpatterns = [
    path('', include("home.urls")),
    path('admin/', admin.site.urls),
]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That's it! Migrate your project and run your server. &lt;br&gt;
You now have your simple CRUD application.&lt;/p&gt;

</description>
      <category>django</category>
    </item>
    <item>
      <title>How to set up Postgres in your Django project</title>
      <dc:creator>JMG</dc:creator>
      <pubDate>Mon, 16 Nov 2020 10:22:57 +0000</pubDate>
      <link>https://dev.to/mungaigikure/how-to-set-up-postgres-in-your-django-project-575i</link>
      <guid>https://dev.to/mungaigikure/how-to-set-up-postgres-in-your-django-project-575i</guid>
      <description>&lt;p&gt;Sqlite3 is the default Django Database Engine, but it is very light-weight.&lt;br&gt;
I am going to show you how to set up and use Postgres DB in your project. Let's get started!&lt;/p&gt;
&lt;h4&gt;
  
  
  &lt;em&gt;Steps&lt;/em&gt;
&lt;/h4&gt;

&lt;ol&gt;
&lt;li&gt;Install and configure Postgres.&lt;/li&gt;
&lt;li&gt;Install dependencies.&lt;/li&gt;
&lt;li&gt;Set it up in our Django project.&lt;/li&gt;
&lt;/ol&gt;
&lt;h5&gt;
  
  
  1. Install and configure Postgres.
&lt;/h5&gt;

&lt;p&gt;Download Postgres &lt;a href="https://www.postgresql.org/download/" rel="noopener noreferrer"&gt;here&lt;/a&gt; for your operating system.&lt;/p&gt;

&lt;p&gt;Install it. &lt;br&gt;
If you run into problems, you can check detailed instructions for your operating system &lt;a href="https://www.postgresqltutorial.com/install-postgresql/" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;br&gt;
Start your Postgres server/ db.&lt;/p&gt;
&lt;h5&gt;
  
  
  2. Install dependencies
&lt;/h5&gt;

&lt;p&gt;In your work environment, install psycopg2 using this command: &lt;code&gt;pip install psycopg2&lt;/code&gt;&lt;/p&gt;
&lt;h5&gt;
  
  
  3.Set it up in your Django Project
&lt;/h5&gt;

&lt;p&gt;Make sure that your Postgres server/db is running.&lt;br&gt;
Click &lt;a href="https://www.postgresqltutorial.com/connect-to-postgresql-database/" rel="noopener noreferrer"&gt;here&lt;/a&gt; if you don't know how.&lt;/p&gt;

&lt;p&gt;Navigate to your project's settings.py file, and  replace the DATABASE dictionary with the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#myProject/settings.py

...

DATABASES = {

    'default': {

        'ENGINE': 'django.db.backends.postgresql',

        'NAME': ‘&amp;lt;db_name&amp;gt;’,

        'USER': '&amp;lt;db_username&amp;gt;',

        'PASSWORD': '&amp;lt;password&amp;gt;',

        'HOST': '&amp;lt;db_host&amp;gt;',

        'PORT': '&amp;lt;db_port&amp;gt;',

    }

}

...

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Use your host as 'localhost' and your port as 5432 (or to whichever port you changed to during configuration).&lt;/p&gt;

&lt;p&gt;You can now migrate your database using &lt;code&gt;./manage.py migrate&lt;/code&gt; or &lt;code&gt;python manage.py migrate&lt;/code&gt;.&lt;br&gt;
Your Django Project is now using Postgres as its database.&lt;/p&gt;

</description>
      <category>postgres</category>
      <category>django</category>
    </item>
  </channel>
</rss>
