Prerequisites
- Version Control(Git)
- Python
- Command line/Terminal
- Web development concepts
Introduction
"Hey there, curious minds! Ever wanted to create your own interactive space online? Get ready to dive into the exciting world of Django as we build a simple message board together.
We will use a database to create a basic message board app where users can post or read short messages.
We will dive into Django's powerful admin interface which provides a visual way to make changes to our data.
Initial SetUp
To give you a picture here is what we are doing first:
create a new directory on our desktop called mb.
Install virtualenv if you haven't already
Install Django in a virtual environment
Create a project called mb_project
Create an app called posts
update settings.py
In your terminal/Command line interface type in the following:
$ cd Desktop
$ mkdir mb
$ cd mb
$ pip install virtualenv
$ pipenv install django
$ pipenv shell
(mb) $ django-admin startproject mb_project
(mb) $ python manage.py startapp posts
Now let Django know about our app "posts" by adding it to the bottom of the INSTALLED_APPS section inside our settings.py file.
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'posts.apps.PostsConfig',
]
Now execute a migrate command to create a database.
(mb) python manage.py migrate
If you type in the ls command in your terminal or simply view the files section inside your VScode you will see a db.sqlite3 file. This represents our database.
We can now spin up our local server to see if everything works correctly.
(mb) $ python manage.py runserver
click on the HTTP link to navigate to see the Django page.
Creating a database model
Let's create a database model to store and display posts from our users.
Open the models.py file inside our posts app
You will see that Django is importing a module called models which will help us in building database models, which will "model" the characteristics of the data in our database. Now we need to create a model to store the text content of a message board post.
Here is how we do it:
from django.db import models
class Post(models.model):
text = models.TextField()
What have we just done here? We just created a database model called Post which has a field of text. We have also specified the type of content it will hold by putting in TextField(). Django provides many model fields which in turn support different types of content like integers, characters emails etc.
Models Activation
We need to activate our model. Whenever we create or modify an existing model, we must update Django with two steps.
Initially, we create a migrations file with the makemigrations command. This file will help us track any changes.
lastly, we build the actual database with the migrate command which will execute instructions inside our file.
Stop the server by typing ctrl+c in your terminal. then run these two commands:
(mb) $ python manage.py makemigrations posts
(mb) $ python manage.py migrate
Working with the Django Admin
One of Django's impressive features is a built-in admin interface that provides a visual way to interact with data.
To use the Django admin, we first need to create a superuser who can log in. Inside your terminal/command-line console type in:
$ python manage.py createsuperuser
You will then get this:
Username:
Email:
Password:
Password(again):
Superuser created sucessfully.
note that your password will not appear in the terminal when typed in
Now restart the server with python manage.py runserver command. Click the HTTP link that appears in the terminal, and now you should be able to see the login screen for the admin.
Log in with your username and password. You will see the admin homepage next.
We can immediately see that there is a problem. Our posts app doesn't feature here. For us to see our app inside the Django admin we need to update our admin.py file.
In your text editor open the admin.py file and type in the following code.
from django.contrib import admin
from .models import Post
admin.site.register(Post)
refresh your browser and you will see that the app now appears.
Since that's done let's create our first post. Click on the add button opposite Posts and type any message of choice (could be a quote, instruction, or gibberish) in the Text field.
Then click the Save button. You will be redirected to the main post page.
You will note that our new entry is called "Post object". Let's change that. Within the models.py file add a new function str like this:
from django.db import models
class Post(models.Model):
text = models.TextField()
def __str__(self):
return self.text[:50]
This will display the first 50 characters of our text field.
Creating Views/Templates/URLs
For us to be able to display database content on our homepage, we have to put our views, templates, and URLs together.
Lets begin with the view. In the views.py file enter the code below:
from django.views.generic import ListView
from .models import Post
Class HomePageView(ListView):
model = Post
template_name = 'home.html'
In the code we first imported ListView then we imported the post model. In the view, we subclass ListView and specify the correct model and template.
We now need to configure our URLs and make our template. We begin with the template. Within your terminal create a new directory called templates and within the template a home.html file:
$ mkdir templates
$ touch templates/home.html
Now update the DIRS field in our settings.py file like this:
TEMPLATES = [
{
'DIRS': [os.path.join(BASE_DIR, 'templates')],
},
]
In our home.html we will create our own variable called post and then access the desired field to be displayed as post.text:
<h1>Message board homepage</h1>
<ul>
{% for post in object_list %}
<li>{{ post.text }}</li>
{% endfor %}
</ul>
The name object_list isn't that friendly. Instead, we can provide an explicit name via the context_object_name attribute.
In our views.py file, add the following:
context_object_name = 'all_posts_list'
Declaring the name like this helps other members of a team.
Let's also update our template in home.html so that it references all_posts_list rather than object_list.
<h1>Message board homepage</h1>
<ul>
{% for post in all_posts_list %}
<li>{{ post.text }}</li>
{% endfor %}
</ul>
Lastly, let us set up our URL configurations. Do this by adding the code below in our urls.py. We simply add posts and include on the second lines.
from django.urls import path, include
path('' include('posts.urls')),
Then create an app level urls.py file.
$ touch posts/urls.py
then update it like this:
from django.urls import path
from .views import HomePageView
urlpatterns = [
path('', HomePageView.as_view(), name='home'),
]
Restart the server with python manage.py runserver and navigate to our homepage using the http link in the terminal.
WOW! we are all done here, congratulations on making it to the end. You can now add more posts through the Django admin and see how the posts appear. Happy Hacking Ya'll!.
Top comments (1)
Neat and easy to follow, very helpful