Create a forum application using django #9: Single page for forums, Passing params in routing and humanize time
Repository
What Will I Learn?
- Single page for forums
- Passing params in routing and Make humanize time
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
This tutorial is the previous tutorial series, for those of you who are just following this tutorial I suggest to follow the previous tutorial series. We have learned many things, now I will continue the features of the previous tutorial. this time we will create a single page for the forum application. The data that we display before is general data, does not explain the details. for more details, we just start the following tutorial.
Single page for forums
Here I will discuss how we process data into single pages. we can start creating a single page by creating a new path. The following is the path we will create:
forums/urls.py
from django.urls import path
from .views import ForumCreate, ForumListView, ForumUserListView //import the class view
urlpatterns = [
path('', ForumListView.as_view(), name='forum-list'),
path('by/<username>/', ForumUserListView.as_view(), name='forum-by'), // new path
path('add/', ForumCreate.as_view(), name='forum-add')
]
We will use the new view class in the path we will create. for that, we need to import it as follows
from .views import ForumUserListView
. ForumUserListView is the class name we use in forums/views.py.
noted: make sure the class name is the same as the one defined in the forums / urls.py class. we will make this class in the next section.The new path that we will use is
by/<username>/
. I this path we will pass the parameter, namely username, this parameter which will be a unique value. to ass the parameters in routing, We can use the< >
sign. After we have defined routing then we will define the class of view that we are going to use, namely ForumUserListView and give a namename='forum-by'
.
- Create ForumUserListView class
We have imported this class at the top. but we haven't made this class yet, now we will make it. We will make the view class in forums/views.py:
from django.shortcuts import render, get_object_or_404
from django.contrib.auth.models import user // import models user
class ForumUserListView(ListView):
template_name = 'forums/forum_by_user.html'
def get_queryset(self):
self.user = get_object_or_404(User, username = self.kwargs['username'])
return Forum.objects.filter(user = self.user)
Here I will define the view class that we have used. we will still use the ListView in this class
class ForumUserListView(ListView):
.Define template: We can customize what template will be rendered in this class, we can make it like this
template_name = 'forums/forum_by_user.html'
.Define query_set(): In this class, we will process the data and filter it so we will do programming logic in this function, so we can do it we can use function
def get_queryset(self)
.Use query_set(): By using
get_queryset ()
we will check whether the username that is being accessed is exist. Because there is a possibility that the user will fill in the wrong parameter, so here we will prevent that. self refers to data contained in this class.Check valid user: to check whether the user exists, we can use the
get_object_or_404()
function. But before that, we have to import the function first like thisfrom django.shortcuts import get_object_or_404
. In this function we will pass two parameters, the first parameter is User data and the second is the parameter we take from the URLusername = self.kwargs['username']
. We can take the value of that parameter fromself.kwargs['username']
.
Noted: We have used User models, to use it we have to import it first like thisfrom django.contrib.auth.models import user
.Filter user: then we will do a filter to filter the data to be rendered according to the username that is passed on the URL
return Forum.objects.filter(user = self.user)
. We can usefilter()
function.
Render URL in frontend
Here we will render the URL in the frontend. I will render the URL in the <a>
tag so that we can access the URL. For more details, we can see the code below:
{% extends "base.html" %}
{% block title %} List Forum{% endblock %}
{% block content %}
<div class="jumbotron">
<h1>Forums</h1>
<ul>
{% for forum in object_list %}
<li>{{forum.title}} | <a href="{% url 'forum-by' forum.user %}">{{forum.user}}</a> | <span style="font-size: 12px;"><i>{{forum.created_at}}</i></span></li><br>
{% endfor %}
</ul>
</div>
{% endblock%}
- In order to be able to restore the URL in our template we can use it like this
{% url 'forum-by' forum.user%}
. 'forum-by' is the alias we gave to the URL.
We can give a ' '
sign for an alias and its parameters we can pass after an alias and when we inspect elements we can see the rendering results from {% url 'forum-by' forum.user %}
to see the results we will demo the results, If there is no error then we can see the results as shown below:
We can see in the picture above we have successfully implemented a single view on Django. the data displayed is detailed from the data forums. In this tutorial, we have 2 usernames namely milleaduski1994 and milleaduski.
Of course, we will also handle when the user enters username parameters that do not exist. then the user will get a response like the following:
- Make time humanize and sort the data
In this section, you can make information that aims to provide additional information to the user. Here we have the forums, but the time displayed is uncomfortable to read. we will make it more pleasing to the eye and easier to understand. to use the humanize time, we first do add 'django.contrib.humanize'
in the settings.py file in the INSTALLED_APPS section, like the example below:
settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.humanize', // for humanize time
# Init forums
'forums',
'account'
]
Then installed the apps we will use in the template section. here's how to load it.
{% extends "base.html" %}
{% load humanize %}
{% block title %} List Forum{% endblock %}
{% block content %}
<div class="jumbotron">
<h1>Forums</h1>
<ul>
{% for forum in object_list %}
<li>{{forum.title}} | <a href="{% url 'forum-by' forum.user %}">{{forum.user}}</a> | <span style="font-size: 12px;"><i>{{forum.created_at | naturaltime}}</i></span></li><br>
{% endfor %}
</ul>
</div>
{% endblock%}
Load the plugin: to load it we can do it like this
{% load humanize %}
.Use the plugin: to use it we can use it like this
{{forum.created_at | naturaltime}}
. Previously the format of forums.created_at wasY-m-d H: i: s
by using it right| naturaltime
. we convert it into an easy time to read and read like 1 hour ago, 1 minute ago, 3 days ago. we can see an example in the picture below:
Curriculum
- Class-based views
Tutorial Django - Class based view #2 : Use Class based view method and Get and Post method
- 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
Create a forum application using django #3: Base template, Login and Register system
Create a forum application using django #4: Admin dashboard ang setting redirect
Thank you for your contribution @duski.harahap.
After reviewing your contribution, we suggest you following points:
We suggest you add more comments in your comments. For readers with less experience programming, comments are very useful to fully understand their development.
Your tutorial is well structured and well explained. Thank you for your work in developing the contribution.
We are waiting for new features in your forum.
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!
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!