Create a forum application using django #5: Slug concept and generated slug and Use forms generic view

in #utopian-io5 years ago

Repository

https://github.com/python

What Will I Learn?

  • Slug concept and generated slug
  • Use forms generic view

Requirements

  • Basic Python
  • Install Python 3
  • Install Django

Resources

Difficulty

Basic

Tutorial Content

Hi everyone, still in the same tutorial. this time we will add features in the application that we have made before. In this tutorial, we will add some functionalities from the application that we made to make it more comfortable for users to use. The first step to be made is the slug concept in the web URL. the concept is commonly used in many web applications that exist today. For that, we just start this tutorial. for those of you who just joined this tutorial, it is recommended to follow the tutorial in the curriculum.

Slug concept

Of course when we create applications related to information, news, or even steemit blogs also use the Slug concept on the URL as we see in the picture below:
Screenshot_3.png

as we have seen in the picture above the URL is https://steemit.com/utopian-io/@duski.harahap/create-a-forum-application-using-django-4-admin-dashboard-ang-setting-redirect. create-a-forum-application-using-django-4-admin-dashboard-ang-setting-redirect is a Slug that becomes a unique key that distinguishes it from other content and blogs. usually, we give a unique ID to a data.

Why should you use a slug ??

So why should we use Slug ?, can you imagine if we make dozens of articles in our database and each article has its own unique ID, then the URL in our application will be like this:

example: https://steemit.com/utopian-io/@duski.harahap/1298500

So which one is more elegant and comfortable to use, the URL above or the URL like this:

example: https://steemit.com/utopian-io/@duski.harahap/create-a-forum-application-using-django-4-admin-dashboard-ang-setting-redirect.

The slug that we see above is taken from the title of the article, but later generated by the system to be like this create-a-forum-application-using-django-4-admin-dashboard-ang-setting-redirect. The use of Slug is not only limited to display URL but recommended being used in Search engine optimization (SEO). So later the search engine will easily find your article because your URL can be read easily by the search engine algorithm. So in this section, we will apply the concept to the forum application.

  • Generate Slug

We will start making Slug for this application, at the beginning of this tutorial, there is a special tutorial that discusses the basic structure of this application, we can see in this tutorial.

The tutorial discusses models in the database structure. We will add a new field that will be used to save Slug. the following are the models we have added to the slug field.

forums/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)
    slug = models.SlugField(unique=True)
    desc = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)
  • We have added Slug to the Forum class. to make Slug we can use the SlugField () method that Django has provided and we will set it to be unique models.SlugField(unique=True).

  • Well, what we do is just define a new field. Of course, we not only want to define but also have to save the Slug, to save we can do one of the ways below:

forums/models.py

from django.db import models
from django.conf import settings
from django.utils.text import slugify // import utils for generate slug

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)
  • Before saving it, we must first regenerate the title to make the slug. Of course, the generate slug method varies in each programming language.

  • To work on slug we need to help the function of slugify, we must import this function first in this section from django.utils.text import slugify.

  • After that, we can define a function to save the slug using def save(). In this function we will use the slugify() function that we imported earlier, self proposes property that is in the class.

  • Define the result of generating slug from the title property and save it in slug property like this self.slug = slugify(self.title).

  • Then we can save the current generated results in the slug property with the super(Forum, self).save(*args, **kwargs).

  • After everything is finished we need to do a re-migration to update the models we made before. For more details you can see the demonstration below:

ezgif.com-video-to-gif.gif

We have successfully re-migrated the models that we have made before if we see there is a warning like we can see in the picture below:

Screenshot_5.png

This warning is intended because we have previously created a model and now we will re-migrate, confirm the change by selecting number 1 and selecting 2 if you cancel it.


Forum.objects.create(title="This the first title Slug", desc="This is the description from first title", user=user)

  • Slug implementation

then we will not only re-migrate but will implement it on our application, for that I will do a test first in the command prompt. So if something goes wrong we can change it before implementing it in the real project.

ezgif.com-video-to-gif (1).gif

We will test it through the Django shell. to shorten the size and duration of the gif I will immediately show the process when saving forum data.

Screenshot_6.png

We can see in the picture above, we have succeeded in making the slug system generated from the title.

Create Forums

Well now in this section we will create a forum module, as we saw in the demonstration above. we enter the data through the shell in python. For that, we will make users interact in the application.

  • Add routing forum in main routing

We will start adding routing forums to the main routing. For more details, we can see the code below

apps/urls.py

from django.contrib import admin
from django.urls import path, include
from django.views.generic import TemplateView

urlpatterns = [
    path('', TemplateView.as_view(template_name='welcome.html')),
    path('admin/', admin.site.urls),
    path('account/', include('account.urls')),
    path('account/', include('django.contrib.auth.urls')),
    path('forum/', include('forums.urls')) // New routing for module forums
]
  • path('forum/', include('forums.urls')): We are adding new routing to the module forums. The path is at fourms / and then we will include the URL in the module forums include('forums.urls').

  • Add routing in module forums

After adding routing to the main routing in apps/urls.py we will now add routing in the module forums. For more details, we can see the code as follows:

forums/urls.py

from django.urls import path // import urls
from .views import ForumCreate // import generic view

urlpatterns = [
path('add/', ForumCreate.as_view(), name='forum-add')
]
  • from .views import ForumCreate: Here I will import all views in the ForumCreate class. We will create ForumCreate in the next section.

  • path('add/', ForumCreate.as_view(name='forum-add')): Define the path that will be used in this section I will create the'add /' path and use the class ForumCreate.as_view() and name the view name='forum-add'

Note: how to separate routes based on each module seems complicated. but we will get routing results that are more structured and easier to maintain.

  • Use forms generic views

Then I will create the ForumCreate class in the views.py section, in this class we will use a generic view that comes from Django to create forms, so later routing 'forums / add' will be used to add forums, for more details, we can see in the views.py section.

forums/views.py

from django.shortcuts import render // to Render template
from django.views.generic.edit import CreateView // Import create view from generic views
from .models import Forum // import models Forum 

class ForumCreate(CreateView):
    model = Forum
    fields = ['title','desc']
  • from django.shortcuts import render: This is used to render the template.

  • from django.views.generic.edit import CreateView: We will import the generic view provided by Django to create Forms

  • from .models import Forum: Because we will relate to the database, we will import the Forum class model. make sure the name matches the class defined, as you can see in the picture below:

Screenshot_7.png

  • class ForumCreate(CreateView): As we have imported in the forums/urls.py section, the class name must be the same as the name we imported:

Screenshot_8.png

  • Create generic view for add

We will see how the routing that we have created is located in the path forums/add/. Make sure you have run the server and the following looks:

Screenshot_10.png

We can see in the picture above, the system expects a template, forums/forum_form.html, but the template does not exist. therefore we must create it in the directory templates/forums/forum-form.html, the following is the template:

forums/forum-form.html

{% extends "base.html" %}

{% block title %} Create Forums{% endblock %}

{% block content %}
<h2>Add Forum</h2>
<form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit" name="button">Submit</button>
</form>

{% endblock%}

In this template, we are still using the base layout that we created in the previous tutorial, if it works we will render the template correctly. like the picture below:

ezgif.com-video-to-gif (2).gif

Curriculum

  • Class-based views

Tutorial Django - Class based views #1 : Installation and configuration Django, Using a template system

Tutorial Django - Class based view #2 : Use Class based view method and Get and Post method

Tutorial Django- Class based view #3 : Authentication in Django and Urls Protection globally and specifically

  • Forum app

Create a forum application using django #1 : Init projects and dependencies and Database schema

Create a forum application using django #2: Template system and Class-based view implementation

Proof of work done

https://github.com/milleaduski/forums-django

Sort:  

Thank you for your contribution @duski.harahap.
After analyzing your tutorial we suggest the following points below:

  • Your tutorial is very interesting, thanks for your work in making this contribution.

  • Your screenshots and GIFs look great on your tutorial.

  • Thanks for following our suggestions in your previous tutorials. Your contribution has improved a lot.

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 have completed the following achievement on the Steem blockchain and have been rewarded with new badge(s) :

You published more than 80 posts. Your next target is to reach 90 posts.

You can view your badges on your Steem Board and compare to others on the Steem Ranking
If you no longer want to receive notifications, reply to this comment with the word STOP

To support your work, I also upvoted your post!

Do not miss the last post from @steemitboard:

Are you a DrugWars early adopter? Benvenuto in famiglia!
Vote for @Steemitboard as a witness to 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!

Coin Marketplace

STEEM 0.35
TRX 0.12
JST 0.040
BTC 70455.47
ETH 3561.82
USDT 1.00
SBD 4.71