Authentication system in the forum application #2: Email verification, Create form and Model Migration by duski.harahap

View this thread on steempeak.com
· @duski.harahap ·
$15.59
Authentication system in the forum application #2: Email verification, Create form and Model Migration
#### Repository
https://github.com/python

#### What Will I Learn?
- Email verification
- Create your own form in Django
- Model migration

#### Requirements
- Basic Python
- Install Python 3
- Install Django


#### Resources
- Python - https://www.python.org/
- Django- https://www.djangoproject.com/
- Bootstrap 4 - https://getbootstrap.com/docs/4.0/getting-started/introduction/
- http://ana-balica.github.io/2015/01/29/pagination-in-django/

#### Difficulty
Basic

### Tutorial Content

Hi all, today we will continue the tutorial about the authentication system on the Django forum. in the previous tutorial [part#1](https://steemit.com/utopian-io/@duski.harahap/authentication-system-in-the-forum-application-1-make-a-change-password-template-and-implement-the-change-password-feature), we have worked on the password change feature in our application. well in this section we will learn how to verify registered e-mail users. Of course, this part is not a basic thing, so I suggest that for those of you who are new in Django. I suggest you follow other tutorials before following this tutorial. We just start the following tutorial.


### Email verification

So far our authentication system has been running well. we have been able to register, login and change the password with the system we have created. I will explain the background of the problem for our reasons for making email verification on our application.

***Why do we have to verify email ?***

In the ***current system***  when the user registers and registers successfully the user will be able to access our forum application immediately. well, sometimes we have to provide additional verification to check whether the user is a valid user by verifying the user's email.

***Change registration using Email***

In the ***current system*** when the user registers we require the user to fill in **USERNAME**, now this method we will change using **EMAIL**. basically, when we create a user model in this [tutorial](https://steemit.com/utopian-io/@duski.harahap/create-a-forum-application-using-django-1-init-projects-and-dependencies-and-database-schema-1551711163679), Need to know in the user model there is a *default* field of Django which is ***is_active*** which is useful as a *reference* whether the user is allowed to **log in or not**. **is_active** is what we will use to give users *permission* to log in.**is_active** has a ***boolean*** value with the default value is **true**. So that in the ***current system*** when we have registered we can immediately log in without having to verify. Well, I have explained how the system we will create and the current system. for that then we just make this feature
<br>

### Add an email field

We will start by creating an additional field to store email users. If you follow this tutorial you will know that when we create a form for a **signup** *we still use the default form from Django*. We can see in the code below:

![Screenshot_3.png](https://ipfs.busy.org/ipfs/QmWHv94pQvVdbe9ovc8XmjtDT6D5AWx9fqS38wEe8KJ9AZ)

we can see in the picture above we still use the default form from Django ```django.contrib.auth.forms```. For that, we will change the form so we can add email fields. I will make our own form. I will create a file with the name **forms.py** under the **account** folder.

- **Custome signup form**

After we create **forms.py** we will copy the form according to our wishes. For more details, we can see the code below:

**account/forms.py**

```
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User

class SignUpForm(UserCreationForm):  // Define Class use UserCreationForm to add email field
	email = forms.EmailField(max_length=200, help_text='Required')

	class Meta:
		model = User
		fields = ('username', 'email', 'password1', 'password2')
```

-  **Import forms module:** To use the Django forms module we must import it first like the following ```from django import forms```.

- **Import UserCreationForm:** then because we will add fields to ***UserCreationForm*** we can import them first ```from django.contrib.auth.forms import UserCreationForm```.

- **Import user model** and don't forget the import user model that we will use to process user data ```from django.contrib.auth.models import User```.

- We will define the class that we will use, namely ```class SignUpForm (UserCreationForm):```. In this function, we will pass the ***UserCreationForm***  as a parameter because we will add an email field to that form. We can add email fields using the ```EmailField()``` function. In this function we have ***two parameters***, namely ```max_length=200``` and ```help_text='Required'```.

- **Meta class:** in our meta class we will define the model we will use, namely ```model = User``` and then we can define what fields we will display as follows ```field = ('username', 'email', 'password1', 'password2')```.
<br>

- **Use SignUpForm on the template**

We have created the ***SignUpForm*** class, now we can use the Form in the **account/views.py** section. We will import the classes that are on **Forms.py**. For more details, we can see in the example below:

**account/views.py**

```
from django.shortcuts import render, redirect
from django.contrib.auth.forms import UserCreationForm, PasswordChangeForm
from django.contrib.auth import update_session_auth_hash
from django.urls import reverse, reverse_lazy
from django.views import generic
from django.contrib import messages
from .forms import SignUpForm

def SignUp(request):
	formClass = SignUpForm
	return render(request, 'signup.html', {'signupForm' : formClass})
```

- The first thing we will do is import ***SignUpForm*** on **forms.py**, we can import it in this way ```from .forms import SignUpForm```.

- The function that we will use is **SignUp** according to the class that we registered in the **account / urls.py** section:

![Screenshot_4.png](https://ipfs.busy.org/ipfs/QmdwPd4iXtnxy6CPXR1osU2ppjA5aYhPazHJNNPtm9d3DA)

- Then after we import from **SignUpForm** we will render the **signup.html** template. We can use the ```render() ``` function that we imported earlier ```from django.shortcuts import render```. We save the **SignUpForm** that we imported into a **formClass** variable ```formClass = SignUpForm``` and the **formClass** variable we will pass to the template with the ```'signupForm'``` name.

- After we render the form to the signup.html template we can display the form in the **signup.html** template:

**account/templates/signup.html**

```
{% extends "base.html" %}

{% block title %} Sign Up{% endblock %}

{% block content %}
<h2>Sign Up</h2>
<form method="post">
	{% csrf_token %}
	{{ signupForm.as_p }}
	<button type="submit" name="button">Register</button>
</form>

{% endblock%}
```

- to render it we can use this method ```{{signupForm.as_p}}```. ***important*** to remember ```signupForm``` is the *key* name of the variable that we are rendering in class **SignUp.**

- If there is no error then we will see the results as follows:

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


We can see in the picture above we have succeeded in adding 1 additional input, e-mail, this means we have successfully created our own form.

### Make a profile model

We have finished the frontend section to *render* a form and add an email field to the **form**. In the backend section, we will create a new model class that we will use as a schema from the profile table. In this class, we will define the fields that we will use in the model. For more details, we can see the example below:

**forums/models.py**

```
class Profile(models.Model):
	user 	= models.OneToOneField(user, null=True, blank=True, on_delete=models.CASCADE)
	activation_key 	= models.CharField(max_length=255, default=1)
	email_validated = models.BooleanField(default=False)
	
	def __str__(self):
		return self.user.username
```

- We will create a Profile function ```class Profile(models.Model)```. In this function, we will pass the model ```models.Model```.

- The first we will create a user field, in the user field we will use the ```OneToOneField ()``` function. We will use this function to make relationships one to one.

- The second field, we will define ***activation_key***. ***activation_key*** uses the ```Charfield ()``` function with ```max_length = 255``` and default value is ```default=1```.

- The third field is ***email_validated***. Well in this field we will save the user's status, whether the user has verified it or not, if it has verified the value is True and the default value is ``default=False```.

-  Then we can retouch the model results in the following way ```def __str__(self):``` and we will return ```return self.user.username```.
<br>
- **Model migration**

Well, after we *define* the fields that will be used in the ***profile*** model. We can migrate so that the model *schema* can be *generated* and recognized by the **Django** system. For more details, we can see the demonstration below:


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

We see in the picture above we managed to make a migration to our new model, there are two steps taken, the following is the explanation:

- **python manage.py makemigrations**

The first thing we will do is make migrations. we will make a migration on the profile model that we have created. If we successfully migrate we will see a new file that is generated as we see in the picture below:

![Screenshot_5.png](https://ipfs.busy.org/ipfs/QmU3mgxzWmaKFA69gFV1RYDrYvRd7QRNm5xi7CJi4NVxXa)

**forums/migrations/003_profile.py**

```
# Generated by Django 2.1.4 on 2019-04-22 13:50

from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('forums', '0002_forum_slug'),
    ]
    operations = [
        migrations.CreateModel(
            name='Profile',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('activation_key', models.CharField(default=1, max_length=255)),
                ('email_validated', models.BooleanField(default=False)),
                ('user', models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
            ],
        ),
    ]
```

The file above is generated from migration, then after we migrate we will **migrate**.

- **Python make migrate**

We have migrated but to use and implement it we have to apply the new model to our system so we need to do ```python manage.py migrate```, we can see in the picture below:

![Screenshot_6.png](https://ipfs.busy.org/ipfs/QmY8PLdDxEMbPbxLagbU4wfSZSoo6qcTUa6dLDmBgTDfBt)

Now we have finished the backend process when verifying email. thank you for following this tutorial hopefully useful


### Curriculum

- **Forum app**

[django#1](https://steemit.com/utopian-io/@duski.harahap/create-a-forum-application-using-django-1-init-projects-and-dependencies-and-database-schema-1551711163679), [django#2](https://steemit.com/utopian-io/@duski.harahap/create-a-forum-application-using-django-2-template-system-and-class-based-view-implementation-1552057536737), [django#3](https://steemit.com/utopian-io/@duski.harahap/create-a-forum-application-using-django-3-base-template-login-and-register-system-1552311993977), [django#4](https://steemit.com/utopian-io/@duski.harahap/create-a-forum-application-using-django-4-admin-dashboard-ang-setting-redirect), [django#5](https://steemit.com/utopian-io/@duski.harahap/create-a-forum-application-using-django-5-slug-concept-and-generated-slug-and-use-forms-generic-view), [django#6](https://steemit.com/utopian-io/@duski.harahap/create-a-forum-application-using-django-6-crud-system-and-url-protection-redirect-system), [django#7](https://steemit.com/utopian-io/@duski.harahap/create-a-forum-application-using-django-7-unique-slug-and-manage-modules-in-admin-dashboard-1553268749861), [django#8](https://steemit.com/utopian-io/@duski.harahap/create-a-forum-application-using-django-8-display-forum-data-and-create-and-implement-list-view-1553525769014),  [django#8](https://steemit.com/utopian-io/@duski.harahap/create-a-forum-application-using-django-8-display-forum-data-and-create-and-implement-list-view-1553525769014),  [django#9](https://steemit.com/utopian-io/@duski.harahap/create-a-forum-application-using-django-9-single-page-for-forums-passing-params-in-routing-and-make-time-humanize-1553788983186),  [django#10](https://steemit.com/utopian-io/@duski.harahap/create-a-forum-application-using-django-10-detail-page-for-forums-use-slug-as-the-parameter-url-and-implement-getcontextdata),  [django#11](https://steemit.com/utopian-io/@duski.harahap/create-a-forum-application-using-django-11-url-behavior-and-update-view-and-edit-menu-1554268753908)


#### Proof of work done

https://github.com/milleaduski/forums-django
πŸ‘  , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , and 88 others
properties (23)
post_id73,538,387
authorduski.harahap
permlinkauthentication-system-in-the-forum-application-2-email-verification-create-form-and-model-migration
categoryutopian-io
json_metadata{"tags":["utopian-io","tutorials","django","python","web"],"image":["https:\/\/ipfs.busy.org\/ipfs\/QmWHv94pQvVdbe9ovc8XmjtDT6D5AWx9fqS38wEe8KJ9AZ","https:\/\/ipfs.busy.org\/ipfs\/QmdwPd4iXtnxy6CPXR1osU2ppjA5aYhPazHJNNPtm9d3DA","https:\/\/cdn.steemitimages.com\/DQmaE8ZNwrP3oFF3fjDJFx7CS3jo3avoQBTAvn2ax8eQzay\/ezgif.com-video-to-gif%20(2).gif","https:\/\/cdn.steemitimages.com\/DQmaaSQXB7rf47CKww4Q1YQLrGL4GkAUL588nWoJCHoW32y\/ezgif.com-video-to-gif%20(3).gif","https:\/\/ipfs.busy.org\/ipfs\/QmU3mgxzWmaKFA69gFV1RYDrYvRd7QRNm5xi7CJi4NVxXa","https:\/\/ipfs.busy.org\/ipfs\/QmY8PLdDxEMbPbxLagbU4wfSZSoo6qcTUa6dLDmBgTDfBt"],"links":["https:\/\/github.com\/python","https:\/\/www.python.org\/","https:\/\/www.djangoproject.com\/","https:\/\/getbootstrap.com\/docs\/4.0\/getting-started\/introduction\/","http:\/\/ana-balica.github.io\/2015\/01\/29\/pagination-in-django\/","https:\/\/steemit.com\/utopian-io\/@duski.harahap\/authentication-system-in-the-forum-application-1-make-a-change-password-template-and-implement-the-change-password-feature","https:\/\/steemit.com\/utopian-io\/@duski.harahap\/create-a-forum-application-using-django-1-init-projects-and-dependencies-and-database-schema-1551711163679","https:\/\/steemit.com\/utopian-io\/@duski.harahap\/create-a-forum-application-using-django-2-template-system-and-class-based-view-implementation-1552057536737","https:\/\/steemit.com\/utopian-io\/@duski.harahap\/create-a-forum-application-using-django-3-base-template-login-and-register-system-1552311993977","https:\/\/steemit.com\/utopian-io\/@duski.harahap\/create-a-forum-application-using-django-4-admin-dashboard-ang-setting-redirect","https:\/\/steemit.com\/utopian-io\/@duski.harahap\/create-a-forum-application-using-django-5-slug-concept-and-generated-slug-and-use-forms-generic-view","https:\/\/steemit.com\/utopian-io\/@duski.harahap\/create-a-forum-application-using-django-6-crud-system-and-url-protection-redirect-system","https:\/\/steemit.com\/utopian-io\/@duski.harahap\/create-a-forum-application-using-django-7-unique-slug-and-manage-modules-in-admin-dashboard-1553268749861","https:\/\/steemit.com\/utopian-io\/@duski.harahap\/create-a-forum-application-using-django-8-display-forum-data-and-create-and-implement-list-view-1553525769014","https:\/\/steemit.com\/utopian-io\/@duski.harahap\/create-a-forum-application-using-django-9-single-page-for-forums-passing-params-in-routing-and-make-time-humanize-1553788983186","https:\/\/steemit.com\/utopian-io\/@duski.harahap\/create-a-forum-application-using-django-10-detail-page-for-forums-use-slug-as-the-parameter-url-and-implement-getcontextdata","https:\/\/steemit.com\/utopian-io\/@duski.harahap\/create-a-forum-application-using-django-11-url-behavior-and-update-view-and-edit-menu-1554268753908","https:\/\/github.com\/milleaduski\/forums-django"],"app":"steemit\/0.1","format":"markdown"}
created2019-04-22 14:41:57
last_update2019-04-22 14:41:57
depth0
children4
net_rshares31,152,126,428,365
last_payout2019-04-29 14:41:57
cashout_time1969-12-31 23:59:59
total_payout_value11.940 SBD
curator_payout_value3.653 SBD
pending_payout_value0.000 SBD
promoted0.000 SBD
body_length13,297
author_reputation60,101,995,119,153
root_title"Authentication system in the forum application #2: Email verification, Create form and Model Migration"
beneficiaries[]
max_accepted_payout1,000,000.000 SBD
percent_steem_dollars10,000
author_curate_reward""
vote details (152)
@portugalcoin ·
$4.98
Thank you for your contribution @duski.harahap.
After reviewing your contribution, we suggest you following points:

- The structure of the tutorial has improved in this contribution. However, we still think bullet placement makes the tutorial a bit confusing.

- In some sections of code you have not added any comments. We suggest that you always put a brief comment on the code sections as it helps less experienced users better understand what you are teaching.

- In our opinion the recovery of the password should be on a different page of the registry.

- Putting a new password could have a validator to check if the password is strong, so as not to let users put passwords easy.

Thank you for your work in developing this tutorial.
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/2-2-1-1-1-3-2-3-).

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

[[utopian-moderator]](https://join.utopian.io/)
πŸ‘  , , , , , , , , , , , , , , , , , , , , , , , ,
properties (23)
post_id73,546,168
authorportugalcoin
permlinkre-duskiharahap-authentication-system-in-the-forum-application-2-email-verification-create-form-and-model-migration-20190422t183243921z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"users":["duski.harahap"],"links":["https:\/\/join.utopian.io\/guidelines","https:\/\/review.utopian.io\/result\/8\/2-2-1-1-1-3-2-3-","https:\/\/discord.gg\/uTyJkNm","https:\/\/join.utopian.io\/"],"app":"steemit\/0.1"}
created2019-04-22 18:32:45
last_update2019-04-22 18:32:45
depth1
children1
net_rshares10,012,684,041,982
last_payout2019-04-29 18:32:45
cashout_time1969-12-31 23:59:59
total_payout_value3.814 SBD
curator_payout_value1.163 SBD
pending_payout_value0.000 SBD
promoted0.000 SBD
body_length1,237
author_reputation214,343,891,436,406
root_title"Authentication system in the forum application #2: Email verification, Create form and Model Migration"
beneficiaries[]
max_accepted_payout1,000,000.000 SBD
percent_steem_dollars10,000
author_curate_reward""
vote details (25)
@utopian-io ·
Thank you for your review, @portugalcoin! Keep up the good work!
properties (22)
post_id73,672,783
authorutopian-io
permlinkre-re-duskiharahap-authentication-system-in-the-forum-application-2-email-verification-create-form-and-model-migration-20190422t183243921z-20190424t232738z
categoryutopian-io
json_metadata{"app":"beem\/0.20.17"}
created2019-04-24 23:27:39
last_update2019-04-24 23:27:39
depth2
children0
net_rshares0
last_payout2019-05-01 23:27:39
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"Authentication system in the forum application #2: Email verification, Create form and Model Migration"
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_id73,546,354
authorsteem-ua
permlinkre-authentication-system-in-the-forum-application-2-email-verification-create-form-and-model-migration-20190422t183927z
categoryutopian-io
json_metadata{"app":"beem\/0.20.19"}
created2019-04-22 18:39:27
last_update2019-04-22 18:39:27
depth1
children0
net_rshares0
last_payout2019-04-29 18:39:27
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"Authentication system in the forum application #2: Email verification, Create form and Model Migration"
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_id73,547,053
authorutopian-io
permlinkre-authentication-system-in-the-forum-application-2-email-verification-create-form-and-model-migration-20190422t190322z
categoryutopian-io
json_metadata{"app":"beem\/0.20.17"}
created2019-04-22 19:03:24
last_update2019-04-22 19:03:24
depth1
children0
net_rshares0
last_payout2019-04-29 19:03: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"Authentication system in the forum application #2: Email verification, Create form and Model Migration"
beneficiaries[]
max_accepted_payout1,000,000.000 SBD
percent_steem_dollars10,000