Create a forum application using django #1 : Init projects and dependencies and Database schema by duski.harahap

View this thread on steempeak.com
· @duski.harahap ·
$30.95
Create a forum application using django #1 : Init projects and dependencies and Database schema
#### Repository
https://github.com/python

#### 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**


![Screenshot_1.png](https://ipfs.busy.org/ipfs/QmRSUpfMnFLPVDsqfNHEVb8uMdvMSpgTSxT12tZ21NSMpd)

and the following are folders and dependencies that are made automatically based on the commands we run on the terminal.

![Screenshot_2.png](https://ipfs.busy.org/ipfs/QmfAJdgvR2h6ZUQ2HheMcnyft1tMdfTgsyxNBJqLabMLst)
<br>

-  **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**:

![Screenshot_3.png](https://ipfs.busy.org/ipfs/QmekefA6RSzqAGfMzSyhCpmdpyMHLhCASrj8nehis1tXL3)
<br>

### 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 the ```ForeignKey ()``` function, Well in **ForeignKey()** has the two parameters which the first is the destination relations of ForeignKey ```settings.AUTH_USER_MODEL``` and because this is a foreign key we can set the on_delete method ```on_delete=models.CASCADE```. I did not make the model user because it already has created ```settings.AUTH_USER_MODEL``` but to use it I need to **import** the settings in ```models.py``` like the following ```from django.conf import settings```.

- ```title``` as Charfield: I will give the title type varchar with a maximum length of 100 characters ```models.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 text ```models.TextField()```.

- ```created_at ``` as DateTime: And then I will create a field to save the forum creation date by using the ```DateTimeField ()``` function and the default time I set to be the current time ```models.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.
<br>


- **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 from ```settings.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 comment ```models.TextField()```

-  ```created_at``` as DateTimeField: And then the comment will also have a created_at field which is by default now ```models.DateTimeField(auto_now_add=True)```.
<br>
- **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:

![ezgif.com-video-to-gif (1).gif](https://cdn.steemitimages.com/DQmYoTm47Tobg6SQJSEdzPsyfcKDRshFdRBUAqaJ5kNq5Hc/ezgif.com-video-to-gif%20(1).gif)

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:

![ezgif.com-video-to-gif.gif](https://cdn.steemitimages.com/DQmah5ovUZEUcUruhMxViVNV4TQPg4cTYmFXNqTZMsdVo2y/ezgif.com-video-to-gif.gif)

and don't forget to add the module you just created in **settings.py**
![Screenshot_4.png](https://ipfs.busy.org/ipfs/Qme3ourZAWBz1JbZs4H679j2MJBtJnbYrzPPufvCgnjCSr)

- **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 module ``` path('account/', include('account.urls'))```. So I use a ```include()``` function to **include** files and to use them I have to import the first include functions like this ```from 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 views #1 : Installation and configuration Django, Using a template system](https://steemit.com/utopian-io/@duski.harahap/django-tutorial-class-based-view-1-installation-and-configuration-django-using-a-template-system-1545837443632)

[Tutorial Django - Class based view #2 : Use Class based view method and Get and Post method](
https://steemit.com/utopian-io/@duski.harahap/django-tutorial-class-based-view-2-use-class-based-view-method-and-get-and-post-method-1546448948207)

[Tutorial Django- Class based view #3 : Authentication in Django and Urls Protection globally and specifically](
https://steemit.com/utopian-io/@duski.harahap/django-tutorial-class-based-view-3-authentication-in-django-and-urls-protection-globally-and-specifically-1546614192675)


#### Proof of work done

https://github.com/milleaduski/forums-django
πŸ‘  , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , and 56 others
properties (23)
post_id70,931,322
authorduski.harahap
permlinkcreate-a-forum-application-using-django-1-init-projects-and-dependencies-and-database-schema-1551711163679
categoryutopian-io
json_metadata{"app":"steeditor\/0.1.2","format":"markdown","image":["https:\/\/ipfs.busy.org\/ipfs\/Qme3ourZAWBz1JbZs4H679j2MJBtJnbYrzPPufvCgnjCSr","https:\/\/ipfs.busy.org\/ipfs\/QmRSUpfMnFLPVDsqfNHEVb8uMdvMSpgTSxT12tZ21NSMpd","https:\/\/ipfs.busy.org\/ipfs\/QmfAJdgvR2h6ZUQ2HheMcnyft1tMdfTgsyxNBJqLabMLst","https:\/\/ipfs.busy.org\/ipfs\/QmekefA6RSzqAGfMzSyhCpmdpyMHLhCASrj8nehis1tXL3","https:\/\/cdn.steemitimages.com\/DQmYoTm47Tobg6SQJSEdzPsyfcKDRshFdRBUAqaJ5kNq5Hc\/ezgif.com-video-to-gif%20(1","https:\/\/cdn.steemitimages.com\/DQmah5ovUZEUcUruhMxViVNV4TQPg4cTYmFXNqTZMsdVo2y\/ezgif.com-video-to-gif.gif","https:\/\/ipfs.busy.org\/ipfs\/Qme3ourZAWBz1JbZs4H679j2MJBtJnbYrzPPufvCgnjCSr"],"tags":["utopian-io","tutorials","python","web","django"],"users":["duski"],"links":["https:\/\/github.com\/python","https:\/\/www.python.org\/","https:\/\/www.djangoproject.com\/","https:\/\/cdn.steemitimages.com\/DQmYoTm47Tobg6SQJSEdzPsyfcKDRshFdRBUAqaJ5kNq5Hc\/ezgif.com-video-to-gif%20","https:\/\/steemit.com\/utopian-io\/@duski.harahap\/django-tutorial-class-based-view-1-installation-and-configuration-django-using-a-template-system-1545837443632","https:\/\/steemit.com\/utopian-io\/@duski.harahap\/django-tutorial-class-based-view-2-use-class-based-view-method-and-get-and-post-method-1546448948207","https:\/\/steemit.com\/utopian-io\/@duski.harahap\/django-tutorial-class-based-view-3-authentication-in-django-and-urls-protection-globally-and-specifically-1546614192675","https:\/\/github.com\/milleaduski\/forums-django"]}
created2019-03-04 14:52:51
last_update2019-03-04 14:52:51
depth0
children5
net_rshares45,937,146,120,766
last_payout2019-03-11 14:52:51
cashout_time1969-12-31 23:59:59
total_payout_value23.254 SBD
curator_payout_value7.693 SBD
pending_payout_value0.000 SBD
promoted0.000 SBD
body_length11,825
author_reputation60,101,995,119,153
root_title"Create a forum application using django #1 : Init projects and dependencies and Database schema"
beneficiaries
0.
accountutopian.pay
weight500
max_accepted_payout100,000.000 SBD
percent_steem_dollars10,000
author_curate_reward""
vote details (120)
@steemitboard ·
<center>[![](https://steemitimages.com/175x175/http://steemitboard.com/@duski.harahap/level.png?201903041843)](http://steemitboard.com/@duski.harahap)
**Congratulations @duski.harahap**!
You raised your level and are now a **Minnow**!</center>

**Do not miss the last post from @steemitboard:**
<table><tr><td><a href="https://steemit.com/carnival/@steemitboard/carnival-2019"><img src="https://steemitimages.com/64x128/http://i.cubeupload.com/rltzHT.png"></a></td><td><a href="https://steemit.com/carnival/@steemitboard/carnival-2019">Carnival Challenge - Collect badge and win 5 STEEM</a></td></tr></table>

###### [Vote for @Steemitboard as a witness](https://v2.steemconnect.com/sign/account-witness-vote?witness=steemitboard&approve=1) and get one more award and increased upvotes!
properties (22)
post_id70,941,380
authorsteemitboard
permlinksteemitboard-notify-duskiharahap-20190304t193818000z
categoryutopian-io
json_metadata{"image":["https:\/\/steemitboard.com\/img\/notify.png"]}
created2019-03-04 19:38:18
last_update2019-03-04 19:38:18
depth1
children0
net_rshares0
last_payout2019-03-11 19:38:18
cashout_time1969-12-31 23:59:59
total_payout_value0.000 SBD
curator_payout_value0.000 SBD
pending_payout_value0.000 SBD
promoted0.000 SBD
body_length788
author_reputation38,705,954,145,809
root_title"Create a forum application using django #1 : Init projects and dependencies and Database schema"
beneficiaries[]
max_accepted_payout1,000,000.000 SBD
percent_steem_dollars10,000
@portugalcoin ·
$14.28
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](https://join.utopian.io/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](https://review.utopian.io/result/8/3-1-1-2-1-3-3-3-).

---- 
Need help? Chat with us on [Discord](https://discord.gg/uTyJkNm).

[[utopian-moderator]](https://join.utopian.io/)
πŸ‘  , , , , , , , , , , , , , , , , , , ,
properties (23)
post_id70,943,488
authorportugalcoin
permlinkre-duskiharahap-create-a-forum-application-using-django-1-init-projects-and-dependencies-and-database-schema-1551711163679-20190304t204639287z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"users":["duski.harahap"],"links":["https:\/\/join.utopian.io\/guidelines","https:\/\/review.utopian.io\/result\/8\/3-1-1-2-1-3-3-3-","https:\/\/discord.gg\/uTyJkNm","https:\/\/join.utopian.io\/"],"app":"steemit\/0.1"}
created2019-03-04 20:46:39
last_update2019-03-04 20:46:39
depth1
children1
net_rshares19,448,208,196,800
last_payout2019-03-11 20:46:39
cashout_time1969-12-31 23:59:59
total_payout_value10.846 SBD
curator_payout_value3.435 SBD
pending_payout_value0.000 SBD
promoted0.000 SBD
body_length946
author_reputation214,343,891,436,406
root_title"Create a forum application using django #1 : Init projects and dependencies and Database schema"
beneficiaries[]
max_accepted_payout1,000,000.000 SBD
percent_steem_dollars10,000
author_curate_reward""
vote details (20)
@utopian-io ·
Thank you for your review, @portugalcoin! Keep up the good work!
properties (22)
post_id71,031,304
authorutopian-io
permlinkre-re-duskiharahap-create-a-forum-application-using-django-1-init-projects-and-dependencies-and-database-schema-1551711163679-20190304t204639287z-20190306t235711z
categoryutopian-io
json_metadata{"app":"beem\/0.20.17"}
created2019-03-06 23:57:12
last_update2019-03-06 23:57:12
depth2
children0
net_rshares0
last_payout2019-03-13 23:57:12
cashout_time1969-12-31 23:59:59
total_payout_value0.000 SBD
curator_payout_value0.000 SBD
pending_payout_value0.000 SBD
promoted0.000 SBD
body_length64
author_reputation152,913,012,544,965
root_title"Create a forum application using django #1 : Init projects and dependencies and Database schema"
beneficiaries[]
max_accepted_payout1,000,000.000 SBD
percent_steem_dollars10,000
@steem-ua ·
#### 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](https://discord.gg/KpBNYGz)**
properties (22)
post_id70,947,094
authorsteem-ua
permlinkre-create-a-forum-application-using-django-1-init-projects-and-dependencies-and-database-schema-1551711163679-20190304t224908z
categoryutopian-io
json_metadata{"app":"beem\/0.20.18"}
created2019-03-04 22:49:09
last_update2019-03-04 22:49:09
depth1
children0
net_rshares0
last_payout2019-03-11 22:49:09
cashout_time1969-12-31 23:59:59
total_payout_value0.000 SBD
curator_payout_value0.000 SBD
pending_payout_value0.000 SBD
promoted0.000 SBD
body_length292
author_reputation23,203,609,903,979
root_title"Create a forum application using django #1 : Init projects and dependencies and Database schema"
beneficiaries[]
max_accepted_payout1,000,000.000 SBD
percent_steem_dollars10,000
@utopian-io ·
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](https://chrome.google.com/webstore/detail/steemplus/mjbkjgcplmaneajhcbegoffkedeankaj?hl=en) or [Steeditor](https://steeditor.app)).

**Want to chat? Join us on Discord https://discord.gg/h52nFrV.**

<a href='https://steemconnect.com/sign/account-witness-vote?witness=utopian-io&approve=1'>Vote for Utopian Witness!</a>
properties (22)
post_id70,952,045
authorutopian-io
permlinkre-create-a-forum-application-using-django-1-init-projects-and-dependencies-and-database-schema-1551711163679-20190305t020523z
categoryutopian-io
json_metadata{"app":"beem\/0.20.17"}
created2019-03-05 02:05:24
last_update2019-03-05 02:05:24
depth1
children0
net_rshares0
last_payout2019-03-12 02:05:24
cashout_time1969-12-31 23:59:59
total_payout_value0.000 SBD
curator_payout_value0.000 SBD
pending_payout_value0.000 SBD
promoted0.000 SBD
body_length595
author_reputation152,913,012,544,965
root_title"Create a forum application using django #1 : Init projects and dependencies and Database schema"
beneficiaries[]
max_accepted_payout1,000,000.000 SBD
percent_steem_dollars10,000