create account

Create a forum application using django #6: CRUD system and URL protection,redirect system by duski.harahap

View this thread on: hive.blogpeakd.comecency.com
· @duski.harahap · (edited)
$22.21
Create a forum application using django #6: CRUD system and URL protection,redirect system
#### Repository
https://github.com/python

#### What Will I Learn?
- CRUD system
- URL protection and redirect system

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

#### Difficulty
Basic

### Tutorial Content

 I will continue the tutorial series on forum applications that use Django. there are some things that we have done and we have done, you can see them in the curriculum section. Until now the application that has been made already has an authentication, a slug system, and several other features. In this tutorial, we will create a **CRUD(Create, read, update and delete)** system. Of course, the ***CRUD system*** in each application can be different. Then how is it implemented in our application, let's start this tutorial


### CRUD System

The applications that we make relate to data and information, of course, data that is made not dynamic in the meaning  can be changed over time, with dynamic data and always increasing, we need to create a system that can manage data to be *added, deleted and edited.* In the previous [section](https://steemit.com/utopian-io/@duski.harahap/create-a-forum-application-using-django-5-slug-concept-and-generated-slug-and-use-forms-generic-view) we have succeeded in creating a simple form that aims to create a forum on our application, here is the view that we can see:

![Screenshot_11.png](https://ipfs.busy.org/ipfs/QmTNTjohUjEBsSPeEywjfVijNMfMPozZQc7QurAg4bijKQ)

- **Insert data**

In the previous tutorial, we created a class that will be used in the URL ```'forum/add'```. There are 5 fields that we must fulfill to enter data into the forum table. They are ***title, desc, created_at, slug, and user.***

![Screenshot_12.png](https://ipfs.busy.org/ipfs/QmPuy2WP5QgqyGD8dGS78Z8GNupbUWDk5tXPZMnSHvLujz)


- We have got the *title, desc, and created_at* fields from the user input.

- We have got the *slug field* from the **generate** **slug** we have made in the previous [tutorial](https://steemit.com/utopian-io/@duski.harahap/create-a-forum-application-using-django-5-slug-concept-and-generated-slug-and-use-forms-generic-view).

- Now we have to fulfill the user field, we can get the value from the request. For that, we will create a new function that will fill that field. Here is the code:

**forums/views.py**

```
from django.shortcuts import render
from django.views.generic.edit import CreateView
from .models import Forum

class ForumCreate(CreateView):
	model = Forum
	fields = ['title','desc']

	def form_valid(self, form):
		form.instance.user = self.request.user
		return super().form_valid(form)
```

- ```def form_valid(self, form)```: In this function we will receive 2 parameters. The **first** parameter is ***self*** and the **second** is ***form.*** ***self*** is a parameter that we must shift so that we can access *properties* in the class and **form** parameters is the forms used in view.

- ```form.instance.user = self.request.user```: **form.instance.user** is used to get an instance of the form model, so we can access the user key ```form.instance.use``` and then fill in the value obtained from the user request ```self.request.user```.

- And then we run the function ```return super().form_valid(form)```.
<br>

- **Protected URL**

We will create new functions that are important for URL protection systems. Of course, we will protect the URL. ***So that not everyone can access it***. For more details, we can see the code below:

**forums/views.py**

```
from django.shortcuts import render
from django.views.generic.edit import CreateView
from .models import Forum
from django.contrib.auth.decorators import login_required // import function login_required
from django.utils.decorators import method_decorator // import utils method_decorator

@method_decorator(login_required, name='dispatch') //Protected the class
class ForumCreate(CreateView):
	model = Forum
	fields = ['title','desc']

	def form_valid(self, form):
		form.instance.user = self.request.user
		return super().form_valid(form)
```

- With this code, we will *protect* our class so that it **cannot** be accessed if we are not logged in.

- ```from django.contrib.auth.decorators import login_required```  for protection when the user is not logged in.

- ```from django.utils.decorators import method_decorator ``` then we have to import the module method_decorator.

- Now we have imported the ***decorator*** and ***login_required*** method, now we will use it like this ```@method_decorator(login_required, name='dispatch') ```. In **@method_decorator** there are two mandatory parameters. The **first** is the function that will be used ***login-required*** and the **second** is the type decorator **name='dispatch'**.

If there is no error then **we cannot access** the path **'forums/add'**, if the user is not logged in.

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

We can see in the picture above we have succeeded in creating a protection system on our **URL.**
<br>

- **Create forum**

Now we will add data with the user interface that we have created. 

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

![Screenshot_13.png](https://ipfs.busy.org/ipfs/QmPHgSVSxkbobMv9yz5fNwAKUP6bdJdYPdJJVSsWsGoj8F)


We can see in the picture above when we want to submit data, we get a warning. We get this not because of an error in our code. But because we don't define the routing that will be addressed after submitting the data. In **Django** there are two options for resolving this problem, namely ```Either provide a URL``` or ```define a get_absolute_url```.
<br>
- **Use ``` get_absolute_url``` method**

To solve the problem above we will use the method ```get_absolute_url```, ***Where we can use the get_absolute_url method ?***. We can define **models.py** and in the ***forum class*** section, because the class we are accessing is ***forum class***. 

**forums/models.py**

```
from django.db import models
from django.conf import settings
from django.utils.text import slugify
from django.urls import reverse //import the reverse function

class Forum(models.Model):
	user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
	title = models.CharField(max_length=100)
	slug = models.SlugField(unique=True)
	desc = models.TextField()
	created_at = models.DateTimeField(auto_now_add=True)

	def save(self, *args, **kwargs):
		self.slug = slugify(self.title)
		super(Forum, self).save(*args, **kwargs)
	
	def get_absolute_url(self): // define function get_absolute_url
		return reverse('home') // redirect to home

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)
```

- We can define the function in the forum class. ***We cannot change the name of the function***. Because the ```get_absolute_url()``` function is the default function of **Django.** ```get_absolute_url()``` is a function that will automatically run when the **URL** is successfully accessed.

- **Redirect URL**: We will run ```get_absolute_url()``` automatically but haven't done anything yet. For that according to the *warning* we have got. We need to create a redirect page when we successfully do **POST** data. To do the redirect we need help with the ```reverse ()``` function. To use it we must import it as follows ```from django.urls import reverse```.

- ```reverse function ()```: We can pass a parameter that contains the ***Path*** from the URL or ***Alias.*** In this tutorial we will use an ***alias***, after saving the data we will redirect to the homepage. We can give the alias as follows:

```path(' ', TemplateView.as_view(template_name='welcome.html'), name='home')```

I gave the alias the name of the path is ```'home'```. If there is no error then we can see the results as follows

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

We can see in the picture above, we have successfully saved the data and implemented the **get_absolute_url** method.


### Curriculum

- **Class-based views**

[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)
<br>
- **Forum app**

[Create a forum application using django #1 : Init projects and dependencies and Database schema](
https://steemit.com/utopian-io/@duski.harahap/create-a-forum-application-using-django-1-init-projects-and-dependencies-and-database-schema-1551711163679)

[Create a forum application using django #2: Template system and Class-based view implementation](https://steemit.com/utopian-io/@duski.harahap/create-a-forum-application-using-django-2-template-system-and-class-based-view-implementation-1552057536737)

[Create a forum application using django #3: Base template, Login and Register system](https://steemit.com/utopian-io/@duski.harahap/create-a-forum-application-using-django-3-base-template-login-and-register-system-1552311993977)

[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-4-admin-dashboard-ang-setting-redirect)


#### Proof of work done

https://github.com/milleaduski/forums-django
πŸ‘  , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , and 63 others
properties (23)
authorduski.harahap
permlinkcreate-a-forum-application-using-django-6-crud-system-and-url-protection-redirect-system
categoryutopian-io
json_metadata{"tags":["utopian-io","tutorials","python","web","django"],"users":["method"],"image":["https://ipfs.busy.org/ipfs/QmTNTjohUjEBsSPeEywjfVijNMfMPozZQc7QurAg4bijKQ","https://ipfs.busy.org/ipfs/QmPuy2WP5QgqyGD8dGS78Z8GNupbUWDk5tXPZMnSHvLujz","https://cdn.steemitimages.com/DQmcbNKnj5xvSs5Eg3Y8onPkoZa9Q9WqvypZTJBeoT9xin6/ezgif.com-video-to-gif.gif","https://cdn.steemitimages.com/DQmb3yuhyid3FCxWqZYYfaz4ZzaLLXqNQtbhMzQE8myx5Bn/ezgif.com-video-to-gif%20(1).gif","https://ipfs.busy.org/ipfs/QmPHgSVSxkbobMv9yz5fNwAKUP6bdJdYPdJJVSsWsGoj8F","https://cdn.steemitimages.com/DQmSe9DzmPfUp5FyE7isY5fXZ2eoBBP3yD7Bhe1cpQaWwXp/ezgif.com-video-to-gif%20(2).gif"],"links":["https://github.com/python","https://www.python.org/","https://www.djangoproject.com/","https://getbootstrap.com/docs/4.0/getting-started/introduction/","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/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://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://github.com/milleaduski/forums-django"],"app":"steemit/0.1","format":"markdown"}
created2019-03-19 13:35:48
last_update2019-03-19 13:38:51
depth0
children5
last_payout2019-03-26 13:35:48
cashout_time1969-12-31 23:59:59
total_payout_value16.946 HBD
curator_payout_value5.262 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length10,407
author_reputation60,094,717,098,672
root_title"Create a forum application using django #6: CRUD system and URL protection,redirect system"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id81,571,972
net_rshares32,688,601,952,470
author_curate_reward""
vote details (127)
@mcfarhat ·
$12.73
Thank you for your contribution.
- Using the term CRUD system is too vague. It would have made more sense to say CRUD system for the Forum object.
- The functionality itself is very basic, and the entities being created are not too complex.
- As always, good use of images in your content.
- Also appreciate your code comments
- There is still lots of room for improvement to your tutorial English language, but I can certainly see you have come a long way. Good work!


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-2-0-1-1-4-2-3-).

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

[[utopian-moderator]](https://join.utopian.io/)
πŸ‘  , , , , , , , , , , ,
properties (23)
authormcfarhat
permlinkre-duskiharahap-create-a-forum-application-using-django-6-crud-system-and-url-protection-redirect-system-20190319t211819284z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"links":["https://join.utopian.io/guidelines","https://review.utopian.io/result/8/3-2-0-1-1-4-2-3-","https://discord.gg/uTyJkNm","https://join.utopian.io/"],"app":"steemit/0.1"}
created2019-03-19 21:18:21
last_update2019-03-19 21:18:21
depth1
children1
last_payout2019-03-26 21:18:21
cashout_time1969-12-31 23:59:59
total_payout_value9.663 HBD
curator_payout_value3.069 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length921
author_reputation150,651,671,367,256
root_title"Create a forum application using django #6: CRUD system and URL protection,redirect system"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id81,590,780
net_rshares18,822,500,812,935
author_curate_reward""
vote details (12)
@utopian-io ·
Thank you for your review, @mcfarhat! Keep up the good work!
properties (22)
authorutopian-io
permlinkre-re-duskiharahap-create-a-forum-application-using-django-6-crud-system-and-url-protection-redirect-system-20190319t211819284z-20190322t122631z
categoryutopian-io
json_metadata"{"app": "beem/0.20.17"}"
created2019-03-22 12:26:33
last_update2019-03-22 12:26:33
depth2
children0
last_payout2019-03-29 12:26:33
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length60
author_reputation152,955,367,999,756
root_title"Create a forum application using django #6: CRUD system and URL protection,redirect system"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id81,732,382
net_rshares0
@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)
authorsteem-ua
permlinkre-create-a-forum-application-using-django-6-crud-system-and-url-protection-redirect-system-20190319t212806z
categoryutopian-io
json_metadata"{"app": "beem/0.20.18"}"
created2019-03-19 21:28:06
last_update2019-03-19 21:28:06
depth1
children0
last_payout2019-03-26 21:28:06
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length292
author_reputation23,214,230,978,060
root_title"Create a forum application using django #6: CRUD system and URL protection,redirect system"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id81,591,152
net_rshares0
@trufflepig ·
**Congratulations!** Your post has been selected as a daily Steemit truffle! It is listed on **rank 18** of all contributions awarded today. You can find the [TOP DAILY TRUFFLE PICKS HERE.](https://steemit.com/@trufflepig/daily-truffle-picks-2019-03-19) 
    
I upvoted your contribution because to my mind your post is at least **13 SBD** worth and should receive **158 votes**. It's now up to the lovely Steemit community to make this come true.

I am `TrufflePig`, an Artificial Intelligence Bot that helps minnows and content curators using Machine Learning. If you are curious how I select content, [you can find an explanation here!](https://steemit.com/steemit/@trufflepig/weekly-truffle-updates-2019-11)
    
Have a nice day and sincerely yours,
![trufflepig](https://raw.githubusercontent.com/SmokinCaterpillar/TrufflePig/master/img/trufflepig17_small.png)
*`TrufflePig`*
    
properties (22)
authortrufflepig
permlinkre-create-a-forum-application-using-django-6-crud-system-and-url-protection-redirect-system-20190319t170533
categoryutopian-io
json_metadata""
created2019-03-19 17:05:36
last_update2019-03-19 17:05:36
depth1
children0
last_payout2019-03-26 17:05:36
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length885
author_reputation21,266,577,867,113
root_title"Create a forum application using django #6: CRUD system and URL protection,redirect system"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id81,581,196
net_rshares0
@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)
authorutopian-io
permlinkre-create-a-forum-application-using-django-6-crud-system-and-url-protection-redirect-system-20190320t102037z
categoryutopian-io
json_metadata"{"app": "beem/0.20.17"}"
created2019-03-20 10:20:39
last_update2019-03-20 10:20:39
depth1
children0
last_payout2019-03-27 10:20:39
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length595
author_reputation152,955,367,999,756
root_title"Create a forum application using django #6: CRUD system and URL protection,redirect system"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id81,616,076
net_rshares0