Skip to main content
ALPHA    This is new software undergoing tests! Thank you for your patience.

Candidate: henrytse henrytse Presented by: Conrad Ho conrad Assessed by: Tim Golden tjguk

Python (2023) ~ Grade 1 (Initial)

Forum with direct message function

When I am browsing the forum, I noticed that some user wished to communicate directly with others when they posted comments. However, many existing forums do not support this feature. It hinders the opportunity for many people to develop and preventing many individuals who could become friends from getting to know each other better. So, I would like to create a forum with direct message function.

Attached files
Filename (click to download) Size Uploaded by
Python_installation.png 142.2 KB henrytse
Markdown code
![Python_installation.png](/media/assessment/b5b36187/2023-03-22/15-58-17/Python_installation.png "Python_installation.png")
django_installed.png 25.1 KB henrytse
Markdown code
![django_installed.png](/media/assessment/b5b36187/2023-03-22/16-02-38/django_installed.png "django_installed.png")
Project_created.png 76.7 KB henrytse
Markdown code
![Project_created.png](/media/assessment/b5b36187/2023-03-22/16-04-58/Project_created.png "Project_created.png")
Trouble_in_finding_django_and_creating_virtual_e_BNjLzMm.png 29.7 KB henrytse
Markdown code
![...](/media/assessment/b5b36187/2023-03-22/16-16-07/Trouble_in_finding_django_and_creating_virtual_e_BNjLzMm.png "...")
Project_created.png 76.7 KB henrytse
Markdown code
![Project_created.png](/media/assessment/b5b36187/2023-03-27/13-31-18/Project_created.png "Project_created.png")
Function_index.png 67.5 KB henrytse
Markdown code
![Function_index.png](/media/assessment/b5b36187/2023-03-27/13-48-22/Function_index.png "Function_index.png")
functionindex.PNG 54.6 KB henrytse
Markdown code
![functionindex.PNG](/media/assessment/b5b36187/2023-03-27/13-49-58/functionindex.PNG "functionindex.PNG")
URL.PNG 75.7 KB henrytse
Markdown code
![URL.PNG](/media/assessment/b5b36187/2023-03-27/13-57-57/URL.PNG "URL.PNG")
welcome.PNG 46.3 KB henrytse
Markdown code
![welcome.PNG](/media/assessment/b5b36187/2023-03-27/14-00-31/welcome.PNG "welcome.PNG")
something_wrong_with_page_not_found.png 46.5 KB henrytse
Markdown code
![...](/media/assessment/b5b36187/2023-03-27/14-03-43/something_wrong_with_page_not_found.png "...")
Wrong_message.png 70.9 KB henrytse
Markdown code
![Wrong_message.png](/media/assessment/b5b36187/2023-03-27/14-05-00/Wrong_message.png "Wrong_message.png")
Picture1.png 83.4 KB henrytse
Markdown code
![Picture1.png](/media/assessment/b5b36187/2023-05-18/07-08-54/Picture1.png "Picture1.png")
Picture2.png 154.1 KB henrytse
Markdown code
![Picture2.png](/media/assessment/b5b36187/2023-05-18/07-11-38/Picture2.png "Picture2.png")
Picture1.png 83.4 KB henrytse
Markdown code
![Picture1.png](/media/assessment/b5b36187/2023-05-18/07-27-19/Picture1.png "Picture1.png")
Visual_Studio_Code_guildline.jpg 389.4 KB henrytse
Markdown code
![Visual_Studio_Code_guildline.jpg](/media/assessment/b5b36187/2023-05-23/07-10-15/Visual_Studio_Code_guildline.jpg "Visual_Studio_Code_guildline.jpg")
visual_code.PNG 172.3 KB henrytse
Markdown code
![visual_code.PNG](/media/assessment/b5b36187/2023-05-23/07-11-27/visual_code.PNG "visual_code.PNG")
intruction_3.PNG 33.3 KB henrytse
Markdown code
![intruction_3.PNG](/media/assessment/b5b36187/2023-05-23/07-18-39/intruction_3.PNG "intruction_3.PNG")
intruction_3.PNG 33.3 KB henrytse
Markdown code
![intruction_3.PNG](/media/assessment/b5b36187/2023-05-23/07-32-40/intruction_3.PNG "intruction_3.PNG")
how_to_add_shit.PNG 316.9 KB henrytse
Markdown code
![how_to_add_shit.PNG](/media/assessment/b5b36187/2023-05-23/07-37-08/how_to_add_shit.PNG "how_to_add_shit.PNG")
擷取1.PNG 145.6 KB henrytse
Markdown code
![擷取1.PNG](/media/assessment/b5b36187/2023-05-23/07-45-32/%E6%93%B7%E5%8F%961.PNG "擷取1.PNG")
擷取2.PNG 38.8 KB henrytse
Markdown code
![擷取2.PNG](/media/assessment/b5b36187/2023-05-23/07-46-30/%E6%93%B7%E5%8F%962.PNG "擷取2.PNG")
Django_view.png 131.1 KB henrytse
Markdown code
![Django_view.png](/media/assessment/b5b36187/2023-05-31/09-57-59/Django_view.png "Django_view.png")
WhatsApp_Image_2023-06-04_at_6.55.26_PM.jpeg 169.7 KB henrytse
Markdown code
![...](/media/assessment/b5b36187/2023-06-04/10-56-00/WhatsApp_Image_2023-06-04_at_6.55.26_PM.jpeg "...")
urls_typing.png 119.5 KB henrytse
Markdown code
![urls_typing.png](/media/assessment/b5b36187/2023-06-05/03-56-44/urls_typing.png "urls_typing.png")
web_urls.png 146.0 KB henrytse
Markdown code
![web_urls.png](/media/assessment/b5b36187/2023-06-05/04-27-46/web_urls.png "web_urls.png")
180.21324.JPG 12.1 KB henrytse
Markdown code
![180.21324.JPG](/media/assessment/b5b36187/2023-06-05/04-33-08/180.21324.JPG "180.21324.JPG")
Hello_user.JPG 49.4 KB henrytse
Markdown code
![Hello_user.JPG](/media/assessment/b5b36187/2023-06-05/04-36-50/Hello_user.JPG "Hello_user.JPG")
installed_app.png 168.6 KB henrytse
Markdown code
![installed_app.png](/media/assessment/b5b36187/2023-06-05/08-00-07/installed_app.png "installed_app.png")
template_forum.JPG 10.6 KB henrytse
Markdown code
![template_forum.JPG](/media/assessment/b5b36187/2023-06-05/08-06-52/template_forum.JPG "template_forum.JPG")
WhatsApp_Image_2023-06-19_at_11.31.25_PM.jpeg 4.2 KB henrytse
Markdown code
![...](/media/assessment/b5b36187/2023-06-19/15-31-45/WhatsApp_Image_2023-06-19_at_11.31.25_PM.jpeg "...")
WhatsApp_Image_2023-06-19_at_11.58.25_PM.jpeg 228.1 KB henrytse
Markdown code
![...](/media/assessment/b5b36187/2023-06-19/16-00-04/WhatsApp_Image_2023-06-19_at_11.58.25_PM.jpeg "...")
WhatsApp_Image_2023-06-20_at_12.02.56_AM.jpeg 30.0 KB henrytse
Markdown code
![...](/media/assessment/b5b36187/2023-06-28/05-38-38/WhatsApp_Image_2023-06-20_at_12.02.56_AM.jpeg "...")
WhatsApp_Image_2023-06-20_at_12.02.56_AM.jpeg 30.0 KB henrytse
Markdown code
![...](/media/assessment/b5b36187/2023-06-28/15-26-48/WhatsApp_Image_2023-06-20_at_12.02.56_AM.jpeg "...")
螢幕截圖_2023-06-29_上午12.00.09.png 418.3 KB henrytse
Markdown code
![螢幕截圖_2023-06-29_上午12.00.09.png](/media/assessment/b5b36187/2023-06-28/16-02-09/%E8%9E%A2%E5%B9%95%E6%88%AA%E5%9C%96_2023-06-29_%E4%B8%8A%E5%8D%8812.00.09.png "螢幕截圖_2023-06-29_上午12.00.09.png")
螢幕截圖_2023-06-29_下午8.45.23.png 386.5 KB henrytse
Markdown code
![螢幕截圖_2023-06-29_下午8.45.23.png](/media/assessment/b5b36187/2023-06-29/12-47-30/%E8%9E%A2%E5%B9%95%E6%88%AA%E5%9C%96_2023-06-29_%E4%B8%8B%E5%8D%888.45.23.png "螢幕截圖_2023-06-29_下午8.45.23.png")
Screen_cap_for_static.png 386.5 KB henrytse
Markdown code
![Screen_cap_for_static.png](/media/assessment/b5b36187/2023-06-29/12-48-12/Screen_cap_for_static.png "Screen_cap_for_static.png")
screen_shot_static_3.png 439.6 KB henrytse
Markdown code
![screen_shot_static_3.png](/media/assessment/b5b36187/2023-06-29/13-07-13/screen_shot_static_3.png "screen_shot_static_3.png")
Screen_shot_for_static_2.png 496.0 KB henrytse
Markdown code
![Screen_shot_for_static_2.png](/media/assessment/b5b36187/2023-06-29/13-07-44/Screen_shot_for_static_2.png "Screen_shot_for_static_2.png")
scree_shot_for_block.png 348.5 KB henrytse
Markdown code
![scree_shot_for_block.png](/media/assessment/b5b36187/2023-06-29/14-13-57/scree_shot_for_block.png "scree_shot_for_block.png")
Project_Home.png 225.0 KB henrytse
Markdown code
![Project_Home.png](/media/assessment/b5b36187/2023-06-30/16-19-46/Project_Home.png "Project_Home.png")
Log_out.png 205.1 KB henrytse
Markdown code
![Log_out.png](/media/assessment/b5b36187/2023-06-30/16-24-45/Log_out.png "Log_out.png")
successfully_logged_out.png 131.8 KB henrytse
Markdown code
![successfully_logged_out.png](/media/assessment/b5b36187/2023-06-30/16-26-37/successfully_logged_out.png "successfully_logged_out.png")
Register.png 131.9 KB henrytse
Markdown code
![Register.png](/media/assessment/b5b36187/2023-06-30/16-29-14/Register.png "Register.png")
Redirect_to_log_in.png 117.5 KB henrytse
Markdown code
![Redirect_to_log_in.png](/media/assessment/b5b36187/2023-06-30/16-31-31/Redirect_to_log_in.png "Redirect_to_log_in.png")
wrong_message.png 122.0 KB henrytse
Markdown code
![wrong_message.png](/media/assessment/b5b36187/2023-06-30/16-33-37/wrong_message.png "wrong_message.png")
螢幕截圖_2023-07-01_上午12.35.05.png 182.5 KB henrytse
Markdown code
![螢幕截圖_2023-07-01_上午12.35.05.png](/media/assessment/b5b36187/2023-06-30/16-37-02/%E8%9E%A2%E5%B9%95%E6%88%AA%E5%9C%96_2023-07-01_%E4%B8%8A%E5%8D%8812.35.05.png "螢幕截圖_2023-07-01_上午12.35.05.png")
Error.png 270.4 KB henrytse
Markdown code
![Error.png](/media/assessment/b5b36187/2023-06-30/16-37-45/Error.png "Error.png")
Add_post.png 233.6 KB henrytse
Markdown code
![Add_post.png](/media/assessment/b5b36187/2023-06-30/16-41-18/Add_post.png "Add_post.png")
post_is_added.png 250.9 KB henrytse
Markdown code
![post_is_added.png](/media/assessment/b5b36187/2023-06-30/16-45-21/post_is_added.png "post_is_added.png")
Reply.png 274.7 KB henrytse
Markdown code
![Reply.png](/media/assessment/b5b36187/2023-06-30/16-48-20/Reply.png "Reply.png")
Result.png 284.0 KB henrytse
Markdown code
![Result.png](/media/assessment/b5b36187/2023-06-30/16-49-29/Result.png "Result.png")
Stack_overflow.png 646.1 KB henrytse
Markdown code
![Stack_overflow.png](/media/assessment/b5b36187/2023-06-30/18-13-44/Stack_overflow.png "Stack_overflow.png")
螢幕截圖_2023-07-01_上午2.09.39.png 311.4 KB henrytse
Markdown code
![螢幕截圖_2023-07-01_上午2.09.39.png](/media/assessment/b5b36187/2023-06-30/18-13-53/%E8%9E%A2%E5%B9%95%E6%88%AA%E5%9C%96_2023-07-01_%E4%B8%8A%E5%8D%882.09.39.png "螢幕截圖_2023-07-01_上午2.09.39.png")
螢幕截圖_2023-07-01_上午2.11.36.png 366.2 KB henrytse
Markdown code
![螢幕截圖_2023-07-01_上午2.11.36.png](/media/assessment/b5b36187/2023-06-30/18-13-58/%E8%9E%A2%E5%B9%95%E6%88%AA%E5%9C%96_2023-07-01_%E4%B8%8A%E5%8D%882.11.36.png "螢幕截圖_2023-07-01_上午2.11.36.png")
螢幕截圖_2023-07-01_上午3.16.19.png 1.9 MB henrytse
Markdown code
![螢幕截圖_2023-07-01_上午3.16.19.png](/media/assessment/b5b36187/2023-06-30/19-16-41/%E8%9E%A2%E5%B9%95%E6%88%AA%E5%9C%96_2023-07-01_%E4%B8%8A%E5%8D%883.16.19.png "螢幕截圖_2023-07-01_上午3.16.19.png")

Status: Submitted for assessment.


henrytse henrytse ~ 19 Mar 2023 4:30 p.m.

How my idea come and how I imagine people would use my project.

I have noticed that people need forum or discussion boards to share their experience and feeling. When people encounter something good, saw an interesting movie or listened a nice music, they want to share or discuss with others. Forum is the place. I believe that discussion board give an opportunity to let people who are not related in life knowing each other because of their own interests, values or attitudes. However, since not much existing forum support direct message or mail box features, it has eliminated the possibility for users to become friend.

In my experience, friends around people may not have the same interests or the same enthusiasm for the interest. For example, someone is a football lover, however, friends around him not that into football but basketball or baseball player. In that case, he needs a platform to find someone who share the same hobby so that he can continue his interested and not feeling alone. I hope my forum or discussing board offer an opportunity for people to knowing someone who share the same interested.

I also noticed that people like to ask for suggestion of their situation. Some users post some of their painful experiences in discussion boards, such as the death of a relative, infidelity of a partner or experiencing break-up, etc. Some compassionate people hope to comfort users through their own experiences. But because only comment can be left, some of the more private or detailed details cannot be revealed. If there is a private message function, users can communicate with each other more privately about their experiences and insights.

To finish the project, I divide it into three main parts, and then each part will have several items that I will research and handle. First, I would like to design a forum with basic function including user registration, post publishment and topic selection.

Then I will improve the forum by adding different function, such as searching function, user block function, mail box.etc.

Finally, I would add instant message function.

Above are just some initial ideas, and I believe there are more details and specifics that need to be added and addressed.


henrytse henrytse ~ 19 Mar 2023 4:30 p.m.

Kick off! Since I only have a basic understanding of Python, and “user registration” seems to be a common and simple task. So, “user registration” would be my first task to be handled in this project. By learning how to write “user registration” code, I hope I could gain a better understand of Python for the coming tasks.

I have done some of the research, but I am also a bit lost. To make “user registration”, I need to 1) Importing Modules, 2) Setting up the Main Frame, 3)Creating the Database Connection, 4) Assigning Variables, 5)Designing the Layout, 6)Creating the Main Function, 7)Initializing the application. I don’t know which part I better should focus on first…

For me, I would like to focus on part 6)Creation the Main Function, because I think the function is the most important part. I will study the code and post it by Monday.


henrytse henrytse ~ 20 Mar 2023 2:03 a.m.

Where can I try my coding?

After research, I have more concrete ideas about the "user registration", however, I don't know where can I test my program...


henrytse henrytse ~ 21 Mar 2023 2:12 p.m. (updated: 19 Jun 2023 3 p.m.)

After a discussion with Jason, I realized I was going in the wrong direction and shouldn't have though that way. "user registration" is important, however, this is not the thing I need to worry about at the beginning, it goes against the concept of 'MVP'. User can not use my product with just "user registration" alone. So, to follow the concept of 'MVP'. I should create a forum with anonymous posts first.


henrytse henrytse ~ 21 Mar 2023 4:40 p.m.

To create a forum with anonymous posts, I need to choose a web framework for my forum.

I have done some research on Google, there are many web framework is available such as Django, Flask, Hug.etc.

As a beginner, to be honest, I can't really tell the different between them, but I would like to go for Django because it is widely use, high popularity means it is easier to find support and sample when I counter problems. Also, Django provides a range of in built libraries and database support which I feel is highly suitable for this project.


henrytse henrytse ~ 22 Mar 2023 4:19 p.m.

I installed Django, Pyhton and Visual Studio Code(texter) for my project. django_installed.png Python_installation.png

I also created the project in Visual Studio Code named "django_project"

Project_created.png

I only did this three things tonight because I have no idea how the framework works. I spent a long time to read the "Django installation guildline" and follow its step, but I messed up.

...

Finally, I need to go to Youtube to get a better understanding, and I installed it as shown above.

In addition, I feel like my progress is little bit slow, actually, I really want to work on the "forum home page" as soon as possible. Hopefully, I can give a coding draft in the next few days. However, the great news is the framework is ready!


henrytse henrytse ~ 27 Mar 2023 1:50 p.m.

After downloading the framework "Django", I try to start actual "Django" project which is the project I am working on (forum_with_message). I created a virtual environment (env) and create the project named "django_project", I dragged the file to the code editor so that I could start coding and modify the code. Project_created.png I also create an apps named "forum_with_message" and I tried to create a website (index.html) linking with my project. functionindex.PNG I defined a function named "index". When the function is called, it returns a rendered html template named "index.html" in the "forum_with_message" directory. The render function is a short cut to render a template with a HTML context.


henrytse henrytse ~ 27 Mar 2023 2:26 p.m.

I imports the "index" function from the "forum_with_message.views" modules, I also created URL"forum_with_message", "the index" function will be called when user visited to the URL "/forum_with_message" URL.PNG

In the module "index.html", I have a code "Print("Welcome to the forum with direct message!")

welcome.PNG

When the users visit to my web, they should see "Welcome to the forum with direct message!"

However, there is something wrong that my website can not be visited. Once I enter the URL, the website indicates 404 not found :( ...

I try very hard to figure out what is going on...I check with my code and wording carefully. Actually, I found I spell the message wrong. I typed "meesage" in my code. Wrong_message.png Then, I tried to visit again, it still does not working...

It seems I won't be able to display the code I've written if I don't fix the problem.

Therefore, I try to re-do the above procedure according to the procedure taught step by step online. However, it does not help :(


henrytse henrytse ~ 27 Mar 2023 2:33 p.m. (updated: 18 May 2023 7:19 a.m.)

To address the problem, I took several steps. First, I reviewed the procedure and ensured that I hadn't missed anything by following a video tutorial. I also carefully checked my typing for any potential mistakes.

Despite the efforts, the problem persisted. Then, I copied the message ”Page not found...The current path, didn't match any of these” and searched for solutions. Hopefully, I could get more insights and know how the problem come. Fortunately, I discovered that many people had encountered similar issues and were willing to share their insights and solutions.

I found a video on Youtube title "How to solve the 'Page Not Found' error(404) in Python Django", which directly relate to my problem. Picture2.png I followed his step and tutorial.

I 1. checked if the template exists and properly configured 2. checked if I have written the required view to render the template 3. checked my URLS if are configured correctly

Unfortunately, it didn't help.


henrytse henrytse ~ 18 May 2023 7:27 a.m.

Then, I found a post on STACK OVERFLOW written by an programmer who has similar problem.

STACK OVERFLOW is a very famous platform allow programmer to share their problem in coding and other experienced programmers will provide possible solution based on the problem.

Picture1.png

I read the post carefully and followed the advice, such as 1. changing the urlpatterns installed apps 2. replacing the static tag with the url tag 3. adding a trailing backlash to the url like path(‘admin\’, admin.site.urls)

However, the problem remains.


henrytse henrytse ~ 18 May 2023 7:29 a.m.

Feeling frustrated, I continued to search for answers on other websites. I came across a suggestion that my Django and Python configurations might be incorrect and that I needed to add my Python to the Path correctly. Additionally, I discovered that I could use Visual Code Editor instead of the command prompt to render the website.

To learn more about using Django with Visual Code Editor, I searched for "Django tutorial in Visual Code Editor" and found an official guide released by Visual Code Editor that provided step-by-step instructions on how to use Django as a beginner. The first step was to install and configure all necessary apps.

Overall, by taking a variety of steps and utilizing various resources, I was able to gain a better understanding of the problem and find a solution.


henrytse henrytse ~ 23 May 2023 7:31 a.m.

visual_code.PNG

This is the tutorial guild released by Visual Studio Code for beginner. The information is much comprehensive compared to other tutorials on YouTube or Websites. It introduces the basic functions of Django, giving me more insight into the framework. It also provides clear procedure for different function such as creating web project, web app, environment.etc. It also provides solution for potential problem that use may encounter. The confusion and frustration disappears.


henrytse henrytse ~ 23 May 2023 7:37 a.m.

I followed the instruction 3 and checked whether my Python interpreter is included in my PATH. I think this is the main reason why I cannot render website on Django.

intruction_3.PNG

Unfortunately, my path did not include Python interpreter.

To proceed, I need to add Python interpreter in my PATH. However, the guild do not have relative instruction.

I have no idea what Python interpreter is, so I googled “How to add python interpreter in path”.

A tutorial on YouTube came up.

how_to_add_shit.PNG


henrytse henrytse ~ 23 May 2023 7:48 a.m. (updated: 25 May 2023 9:10 a.m.)

I read and followed the procedure carefully. However, I encountered a problem. The owner of the video instructed me to click the "see more" button and then select “Show the hidden file”, but I couldn't find that button on my layout because my interface is different.

Below is the interface of the owner of video 擷取1.PNG

Below is the interface of mine 擷取2.PNG

So, I googled “How to show hidden file and drive”. There is another tutorial on YouTube for “show hidden file and drive”.

Then, I successfully add the Python interpreter in the path.


henrytse henrytse ~ 30 May 2023 2:48 p.m. (updated: 30 May 2023 2:48 p.m.)

Python and Django are installed and properly configured. I have verified that the Python interpreter and necessary extensions are available and up-to-date.

To start the project, I created a new folder named "django_project" on my system and set up a virtual environment within it by running the command py -3 -m venv .venv.

After creating the virtual environment, I activated it by running venv\scripts\activate

To ensure that I have the latest version of the "pip" package installer for Python

I ran the command python -m pip install --upgrade pip.

Next, I installed the Django framework by running python -m pip install django


henrytse henrytse ~ 30 May 2023 2:54 p.m.

With the necessary tools and environment in place, I created the Django project by running the command django-admin startproject web_message_project. It created a new folder named "web_message_project" and generated several files, including "manage.py", "init.py", "settings.py", and "urls.py".etc

-The "settings.py" file contains the configuration settings for the Django project, while the "urls.py" file serves as a table of contents for the project.

To create an empty development database, I ran the command manage.py migrate and finally, I started the server by running manage.py runserver, which runs on the default port 8000.


henrytse henrytse ~ 31 May 2023 10:49 a.m. (updated: 05 Jun 2023 3:48 a.m.)

Create A Django app

Then, I created a django named "Forum" by typing python manage.py startapp forum, it created a folder called forum that contains a number of code files and a subfolder such as view.py, models.py, apps.py.etc.

Afterward, I put the following code in the views.py which is one of the code files created with "forum" folder.

from django.http import HttpResponse

def home(request):
    return HttpResponse("Hello, user!")

from django.http import HttpResponse it imports the HttpResponse class from the django.http module

def home(request): it defined a function named home and take a "request" argument which belongs to HttpResponse class.

return HttpResponse("Hello, user!") when the request is called, the string "Hello, user!" will be returned to the user as a feedback.

When a user sends a request to the application, this view function will be called and generate a response which is "Hello, user!"

...


henrytse henrytse ~ 04 Jun 2023 11:03 a.m. (updated: 05 Jun 2023 4:03 a.m.)

Then, I created a file named urls.py in the forum dietary.

urls.py file is used to define the URL patterns for the application and maps URL pattern to corresponding view functions for generating HTTP response.

I put the following code to the forum/urls.py

from django.urls import path
from forum import views

urlpatterns = [
    path("", views.home, name="home"),
]

from django.urls import path It imports the path from Django's urls module.

from forum import views It imports the views module from the forum application, which, in my case, is the home function I defined previously in view.py.

python urlpatterns = [ path("", views.home, name="home"), Then, I defined a list of URL patterns to map the root URL of the application to a view function called "home". The URL pattern is empty string "". When the URL pattern is matched, the function "home" will be called in the forum view.py module. I also named this URL pattern as "home".

Therefore, when user visits the root URL (empty string) of the application, Django will call the home function to generate an HTTP response.

urls_typing.png


henrytse henrytse ~ 05 Jun 2023 4:25 a.m. (updated: 05 Jun 2023 4:28 a.m.)

Next, I put the following code in the urls.py file in the web_message_project.

from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path("", include("hello.urls")),
    path('admin/', admin.site.urls)
]

The urls.py file in the web_meesage_project is the file where django actually handle the URL routing. web_urls.png

from django.contrib import admin It imports the admin module from django.contrib. The functionality for the Django admin will be provided after import.

from django.urls import include, path It imports the path and include module from django.urls. It defines and includes URL patterns.

path("", include("forum.urls")), it maps the root URL path to the forum.urls module. path('admin/', admin.site.urls) it maps the URL path (admin) to the built-in Django admin site.

In summary, it sets up the root URL path to route to the forum app.


henrytse henrytse ~ 05 Jun 2023 4:33 a.m. (updated: 05 Jun 2023 6:48 a.m.)

I typed python manage.py runserver to run the server again, and visited http://127.0.0.1:8000/

180.21324.JPG

Finally...I successfully render the website with text message!!!!

Hello_user.JPG

I solved the problem!


henrytse henrytse ~ 05 Jun 2023 7:30 a.m. (updated: 19 Jun 2023 3:11 p.m.)

Although I was able to render a website with the content message "Hello, user!", it is slightly different from the problem I encountered because I was unable to render a website using templates. The method used above generates HTML directly in the code.

In addition, we avoid generate HTML directly in code because it opens the app to cross-site scripting(XSS) attacks. Since the content is given directly to a broswer. This opening allows an attacker to place malicious HTML, including JavaScript code.

Therefore, normally, we render a website using templates as templates keep HTML out of the code entirely.

I am confident I can render a website using templates as all the configurations are in place. What I need to do is to ensure other steps are executed correctly.


henrytse henrytse ~ 05 Jun 2023 8 a.m. (updated: 19 Jun 2023 3:12 p.m.)

First, in the web_message_project, I added the 'forum' app to the "INSTALLED_APP" setting to ensure the project recognizes the app and is able to handle templating.

installed_app.png


henrytse henrytse ~ 05 Jun 2023 8:06 a.m. (updated: 05 Jun 2023 9:19 a.m.)

Inside the forum folder, I created a folder named "templates" and another subfolder named "forum" to match the app name.

I also created a file named hello_there.html in the "templates/forum"

template_forum.JPG


henrytse henrytse ~ 19 Jun 2023 3:24 p.m. (updated: 19 Jun 2023 3:39 p.m.)

I put the following code in template/hello_there.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>Hello, CodeGrades</title>
    </head`>
    <body>
        <strong>Hello there, {{ name }}!</strong> It's {{ date | date:"l, d F, Y" }} at {{ date | time:"H:i:s" }}
    </body>
</html>

<!DOCTYPE html>This is an instruction to the web browser about what version of HTML the page is written in. It must be included in the first line of code for every HTML

<title>Hello, Codegrades</title> It defines the title of the document and it is shown in the browser;s title bar, like the following below.

...

<body> <strong>Hello there, {{ name }}!</strong> It's {{ date | date:"l, d F, Y" }} at {{ date | time:"H:i:s" }} </body>

The body defines the document's body. "Hello there" will be bold because of <strong>

{{ name }}, {{ date | date:"l, d F, Y" }}, {{ date | time:"H:i:s" }} are the variables will be passed to this template.


henrytse henrytse ~ 19 Jun 2023 3:42 p.m. (updated: 28 Jun 2023 5:35 a.m.)

Then, I put the following code in the view.py in the forum.

from django.shortcuts import render
def hello_there(request, name):
    return render(
        request,
        'forum/hello_there.html',
        {
            'name': name,
            'date': datetime.now()
        }
    )

from django.shortcuts import render It imports the render function from django.shortcuts modue. The render function is a shortcut function that generates an HTTP response by rendering an HTML template.

def hello_there(request, name): It defines a function named hello_there which takes two parameter, request and name. The second parameter represent a request sent by the client, it will then return a statement as response. Name is another parameter.

python return render( request, 'forum/hello_there.html', { 'name': name, 'date': datetime.now(

It will return a statement as HTTP response object. This code will request hellothere.html under the forum to get two parameter which is name and date in this case. The value of name and date will be return as response. datetime.now() is a method to obtain the date in python.

Overall, when this function is called, the webpage will display a message with current date and time.


henrytse henrytse ~ 19 Jun 2023 4 p.m.

After that, I put the code path("forum/<name>", views.hello_there, name="hello_there"), inside urlpatterns in the urls.py/forum like the below graph.

...


henrytse henrytse ~ 28 Jun 2023 5:38 a.m. (updated: 28 Jun 2023 2:08 p.m.)

I typed 127.0.0.1:8000/forum/CodeGrades in the Google and you can see the result as below.

...

Finally!!!! A template is rendered successfully! It feels good to solve the problem!

As you see, the website displays "hello_there, CodeGrads! It's Tuesday, 20 June, 2023 at 00:02:30." It shows the current date and time in the website and if you reload, the date and time will also be updated.

In this case, words "CodeGrads" can be any world you type after 127.0.0.1:8000/forum/ because the path name I defined in the "Urlpatterns" is forum/<name> and the variable is defined in the view.py, the value will be returned when the function is called. So whatever you insert after forum, it displays.

In this case, I type Codegrads so it displays hello there, CodeGrades.


henrytse henrytse ~ 28 Jun 2023 3:39 p.m.

Back to the project.

If you notice, you may find that the color of the sentence, "Hello, there CodeGrades" is red.

...

Before I establish a forum, I try to do the formating by serving static files. Static files will not change the application when the program is running. It will deliver static content, such as CSS, Javascript and images or other files to make the interface of the web application looks great.


henrytse henrytse ~ 28 Jun 2023 3:52 p.m. (updated: 29 Jun 2023 12:49 p.m.)

In the forum folder, I created a folder named "static" and subfolder "forum" within the "static" folder to match the app name. The reason for this extra subfolder, After that, I created a file named site.css. Then, I put the following code in this file.

.message {
    font-weight: 600;
    color: red;
}

The above code defines a CSS rule that set the font weight to 600 and bold as well as the color to red.

螢幕截圖_2023-06-29_上午12.00.09.png


henrytse henrytse ~ 29 Jun 2023 12:48 p.m. (updated: 29 Jun 2023 12:49 p.m.)

In the templates/forum/hello_there.html.

I put the following code after the <title> element.

{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'forum/site.css' %}" />

Screen_cap_for_static.png

{% load static %} is a tag to load the static files in the current application.

href="{% static 'forum/site.css' %} it specifies the location of the static file

type="text/css" it specfies the type of style sheet.


henrytse henrytse ~ 29 Jun 2023 1:07 p.m.

In addition, I added the following Import statement in urls.py in my web_message project, including

from django.contrib.staticfiles.urls
import staticfiles_urlpatterns

It allows me to generate URL patterns for serving static files and using the staticfiles_urlpatterns function.

I also added this code urlpatterns += staticfiles_urlpatterns(), it will automatically generate URL patterns and service static files for me during development.

screen_shot_static_3.png


henrytse henrytse ~ 29 Jun 2023 1:20 p.m.

I modified ALLOWED_HOSTS = [ ' * ' ] and set DEBUG = False

Screen_shot_for_static_2.png

Unfortunately, I failed to serve the static file when I first tried. I gained message "404 207" in my terminal.

I double-checked my typing and redid the entire procedure by following the guidelines, but I still failed. I was disappointed and frustrated. Then, I searched for possible causes and solutions on Google, but found that there wasn't much discussion on the topic.

I focused on finding a solution on Stack Overflow, and luckily, I found a user who had the exact same problem as me. He suggested changing the DEBUG setting to True. I followed his advice and... it worked! You can see the results above.


henrytse henrytse ~ 29 Jun 2023 2:12 p.m. (updated: 29 Jun 2023 2:12 p.m.)

Before I establish a forum, I'm learning additional skills to make creating multiple web applications more efficient. One such skill is using the snippet. First, I need to create a base template with block tags, such as {% block title %}{% endblock %}, as demonstrated in the following program."

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <title>{% block title %}{% endblock %}</title>
    {% load static %}
    <link rel="stylesheet" type="text/css" href="{% static 'forum/site.css' %}"/>
</head>

<body>
<div class="navbar">
    <a href="{% url 'home' %}" class="navbar-brand">Home</a>
    <a href="{% url 'about' %}" class="navbar-item">About</a>
    <a href="{% url 'contact' %}" class="navbar-item">Contact</a>
</div>

<div class="body-content">
    {% block content %}
    {% endblock %}
    <hr/>
    <footer>
        <p>&copy; 2023</p>
    </footer>
</div>
</body>
</html>

henrytse henrytse ~ 29 Jun 2023 2:17 p.m.

Then, we need to type {% extends "forum/layout.html" %} informing the current templates that a block tag is using.

Once the base template is created with block tags, the next step is to add content between the tags. This synchronized format for templates not only ensures consistency, but also saves time for creating multiple templates.

scree_shot_for_block.png


henrytse henrytse ~ 29 Jun 2023 2:17 p.m.

Then, we need to type {% extends "forum/layout.html" %} informing the current templates that a block tag is using.

Once the base template is created with block tags, the next step is to add content between the tags. This synchronized format for templates not only ensures consistency, but also saves time for creating multiple templates.

scree_shot_for_block.png


henrytse henrytse ~ 29 Jun 2023 4:44 p.m.

Now, everything is ready and I am good to back to my project which is building a forum with instant message function. I searched tutorial on build a forum and I found a open source code with tutorial on building a forum with Python and django. The guild line is clear and the CSS file also did great. So, I follow the tutorial and start building the forum first.

The tutorial is in the link.

https://projectgurukul.org/python-django-online-discussion-forum/


henrytse henrytse ~ 30 Jun 2023 6:03 a.m.

First, I create a template base.html which contain the basic design that applied in other templates. It uses bootstrap to do the styling. Bootstrap is a CSS framework for the responsive website. A navigation bar is used in this project and there are four places that user can navigate to including Profile, Login, Register and Home.

below is the code I add.

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">

    <title>{% block title %} {% endblock %}</title>
      <style>
          {% block css %} {% endblock %}
    </style>
  </head>
  <body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top">
  <a class="navbar-brand" href="/">Discussion Forum</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>

  <div class="collapse navbar-collapse" id="navbarSupportedContent">
    <ul class="navbar-nav mr-auto">
      <li class="nav-item {% block homeactive %} {% endblock homeactive %} ">
        <a class="nav-link" href="/">Home <span class="sr-only"></span></a>
      </li>
      {% if user.is_authenticated %}
<ul class="navbar-nav mr-2">
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href='#' id="navbarDropdown" role="button" data-toggle="dropdown"> Welcome {{request.user}}</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
          <a class="dropdown-item" href="/logout">Logout</a>

      <li class="nav-item {% block profileactive %} {% endblock profileactive %}">
        <a class="nav-link" href="/myprofile">Profile</a>
      </li>

        </div>
      </li>      
{% else %}
      <li class="nav-item {% block registeractive %} {% endblock registeractive %}">
        <a class="nav-link" href="/register">Register</a>
      </li>
      <li class="nav-item {% block loginactive %} {% endblock loginactive %}">
        <a class="nav-link" href="/login">Login</a>
      </li>
      {% endif %}

    </ul>
  </div>
</nav>
<br>
</body>
{% block body %} {% endblock %}

<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script>
  {% block js %} {% endblock %}
</html>

henrytse henrytse ~ 30 Jun 2023 6:16 a.m. (updated: 30 Jun 2023 10:48 a.m.)

Then, I add the following code in the forum/models.py

from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.utils.timezone import now


class Profile(models.Model):
    user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE)    
    image = models.ImageField(upload_to="images",default="default/user.png")

class Post(models.Model):
    user1 = models.ForeignKey(User, on_delete=models.CASCADE, default=1)
    post_id = models.AutoField
    post_content = models.CharField(max_length=5000)
    timestamp= models.DateTimeField(default=now)
    image = models.ImageField(upload_to="images",default="")

class Replie(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, default=1)
    reply_id = models.AutoField
    reply_content = models.CharField(max_length=5000) 
    post = models.ForeignKey(Post, on_delete=models.CASCADE, default='')
    timestamp= models.DateTimeField(default=now)
    image = models.ImageField(upload_to="images",default="")

from django.db import models It imports the Django built-in model

from django.contrib.auth.models import User It imports the built-in Django user model

from django.utils.timezone import now It is also a built-in Django function which provides the current date and time as well as the time zone.

I divided three classes including profile, post and repiles. These three models are taken from django built in function.

Profiles model stored user information like user name, profile picture.etc

Concerning the class post

user1 = models.ForeignKey(User, on_delete=models.CASCADE, default=1) It links post model to the user's model

post_id = models.AutoField User's ID will be identified when user comments or add posts.

post_content = models.CharField(max_length=5000) Maximum character length for each post is 5000.

timestamp= models.DateTimeField(default=now) It stores the date and time when the post was created

image = models.ImageField(upload_to="images",default="") It will store the image or image were uploaded

Concerning the class Replies

The usage is similar to the Class_post except the model will be activated in the scenario of replies.


henrytse henrytse ~ 30 Jun 2023 10:56 a.m. (updated: 30 Jun 2023 2:47 p.m.)

Second, I created registration page named register.html with the below code.

{% extends "forum/basic.html" %}

{% block title %} Register {% endblock %}
{% block registeractive %} active {% endblock registeractive %}
{% block css %}
@import url(https://fonts.googleapis.com/css?family=Roboto:400,300,500);
*:focus {
  outline: none;
}

body {
  margin: 0;
  padding: 0;
  background: #DDD;
  font-size: 16px;
  color: #222;
  font-family: 'Roboto', sans-serif;
  font-weight: 300;
}

#login-box {
  position: relative;
  margin: 5% auto;
  width: 700px;
  height: 500px;
  background: #FFF;
  border-radius: 2px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.4);
}

.items {
  position: absolute;
  top: 0;
  left: 0;
  box-sizing: border-box;
  padding: 40px;
  width: 700px;
  height: 500px;
}

h1 {
  margin: 0 0 20px 0;
  font-weight: bold;
  font-size: 28px;
  text-align: center;
}

input[type="text"],
input[type="email"],
input[type="password"] {
  display: block;
  box-sizing: border-box;
  margin-bottom: 20px;
  padding: 4px;
  width: 600px;
  height: 32px;
  border: none;
  border-bottom: 1px solid #AAA;
  font-family: 'Roboto', sans-serif;
  font-weight: 400;
  font-size: 15px;
  transition: 0.2s ease;
}

input[type="text"]:focus,
input[type="email"]:focus,
input[type="password"]:focus {
  border-bottom: 2px solid #16a085;
  color: #16a085;
  transition: 0.2s ease;
}

input[type="submit"] {
  margin-top: 28px;
  width: 120px;
  height: 32px;
  background: #16a085;
  border: none;
  border-radius: 2px;
  color: #FFF;
  font-family: 'Roboto', sans-serif;
  font-weight: 500;
  text-transform: uppercase;
  transition: 0.1s ease;
  cursor: pointer;
  position: relative;
  left: 250px;
}

input[type="submit"]:hover,
input[type="submit"]:focus {
  opacity: 0.8;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.4);
  transition: 0.1s ease;
}

input[type="submit"]:active {
  opacity: 1;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.4);
  transition: 0.1s ease;
}
{% endblock %}
{% block body %} 
<br>
{% for message in messages  %}            
<div class="alert alert-{{ message.tags }} alert-dismissible fade show" role="alert">
      <strong>Message : </strong> {{ message }}
      <button type="button" class="close" data-dismiss="alert" aria-label="Close">
        <span aria-hidden="true">&times;</span>
      </button>
    </div>
{% endfor %}  
<div id="login-box">
    <div class="items">
      <h1>Register</h1>
        <form action="/register/" method="post"> {% csrf_token %}

      <input type="text" name="username" placeholder="Username" />
      <input type="email" name="email" placeholder="E-mail" />
      <input type="text" name="first_name" placeholder="First Name" />
      <input type="text" name="last_name" placeholder="Last Name" />
      <input type="password" name="password" placeholder="Password" />
      <input type="password" name="confirm_password" placeholder="Confirm your password" />

      <input type="submit" name="signup_submit" value="Register" />
    </div>   
  </div>

  {% endblock %}

henrytse henrytse ~ 30 Jun 2023 2:08 p.m. (updated: 30 Jun 2023 5:50 p.m.)

Third, I add the following code in the forum/view.py.

    def UserRegister(request):
      if request.method=="POST":   
        username = request.POST['username']
        email = request.POST['email']
        first_name=request.POST['first_name']
        last_name=request.POST['last_name']
        password = request.POST['password']
        confirm_password = request.POST['confirm_password']
        user = User.objects.create_user(username, email, password)
        user.first_name = first_name
        user.last_name = last_name
        user.save()
        return render(request, 'login.html')        
    return render(request, "forum/register.html")

This is the function named UserRegister. When the function is called, it will request the variable including user name, email, first name, last name and password. The variable correspond to the data inputted by the user in the register.html, then are saved in Django user model.


henrytse henrytse ~ 30 Jun 2023 2:26 p.m. (updated: 30 Jun 2023 3:16 p.m.)

I also created user log in page(login.html) with following code.

{% endblock %}
{% block body %} 
<br>
{% for message in messages  %}            
<div class="alert alert-{{ message.tags }} alert-dismissible fade show" role="alert">
      <strong>Message : </strong> {{ message }}
      <button type="button" class="close" data-dismiss="alert" aria-label="Close">
        <span aria-hidden="true">&times;</span>
      </button>
    </div>
{% endfor %}   
<div id="login-box">
    <div class="items">
      <h1>Log In</h1>
              <form action="/login/" method="post"> {% csrf_token %}
      <input type="text" name="username" placeholder="Username" />
      <input type="password" name="password" placeholder="Password" />      
      <input type="submit" name="signup_submit" value="Log In" />
    </div>   
  </div>
  {% endblock %}

henrytse henrytse ~ 30 Jun 2023 2:30 p.m. (updated: 30 Jun 2023 3:16 p.m.)

In addition, I add the following code in the forum/view.py

  def UserLogin(request):
    if request.method=="POST":
        username = request.POST['username']
        password = request.POST['password']

        user = authenticate(username=username, password=password)

        if user is not None:
            login(request, user)
            messages.success(request, "Successfully Logged In")
            return redirect("/myprofile")
        else:
            messages.error(request, "Invalid Credentials")
        alert = True
        return render(request, 'login.html', {'alert':alert})            
    return render(request, "forum/login.html")

The code is similar to the registration code but this function is used for log in. The variable "user name" and "password" will be requested when the function is called. When "user name" and "password" match the data stored in Database of Django, it will first send back a message "successfully logged in", then, return a function redirect("/myprofile") which means user will be redirected to the profile page.

If the data does not match, the user will be redirected to log in page with error message.


henrytse henrytse ~ 30 Jun 2023 2:51 p.m. (updated: 30 Jun 2023 2:56 p.m.)

After that, I created profile page name profile.html and add the below code.

<br>
{% for message in messages %}
<div class="alert alert-{{ message.tags }} alert-dismissible fade show" role="alert">
    <strong>Message : </strong> {{ message }}
    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
        <span aria-hidden="true">&times;</span>
    </button>
</div>
{% endfor %}
<div class="container">
    <div class="row">
        <div class="col-lg-12 col-lg-offset-0">

            <div class="row pad">
                <div class="col-lg-12">
                    <div class="panel panel-primary">
                        <div class="card-body">
                            <ul class="list-group">
                                <li class="list-group-item">
                                    Username: <strong class="float-right">{{request.user}}</strong>
                                </li>
                                <li class="list-group-item">
                                    Full Name: <strong class="float-right">{{request.user.get_full_name}}</strong>
                                </li>
                                <li class="list-group-item">
                                    Email: <strong class="float-right">{{request.user.email}}</strong>
                                </li>
                                <li class="list-group-item">
                                    <form action="/myprofile/" enctype="multipart/form-data" method="POST">{% csrf_token %} 
                                        {{ form.as_p }}
                                        <button type="submit">Upload</button>
                                        Profile Photo: <strong class="float-right"> <img
                                                src="{{request.user.profile.image.url}}" class="rounded-circle" alt=""
                                                width="150px" height="150px"></strong>
                                </li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
</div>
{% endblock %}

User's personal information will be displayed here. Although the code seems lengthy but most of it is related to styling. I did not serve static file but using inline styling. If multiple templates are used, inline styling are not recommanded. However, in my case, I believe using inline styling is the better option.


henrytse henrytse ~ 30 Jun 2023 2:58 p.m. (updated: 30 Jun 2023 3 p.m.)

In the forum/view.py, I add the following code.

def myprofile(request):
    if request.method=="POST":
        user = request.user
        profile = Profile(user=user)
        profile.save()
        form = ProfileForm(data=request.POST, files=request.FILES)
        if form.is_valid():
            form.save()
            obj = form.instance
            return render(request, "forum/profile.html",{'obj':obj})
    else:
        form=ProfileForm()
    return render(request, "forum/profile.html", {'form':form})

When the function is called, this function will request the data from the database and display in the template. User could also add a profile photo if the user wants.


henrytse henrytse ~ 30 Jun 2023 3:04 p.m. (updated: 30 Jun 2023 3:10 p.m.)

Next, I created a template for the forum which also the home page. User can add post or leave a comment here.

The code is as below:

{% block body %} 
<br>
<div class="container-fluid mt-5">
    <div class="row">
        <div class="col-md-12">
            <div class="card mb-4">
                <div class="card-header">
                    <div class="media flex-wrap w-100 align-items-center"> <img src="/media/{{post.image}}"
                            class="d-block ui-w-40 rounded-circle" alt="" width="40px" height="40px">
                        <div class="media-body ml-3" style="text-transform: uppercase;"> <a data-abc="true">{{post.user1}}</a>
                        </div>
                        <div class="text-muted small ml-3">
                            <div>Date and Time Of Post :</div>
                            <div><strong>{{post.timestamp}}</strong></div>
                        </div>
                    </div>
                </div>         
                <div class="card-body">
                    <p>{{post.post_content}}</p>
                </div>
                <div class="card-footer d-flex flex-wrap justify-content-between align-items-center px-0 pt-0 pb-3">

                    <div class="px-4 pt-3"> <button type="button" class="btn btn-primary" data-target="#reply" data-toggle="modal"><i
                                class="ion ion-md-create"></i>&nbsp; Reply</button> </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% for reply in replies %}
<br>
<div class="container">
<div class="media">
    <img class="mr-3 rounded-circle" src="/media/{{reply.image}}" alt="." width="30px" height="30px">
    <div class="media-body">
      <h4 class="mt-0">{{reply.user}}   &nbsp;  &nbsp;  &nbsp;  &nbsp;  &nbsp;  &nbsp;  <span><small style="font-size: 13px;">({{reply.timestamp}})</small></span></h4>   
      <h5>{{reply.reply_content}}</h5>
    </div>
  </div>
</div>
{% endfor %}
<!-- Modal -->
<div class="modal fade" id="reply" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        {% if user.is_authenticated %}
        <div class="modal-body">
          <form action="/discussion/{{post.id}}/" method="POST"> {% csrf_token %}
            <div class="form-group">
              <label for="exampleFormControlTextarea1">Post Your Solution Here</label>
              <input type="hidden" name="post_id" value="{{post.id}}">
              <textarea class="form-control" id="desc" name="desc" rows="3"></textarea>
            </div>
          </div>
          {% else %}
          <h3>Please Login first to post a reply</h3>
          {% endif %}
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
          <button type="submit" class="btn btn-primary">Post Solution</button>
        </div>
      </div>
    </div>
  </div>
{% endblock %}
{% block js %}
<script>
 {% if alert %}
alert('Your Reply has been posted successfully!!');
document.location = "/"
{% endif %}
</script>
{% endblock %}

User can click the button to add post. A modal will be opened, use can write content and click "post" button to publish his post. Once the post is added, a message "Yours question has been post successfully".


henrytse henrytse ~ 30 Jun 2023 3:06 p.m. (updated: 30 Jun 2023 6:03 p.m.)

I put the following code in the forum/views.py

def discussionforum(request):
    profile = Profile.objects.all()
    if request.method=="POST":   
        user = request.user
        image = request.user.profile.image
        content = request.POST.get('content','')
        post = Post(user1=user, post_content=content, image=image)
        post.save()
        alert = True
        return render(request, "forum/discussionforum.html", {'alert':alert})
    posts = Post.objects.filter().order_by('-timestamp')
    return render(request, "forum/discussionforum.html", {'posts':posts})

It saves all the data from Post database and the post variable can be used from the post database to the web. In addition, the date and time of the post creating will be displayed. User name and user ID will also be displayed.


henrytse henrytse ~ 30 Jun 2023 3:14 p.m. (updated: 30 Jun 2023 5:51 p.m.)

Last, I created the reply page named discussion.html

{% block body %} 
<br>
<div class="container-fluid mt-5">
    <div class="row">
        <div class="col-md-12">
            <div class="card mb-4">
                <div class="card-header">
                    <div class="media flex-wrap w-100 align-items-center"> <img src="/media/{{post.image}}"
                            class="d-block ui-w-40 rounded-circle" alt="" width="40px" height="40px">
                        <div class="media-body ml-3" style="text-transform: uppercase;"> <a data-abc="true">{{post.user1}}</a>
                        </div>
                        <div class="text-muted small ml-3">
                            <div>Date and Time Of Post :</div>
                            <div><strong>{{post.timestamp}}</strong></div>
                        </div>
                    </div>
                </div>         
                <div class="card-body">
                    <p>{{post.post_content}}</p>
                </div>
                <div class="card-footer d-flex flex-wrap justify-content-between align-items-center px-0 pt-0 pb-3">

                    <div class="px-4 pt-3"> <button type="button" class="btn btn-primary" data-target="#reply" data-toggle="modal"><i
                                class="ion ion-md-create"></i>&nbsp; Reply</button> </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% for reply in replies %}
<br>
<div class="container">
<div class="media">
    <img class="mr-3 rounded-circle" src="/media/{{reply.image}}" alt="." width="30px" height="30px">
    <div class="media-body">
      <h4 class="mt-0">{{reply.user}}   &nbsp;  &nbsp;  &nbsp;  &nbsp;  &nbsp;  &nbsp;  <span><small style="font-size: 13px;">({{reply.timestamp}})</small></span></h4>   
      <h5>{{reply.reply_content}}</h5>
    </div>
  </div>
</div>
{% endfor %}
<!-- Modal -->
<div class="modal fade" id="reply" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        {% if user.is_authenticated %}
        <div class="modal-body">
          <form action="/discussion/{{post.id}}/" method="POST"> {% csrf_token %}
            <div class="form-group">
              <label for="exampleFormControlTextarea1">Post Your Solution Here</label>
              <input type="hidden" name="post_id" value="{{post.id}}">
              <textarea class="form-control" id="desc" name="desc" rows="3"></textarea>
            </div>
          </div>
          {% else %}
          <h3>Please Login first to post a reply</h3>
          {% endif %}
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
          <button type="submit" class="btn btn-primary">Post Solution</button>
        </div>
      </div>
    </div>
  </div>
{% endblock %}
{% block js %}
<script>
 {% if alert %}
alert('Your Reply has been posted successfully!!');
document.location = "/"
{% endif %}
</script>
{% endblock %}

henrytse henrytse ~ 30 Jun 2023 3:15 p.m. (updated: 30 Jun 2023 5:58 p.m.)

In the forum/views.py I add the following code.

def discussion(request, myid):
    post = Post.objects.filter(id=myid).first()
    replies = Replie.objects.filter(post=post)
    if request.method=="POST":
        user = request.user
        image = request.user.profile.image
        desc = request.POST.get('desc','')
        post_id =request.POST.get('post_id','')
        reply = Replie(user = user, reply_content = desc, post=post, image=image)
        reply.save()
        alert = True
        return render(request, "forum/discussion.html", {'alert':alert})
    return render(request, "forum/discussion.html", {'post':post, 'replies':replies})

If this function is activated, this function will request use's information including user ID.etc. If user click a "add post" button on the particular post, it will allow user to reply corresponding post. After user click on "reply" button, the inputted content will be saved and return, the model of django will store the changed data, user also will be redirected to the discussion page.


henrytse henrytse ~ 30 Jun 2023 4:19 p.m. (updated: 30 Jun 2023 4:21 p.m.)

here is the result

Project_Home.png

You can see a navigation bar, a welcome message and a "add post" button. You can also see that I had logged it with user name Henrytse.


henrytse henrytse ~ 30 Jun 2023 4:26 p.m.

When I move my cursor to my name, a "log out option" is popped down. I can log out

Log_out.png

When I successfully logged out, I will return to the log in page with message "successfully logged out"

successfully_logged_out.png


henrytse henrytse ~ 30 Jun 2023 4:29 p.m.

I can register account by clicking register

Register.png


henrytse henrytse ~ 30 Jun 2023 4:31 p.m.

I will be redirected to the log in page, what I need to do is enter my user name and password to log in.

Redirect_to_log_in.png


henrytse henrytse ~ 30 Jun 2023 4:33 p.m. (updated: 30 Jun 2023 4:34 p.m.)

If the password or user name is not correct, I will be redirected to the log in page with the message invalid credentials

wrong_message.png


henrytse henrytse ~ 30 Jun 2023 4:37 p.m.

If my user name and password is correct, I will be redirected to the profile page with message: " successfully log in", I can also try to upload my profile picture here.

螢幕截圖_2023-07-01_上午12.35.05.png


henrytse henrytse ~ 30 Jun 2023 4:38 p.m. (updated: 30 Jun 2023 6:22 p.m.)

When I click the "upload button", the error message is popped out.

Error.png

To solve the problem, I search "Integrity Error" on Google. I think it is necessary to know the cause of problem, so that we will have clear direction for the solution.

Stack Overflow, Django indicates that many people had encountered this problem. I think we will come up some possible solution by studying their case carefully. It seems some setting or some value is missing so that I can not render the template. I would like to solve this problem, but this problem is not that important at this moment, so, I will finish updating all my content first, I will come back to solve the problem when I have time.

Stack_overflow.png

螢幕截圖_2023-07-01_上午2.09.39.png

螢幕截圖_2023-07-01_上午2.11.36.png


henrytse henrytse ~ 30 Jun 2023 4:43 p.m.

When I click the "add" button, a box model is displayed, I can write some messages here.

Add_post.png


henrytse henrytse ~ 30 Jun 2023 4:45 p.m.

When the post is added, you can see a new new post will be displayed with time and dated as well as the user information.

post_is_added.png


henrytse henrytse ~ 30 Jun 2023 4:48 p.m.

You can also click "add post" to reply.

Reply.png


henrytse henrytse ~ 30 Jun 2023 4:49 p.m.

And the result is as below.

Result.png


henrytse henrytse ~ 30 Jun 2023 7:11 p.m.

As the program is near end, I would like to share some of my feeling.

It took me a long time to solve the problem which I did not expect, but I'm thrilled and proud that I was able to do it. I remembered I was so frustrated and upset because I did not get the same result when I strictly follow the steps of tutorial on Youtube. I have no idea what I need to do.

When I started working on the project, I was very new to coding and programming, although I had some basic knowledge of Python and JavaScript, such as how to use strings, variables, control structures, data structures, and functions, including for loops, if-clauses, operators and Boolean logic. However, I had no idea how to make my code work or where to write it, and I also didn't understand how the Python and Django framework worked.

I thought that by downloading Python, I would be able to write code on the Python program. I knew that I needed to use Django, but I had no idea how to use it. I thought that by downloading Django and running it, it would automatically work.

During the project, I gradually learned some concepts by searching solution. I read the problem and solution carefully on the Stack overfull or other forum for programmer. I also study documentation tirelessly although most of the time I don't understand. I did not give up, I read, search and read and search, I repeat it again and again.

For a programmer, rendering templates may seem like a simple task, but for me as a beginner, it was a difficult and arduous task especially I couldn't succeed after countless trial.Template rendering may seem simple, but it involves many and varied concepts, including Python, Django, and virtual environment configuration and setup. In the end, I solved the problem and even successfully built a forum, which made me feel very proud and excited about myself.

I would also like to express my appreciation for this opportunity, I learned a lot and had a lot of fun (although most of the time is painful, it feels great when I solved the problem). I will cherish the opportunity and time if I can do programming project in the future.


henrytse henrytse ~ 30 Jun 2023 7:25 p.m.

I tried to push my project to the git_hub, but it seems the file is too large, git hub does not allowed me to push the file.

螢幕截圖_2023-07-01_上午3.16.19.png

To save time, I just compress the file and upload to my google drive, below is the link, please check.

https://drive.google.com/drive/folders/19UprOmTuW3kCunSlcN-_8yFci_6GEPxJ?usp=sharing

In fact, I tried to open the folder downloaded from USB as my old computer is broken. However, my program suddenly not functional. I was panic and I search and study the "error message" in my terminal. I realized the file of virtual environment cannot be used as I am not supposed to share programming file in that way. I have to delete the old file and establish a new virtual environment including re-downloading django, pillow and migrating data base. Finally, it works and I can capture my work.

This is my project, thank you for your time.


tjguk Tim Golden ~ 30 Jul 2023 8:03 p.m.

Hello Henry,

This is Tim -- I'm the mentor for your project.

A couple of things initially. The first is that the project you've chosen (a Django-based forum) is far beyond what's expected of a Grade 1 project. Have a look a the different syllabus outlines from this page

https://www.codegrades.com/syllabus/python2023/

and see if the level of complexity in your project fits better into a higher grade.

Secondly, I need to be able to see your code, and I can't access via the GDrive link you provided. There shouldn't be any problem pushing any size of code up to Github. I don't know what your level of experience is there, but I'm quite happy to point you towards some resources which can help you get the code on Github.


henrytse henrytse ~ 16 Aug 2023 3:46 a.m.

Please accept my sincere apology for being so busy last week. I had pushed my project on GitHub, please feel free to check with HTTPs: https://github.com/HenryTseee/Django_project.git or directly git clone with git@github.com:HenryTseee/Djangoproject.git.

During my initial attempt to push it, I did not excluded database file such as .DS store, .venv, python_modules,pycache from the gitignore file, resulting in the size exceeding the limit. As a result, I had to spend some time rewriting the history, which is very complicated for me. Nevertheless, I found the solution and you can see my code now~ :) Thank you very much for your time.


tjguk Tim Golden ~ 20 Sep 2023 8:30 p.m.

Please accept my apologies for being so late to review and assess. I can now see the code and I hope to be able to assess it tomorrow.

As it stands, I'm still assessing it against a Grade 1 framework. But, as I mentioned above, the project you've chosen is considerably more sophisticated than a Grade 1 would usually be. Feel free to reconsider whether you want to aim at a higher grade to start with: there's no requirement to start with Grade 1 simply because it's your first project.


Back to top