Create a forum application using django #1 : Init projects and dependencies and Database schema
Repository
What Will I Learn?
- Init projects and dependencies
- Database schema and migration
Requirements
- Basic Python
- Install Python 3
- Install Django
Resources
- Python - https://www.python.org/
- Django- https://www.djangoproject.com/
Difficulty
Basic
Tutorial Content
Hi everyone, this tutorial will discuss the application of the forums using one of the frameworks of python, that is Django. Of course, Django is no stranger to the python developers, some time ago I explored Django to create an application project forum. now I will share the tutorial on my blog. I suggest you first learn the basics of python and find out what is Django?. This tutorial will start from the beginning by initiating the project. let's see what will be made in this tutorial. The first part that will start is initializing the project and creating the basic structure then there will be authentication to the user.
Init Project
This tutorial requires python installation and also the Django installation. I suggest installing the dependencies first. I will start by initializing the Django project. I will create a project folder with the name forum-django and initialize the project forum in it, for example, can be seen in the picture below:
Init folder
and the following are folders and dependencies that are made automatically based on the commands we run on the terminal.
- Settings
Now there are a few settings that must be done to connect main projects (apps) to subprojects (forums). The settings are located in the app / settings.py
. Open the file and add the directory from our subproject as shown below:
settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# Init forums
'forums'
]
Ad then still in the settings.py file I will add a directory to the template that will be used in this project can be seen in the key TEMPLATES:
Models
A with other applications, of course, the application requires interaction with the database and generally Django also has its own MVC system. for that, I will make the models structure first. when generating project forums automatically models.py has been created. can be seen in the forums/ models.py
folder.
models.py
from django.db import models
# Create your models here.
- Forum models class
For now, the models that will be created first are named forums. so the models.py can contain abstractions from a table in the form of a class. Starting with creating a class model for the forum. here's how to declare it.
Note: The forum rules are that each forum is created by the user and the forum can have more than a few comments in it, with rules like that then I will abstraction it in a forum class like the example below:
models.py
from django.db import models
from django.conf import settings
class Forum(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
title = models.CharField(max_length=100)
desc = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
user
as a foreign key: to make foreign keys on models, you can use theForeignKey ()
function, Well in ForeignKey() has the two parameters which the first is the destination relations of ForeignKeysettings.AUTH_USER_MODEL
and because this is a foreign key we can set the on_delete methodon_delete=models.CASCADE
. I did not make the model user because it already has createdsettings.AUTH_USER_MODEL
but to use it I need to import the settings inmodels.py
like the followingfrom django.conf import settings
.title
as Charfield: I will give the title type varchar with a maximum length of 100 charactersmodels.Charfield(max_length=100)
.desc
as Textfield: Then in the forum class I will create a desc field for the description of the forum, I will use a text field because the possibility of the description will have a much textmodels.TextField()
.created_at
as DateTime: And then I will create a field to save the forum creation date by using theDateTimeField ()
function and the default time I set to be the current timemodels.DateTimeField(auto_now_add=True)
.
For now, only those fields are needed in the forum class. Next, I will make a class comment to save every comment that is in the forum.
- Comment models class
So each forum will have comments in it, later the user will interact with other users by using comments. For that, I will design the database structure.
Note: The Rules of the Comment class are that each comment must have a user and each comment must be related to forum. the following is a sequence of comment classes:
class Comment(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
forum = models.ForeignKey(Forum, on_delete=models.CASCADE)
desc = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
User
as a foreign key: same as in the forum class, here the user is still a foreign key whose value is taken fromsettings.AUTH_USER_MODEL
.forum
as a foreign key: class comment has two foreign keys and one of them is the key forum, as I mentioned below, the comments must have a relationship with the forum so I put the forum as a foreign key comment.models.ForeignKey(Forum, on_delete=models.CASCADE)
desc
as Textfield: in the comment class there is also a description of the contents of the commentmodels.TextField()
created_at
as DateTimeField: And then the comment will also have a created_at field which is by default nowmodels.DateTimeField(auto_now_add=True)
.
Database migration
After creating a class and defining the fields that will be used in the class, now all you have to do is migrate the database so that the database schema can be formed. To do a migration, you can use:
python manage.py makemigrations
and then after the migration is made you run the migration using:
python manage.py migrate
For more details, see the demonstration below:
and the following is a file that is formed from the migration results that are run above. if the file has been formed, the database migration process has been successful.
0001_initial.py
# Generated by Django 2.1.4 on 2019-03-04 14:00
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Comment',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('desc', models.TextField()),
('created_at', models.DateTimeField(auto_now_add=True)),
],
),
migrations.CreateModel(
name='Forum',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=100)),
('desc', models.TextField()),
('created_at', models.DateTimeField(auto_now_add=True)),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
migrations.AddField(
model_name='comment',
name='forum',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='forums.Forum'),
),
migrations.AddField(
model_name='comment',
name='user',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
),
]
User Authentication
then I will enter the authentication to the user. well in this section I will create a new module that will use everything related to the account. to make a new module can go through the terminal like the following example:
and don't forget to add the module you just created in settings.py
- Create Signup
Before creating a page the signup needs to know that Django has set up an auth system that is ready to use but Django does not set up a page or signup feature on the application, because of this I will create the URL and page. the Django URL starts with urls.py in the apps folder.
app/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('account/', include('account.urls')), // new routing that is connected with the account module
]
- I will create a separate routing system that is in the module account. Therefore I will direct the routing
account /
to the urls in the account modulepath('account/', include('account.urls'))
. So I use ainclude()
function to include files and to use them I have to import the first include functions like thisfrom django.urls import path, include
. urls is the file name that we will create in the module account.
then I switch to the module account and create a new file urls.py.
account/urls.py
from django.urls import path
from . import views
urlpattern = [
path('signup/', views.SignUp.as_view(), name=sigup),
]
The URLs account only needs to import parts and new routing is signup, in this routing, I will share how to implement a class-based view, for that, I suggest you follow my previous tutorial about the class-based view in the curriculum section. For now I'll just see my tutorial this time. in the next tutorial, I will discuss more how authentication processes will be used in this forum application. Thank you for following this tutorial.
Curriculum
Tutorial Django - Class based view #2 : Use Class based view method and Get and Post method
Thank you for your contribution @duski.harahap.
After analyzing your tutorial we suggest the following points below:
Using the first person in the tutorials makes it difficult to understand the tutorials. We suggest using the third person in your text.
Using GIFs to show results is definitely better than standard still images.
We suggest you put comments in your code. We have already mentioned this point several times in your tutorials!
Looking forward to your upcoming tutorials.
Your contribution has been evaluated according to Utopian policies and guidelines, as well as a predefined set of questions pertaining to the category.
To view those questions and the relevant answers related to your post, click here.
Need help? Chat with us on Discord.
[utopian-moderator]
Thank you for your review, @portugalcoin! Keep up the good work!
Congratulations @duski.harahap!
You raised your level and are now a Minnow!
Do not miss the last post from @steemitboard:
Vote for @Steemitboard as a witness and get one more award and increased upvotes!
Hi @duski.harahap!
Your post was upvoted by @steem-ua, new Steem dApp, using UserAuthority for algorithmic post curation!
Your post is eligible for our upvote, thanks to our collaboration with @utopian-io!
Feel free to join our @steem-ua Discord server
Hey, @duski.harahap!
Thanks for contributing on Utopian.
We’re already looking forward to your next contribution!
Get higher incentives and support Utopian.io!
Simply set @utopian.pay as a 5% (or higher) payout beneficiary on your contribution post (via SteemPlus or Steeditor).
Want to chat? Join us on Discord https://discord.gg/h52nFrV.
Vote for Utopian Witness!