Home Backend Development Python Tutorial Week Getting Started with My Blog App

Week Getting Started with My Blog App

Jul 19, 2024 pm 03:32 PM

Week  Getting Started with My Blog App

They say that when you document your learning, struggles, and etc., you will gain knowledge more. So from this day, 15th of July, 2024, I decided to document my progress for learning Django by developing Blog App without using ChatGPT, Gemini, and other AI chatbots that can generate code.

These past few years, I've been creating applications with the help of ChatGPT for generating code for me, and the outcome was great, I was able to build the applications. however, I depend too much on ChatGPT and fail to deeply understand the concepts of programming. I feel that I do not know how to code from scratch and useless without the help of ChatGPT when developing applications. So from this point onward, I will do my best to read and understand from documentation to build this Simple Blog App.

This week, I started my journey of learning Django by creating a simple blog app. My goal is to document each step of the process and show my experiences and learnings.

Setting Up the Project

Step 1: Create a virtual Environment
First, I created a virtual environment to manage project dependencies:

python -m venv <myenv> 
source myenv/bin/activate # On Windows use `myenv\Scripts\activate`
Copy after login

Step 2: Install Django and Create New Django Project
Next, I installed django and create new project called blog_app

pip install django
# Create new django project
django-admin startproject blog_app
cd blog_app
Copy after login

Create User's App

Step 1: Setting Up the App
I created first the, User authentication

# Either of the two
django-admin startapp user
python manage.py startapp user
Copy after login

I then added the new app to the INSTALLED_APPS list in the settings.py.

Step 2: Creating User's Login and SignUp forms
I created forms.py file in the users app folder. I make use of the Django built-in AuthenticationForm and UserCreationForm by inheriting it to the custom class. I think this way, I can customize later the users information.

# user/forms.py
from django.contrib.auth.forms import AuthenticationForm, UserCreationForm
from django.forms.widgets import PasswordInput, TextInput
from django.forms.fields import EmailField
from django import forms


class LoginForm(AuthenticationForm):
    username = forms.CharField(widget=TextInput())
    password = forms.CharField(widget=PasswordInput())


class SignUpForm(UserCreationForm):
    username = forms.CharField(max_length=150, required=True)
    email = forms.EmailField(required=True)
    password1 = forms.CharField(widget=forms.PasswordInput, required=True)
    password2 = forms.CharField(widget=forms.PasswordInput, required=True)

    def save(self, commit=True):
        user = super().save(commit=False)
        user.email = self.cleaned_data["email"]
        if commit:
            user.save()
        return user
Copy after login

Step 3: Create views.py
I then created a views for the home, login, logout and signup. I will not include how I created the html, css and javascript in this project. If you want to check I will link my Github repository below.

# user/views.py
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.contrib.auth import logout, authenticate, login
from .forms import *
from django.contrib.auth.models import auth

# I use the decorator `login_required` in order for the application to navigate to the login page if the user has not login or sign up yet.
@login_required
def homeView(request):
    return render(request, "home.html")

def loginView(request):
    '''
    First, I initialized my custom LoginForm then it will check the request of the user. 
    The user will then input it's username and password. Then it will check if the form is valid then it will get the user's input credential and it will authenticate it by using the built-in Django `authenticate` method. It will then check if the user correctly input it's credential and it will call the `login` method of Django and redirect the user to the homepage.
    '''
    form = LoginForm()
    if request.method == "POST":
       form = LoginForm(request, data=request.POST)
        if form.is_valid():
            username = request.POST.get("username")
            password = request.POST.get("password")
            user = authenticate(request, username=username, password=password)
            if user is not None:
                auth.login(request, user)
                return redirect("user:home")
    return render(request, "login.html", {"form": form})

def signupView(request):
    '''
    We will get the request from the user and check if the form is valid the we wills ave the user information in our SignUpForm
    '''
    if request.method == "POST":
        form = SignUpForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect("user:login")
    else:
        form = SignUpForm()
    return render(request, "signup.html", {"form": form})

def logoutView(request):
    '''
    I use the Django built-in `logout` method to logut the user
    '''
    logout(request)
    return redirect("user:login")
Copy after login

Step 4: Added a urls
I then added the urls for the user. First I added a home/empty urls in the blog_app/urls.py.

# blog_app/urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path("", include("user.urls", "user")),
    path("admin/", admin.site.urls),
]
Copy after login

Then I added created a urls.py in the user directory.

# user/urls.py
from django.urls import path, include
from .views import *

app_name = "user"

urlpatterns = [
    path("", homeView, name="home"),
    path("signup/", signupView, name="sign-up"),
    path("login/", loginView, name="login"),
    path("logout/", logoutView, name="logout"),
]
Copy after login

I created a variable app_name and assign the user. In this, as you can see in the views.py above, instead of templates/html.py I use user:login. I learned that with this, if the I will create a large-scale project, I can easily determine what app the function of views I redirect into.

Challenges and Learnings

This week, I encountered a few challenges, such as:

  • Understanding Django's project structure
  • Creating Django app and customizing forms

However, I learned a lot about the basics of Django and how to structure a project. I also realize the importance of reading the documentation thoroughly. Well, I still cannot stop using ChatGPT for asking questions for the error I encountered but I prompt it so that it won't give me an example code rather just plain explanations.

Next Week Goals

I plan to:

  1. Set up the admin panel for the Blog posts
  2. Create views and templates for listing and displaying blog posts
  3. Implement so that the user can post a blog.

Stay tuned for next week's update!

The above is the detailed content of Week Getting Started with My Blog App. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1663
14
PHP Tutorial
1266
29
C# Tutorial
1239
24
Python vs. C  : Applications and Use Cases Compared Python vs. C : Applications and Use Cases Compared Apr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

The 2-Hour Python Plan: A Realistic Approach The 2-Hour Python Plan: A Realistic Approach Apr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python: Games, GUIs, and More Python: Games, GUIs, and More Apr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

How Much Python Can You Learn in 2 Hours? How Much Python Can You Learn in 2 Hours? Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

Python vs. C  : Learning Curves and Ease of Use Python vs. C : Learning Curves and Ease of Use Apr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python and Time: Making the Most of Your Study Time Python and Time: Making the Most of Your Study Time Apr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python: Exploring Its Primary Applications Python: Exploring Its Primary Applications Apr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

Python vs. C  : Exploring Performance and Efficiency Python vs. C : Exploring Performance and Efficiency Apr 18, 2025 am 12:20 AM

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

See all articles