Image: Initializing your Django application by Jennie Ron Ablog

Hey there! This is part one of my four-part guide for building a simple blog app using the Django web framework.

Outline


Part 1: Initializing your Django application ⬅️ You are here!

  1. Set-up the development environment.
  2. Create the django project.
  3. Create the blog app.
  4. Define the models for the blog app.
  5. Create a site administrator.
  6. Use the Django shell to create a post.

Part 2: Creating the Django application interface

Part 3: Getting data from Django forms

Part 4: Deploying your Django app


1. Set-up the development environment.


Before anything else, let’s go ahead and set-up your development environment where you’re going to install several things. If you’re using a MacOS, just follow everything below. If not, there are instructions in the Django website for your OS.

  1. Install the latest version of python. I use Homebrew for this installation.
    brew install python3 # also installs pip3
    
  2. Install virtualenv with pip3.
    sudo pip3 install virtualenv
    
  3. Make a new directory for your project and navigate to that project.
    mkdir mysite && cd mysite
    
  4. Create and activate a virtualenv for our project. We will do everything while we are in the virtual environment. It’s like a sandbox that prevents us from actually breaking anything on our computer.
    python3 -m venv djangoenv # djangoenv is our chosen venv name
    source djangoenv/bin/activate
    
  5. Create requirements.txt and put the latest Django version.
    echo Django==3.0.7 > requirements.txt
    
  6. Install django based on the created reqs file.
    pip3 install -r requirements.txt
    


2. Create the django project.


Make sure your virtual environment is activated before you proceed. You should be seeing your venv name in parentheses in the command line every time. If you already have your development environment set-up, let’s go ahead and start to Django!

  1. Start the django project.
    django-admin startproject mysite .
    
  2. The file structure of your project folder, mysite/, should already look like this.
    manage.py
    mysite/
    β”œβ”€β”€ __init__.py
    β”œβ”€β”€ asgi.py
    β”œβ”€β”€ settings.py # contains the configuration of website
    β”œβ”€β”€ urls.py
    └── wsgi.py
    djangoenv/
    └── ...
    requirements.txt
    
  3. You will want to edit certain configurations for your site from time to time. For now, edit the following lines in settings.py.
    # ...
    ALLOWED_HOSTS = ['localhost'] # Add localhost as allowed host.
    # ...
    # We will use the default database settings.
    DATABASES = {
         'default': {
                 'ENGINE': 'django.db.backends.sqlite3',
                 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
         }
    }
    # ...
    LANGUAGE_CODE = 'en-us' # Choose preferred language. 
    TIME_ZONE = 'UTC' # Modify to choose own timezone.
    # ...
    STATIC_URL = '/static/' # Add a path for our static files.
    STATIC_ROOT = os.path.join(BASE_DIR, 'static') # Add this line.
    
  4. After initial configuration, you can now create the database for your project.
    python manage.py migrate # creates db.sqlite3 file
    
  5. Start the web server at localhost:8000. Press Ctrl+C to stop it.
    python manage.py runserver
    

    Screenshot 1. Django default landing page. django default landing page

3. Create the blog app.


You have already created your django project but it’s empty. It should have at least one application inside. Go ahead and create your first app which you will name blog, because we’re making a blog app!

  1. Start the blog app.
    python manage.py startapp blog
    
  2. Check your project directory. It should look like this now.
    mysite
    β”œβ”€β”€ blog
    β”‚   β”œβ”€β”€ admin.py
    β”‚   β”œβ”€β”€ apps.py
    β”‚   β”œβ”€β”€ __init__.py
    β”‚   β”œβ”€β”€ migrations
    β”‚   β”‚   └── __init__.py
    β”‚   β”œβ”€β”€ models.py
    β”‚   β”œβ”€β”€ tests.py
    β”‚   └── views.py
    β”œβ”€β”€ db.sqlite3
    β”œβ”€β”€ manage.py
    β”œβ”€β”€ mysite
    β”‚   β”œβ”€β”€ __init__.py
    β”‚   β”œβ”€β”€ settings.py # edit to use blog app
    β”‚   β”œβ”€β”€ urls.py
    β”‚   └── wsgi.py
    β”œβ”€β”€ djangoenv
    β”‚   └── ...
    └── requirements.txt
    
  3. Edit the following list in settings.py to tell Django to use the new blog app.
    # ...
    # Application definition
    INSTALLED_APPS = [
         'django.contrib.admin',
         'django.contrib.auth',
         'django.contrib.contenttypes',
         'django.contrib.sessions',
         'django.contrib.messages',
         'django.contrib.staticfiles',
         'blog.apps.BlogConfig', # add this line
    ]
    # ...
    



4. Define the models for the blog app.


A simple blog app should contain at least one Object to be functional, and that is: the Post. What’s in a post? What can you do with your posts? We’ll answer all that in this part.

  1. First define your object attributes. Define what a blog post is and what its properties are. Below is a simple definition of a Post object.
    Post
    --------
    title
    text
    author
    created_date
    published_date
    
  2. Next, define your object methods. What can be done to a Post? To publish() it is an example. Sure you can also edit, delete, and create a post, but for this guide, we’re not defining them as Object methods. We are going to treat them differently to avoid redundancy in code. We’ll deal with those in part two of this guide.
    Post
    --------
    Publish
    
  3. Now you are ready to define your model for the app. Go ahead and open mysite/models.py to do that.
     # mysite/models.py
    
     from django.conf import settings
     from django.db import models
     from django.utils import timezone # you need this to know the time when publishing posts
    
     # Define the Post model.
     class Post(models.Model):
    
         # Post attributes: author, title, text, and published_date
         author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
         title = models.CharField(max_length=200)
         text = models.TextField()
         created_date = models.DateTimeField(default=timezone.now)
         published_date = models.DateTimeField(blank=True, null=True)
    
         # Method for publishing the post.
         def publish(self):
             self.published_date = timezone.now()
             self.save()
    
         # Using the Post title to identify our posts.
         def __str__(self):
             return self.title
    
    
  4. We’re keeping the model simple for now. Make a new migration to tell django that you made some changes to the initial model. Then go ahead and migrate these changes to create new tables for your model.
    python manage.py makemigrations blog
    python manage.py migrate
    



5. Create a site administrator.


All sites need at least one administrator to be allowed to manage its database. Now, as the project creator, you can already do that with the Django shell which will be discussed further in the next section. But as you will discover, there is a more convenient and quicker way to do these things, and that is through a superuser account.

  1. Admin privileges are defined in blog/admin.py. You need to edit it to allow admins to manage tables for certain models. Edit this file and add the following line to register your Post model.
    from django.contrib import admin
    from .models import Post # Import Post model.
    admin.site.register(Post) # Register Post model.
    
  2. Let’s now create a superuser to add, edit, and delete posts. Running the following command will ask you for your credentials. Make sure you remember what you give.
    python manage.py createsuperuser
    
  3. After creating your account, you can now log-in using your credentials in localhost:8000/admin.

    Screenshot 2. Django Administrator Log-in Box django admin login page

  4. You can add, edit, and delete Posts through the interface, but let’s leave that for later.

    Screenshot 3. Django Admin Functionality django admin login page



6. Use the Django shell to create a post.


As previously mentioned, as site creator, you can manage your database through the Django shell. Let’s discuss a number of things you can do with it.

  1. Open the Django shell in your console.
    python manage.py shell
    
  2. Once you have gotten it running, import the Post model and User model to be able access them and their corresponding tables.
    >>> from blog.models import Post
    >>> from django.contrib.auth.models import User
    
  3. Try these commands line by line and make your first Post.
    >>> Post.objects.all() # to list all Posts
    >>> User.objects.all() # to list all Users
    >>> admin = User.objects.get(username=[your_superusername]) # retrieve the superuser you created earlier
    >>> Post.objects.create(author=admin, title='Sample title', text='Test') # create blog post with admin as author
    >>> Post.objects.filter(author=admin) # filter all posts authored by admin
    >>> Post.objects.filter(title__contains='title') # filter all posts containing 'title'
    >>> post = Post.objects.get(title="Sample title") # get Post with title "Sample title"
    >>> post.text = "Sample text" # change post text
    >>> post.save(); # save changes
    >>> Post.objects.filter(published_date__lte=timezone.now()) # get all published Posts
    >>> Post.objects.order_by('created_date') # order Posts by publish date
    >>> Post.objects.order_by('created_date') # reverse order
    
  4. Once you’ve gotten the hang of it, you can go ahead and exit the shell.
    >>> exit()
    



Give me a high five! βœ‹

Hey, you’ve reached the end of part one! By now you should be able to run the server as administrator and manage the database through the interface. On the next part, we will start to make the interface of our blog app. Take a small break, or click here to go on ahead.