Python and Web Development: Building a Social Media Website with Django

Table of Contents

  1. Overview
  2. Prerequisites
  3. Setup
  4. Creating a Django Project
  5. Setting Up the Database
  6. Creating User Authentication
  7. Building the User Profile
  8. Creating a Post Model
  9. Implementing Post Views
  10. Adding Likes and Comments
  11. Conclusion

Overview

In this tutorial, we will learn how to build a social media website using Python and the Django web framework. By the end of this tutorial, you will have a basic understanding of Django and be able to create a fully functional social media website where users can sign up, create posts, and interact with each other’s posts.

Prerequisites

Before starting this tutorial, you should have a basic understanding of Python programming language. Familiarity with web development concepts such as HTML, CSS, and JavaScript will also be helpful but not required.

Setup

To get started, make sure you have Python installed on your computer. You can download the latest version of Python from the official website (https://www.python.org/downloads/). Additionally, you will need to install Django, which can be done using pip, the Python package installer. Open your command line interface and run the following command: shell pip install django

Creating a Django Project

Let’s begin by creating a new Django project. Open your command line interface and navigate to the desired directory where you want to create your project. Run the following command to create a new Django project named “social_media”: shell django-admin startproject social_media This will create a new directory called “social_media” with the basic structure for a Django project.

Setting Up the Database

Next, we need to configure the database for our project. By default, Django uses SQLite as a database backend, which is suitable for development purposes. Open the “settings.py” file inside the “social_media” directory and locate the “DATABASES” section. Update the configuration as follows: python DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'db.sqlite3', } } Save the file.

Creating User Authentication

A social media website needs user authentication to allow users to sign up and log in. Django provides built-in authentication functionality, so we can easily implement this feature. Run the following command to create the necessary authentication views, URLs, and templates: shell python manage.py startapp accounts Then, open the “settings.py” file again and add ‘accounts’ to the “INSTALLED_APPS” list: python INSTALLED_APPS = [ ... 'accounts', ... ] Save the file.

Next, create a new file called “urls.py” inside the “accounts” directory. Add the following code to the file: ```python from django.urls import path from . import views

urlpatterns = [
    path('signup/', views.signup, name='signup'),
    path('login/', views.login, name='login'),
    path('logout/', views.logout, name='logout'),
]
``` Save the file.

Now, let’s create the views and templates for authentication. In the “accounts” directory, create a new file called “views.py”. Add the following code to the file: ```python from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.contrib.auth import login as auth_login, logout as auth_logout

def signup(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            user = form.save()
            auth_login(request, user)
            return redirect('home')
    else:
        form = UserCreationForm()
    
    return render(request, 'signup.html', {'form': form})

def login(request):
    if request.method == 'POST':
        form = AuthenticationForm(request, data=request.POST)
        if form.is_valid():
            user = form.get_user()
            auth_login(request, user)
            return redirect('home')
    else:
        form = AuthenticationForm()
    
    return render(request, 'login.html', {'form': form})

def logout(request):
    auth_logout(request)
    return redirect('login')
``` Save the file.

Next, create two HTML templates inside the “templates” directory:

Create “signup.html” with the following content: ```html

<h2>Sign Up</h2>

<form method="POST">
  {% csrf_token %}
  {{ form.as_p }}
  <button type="submit">Sign Up</button>
</form>

``` Create "login.html" with the following content:
```html

<h2>Login</h2>

<form method="POST">
  {% csrf_token %}
  {{ form.as_p }}
  <button type="submit">Login</button>
</form>

``` At this point, we have implemented user authentication views, URLs, and templates. Django's built-in authentication forms take care of form validation, user creation, login, and logout processes.

Building the User Profile

In our social media website, we want each user to have a profile page where their information and posts can be displayed. Let’s implement this feature.

First, create a new app called “profiles” using the following command: shell python manage.py startapp profiles Then, open the “settings.py” file and add ‘profiles’ to the “INSTALLED_APPS” list.

Next, update the “models.py” file inside the “profiles” directory with the following code: ```python from django.db import models from django.contrib.auth.models import User

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    bio = models.TextField(max_length=500)
    avatar = models.ImageField(upload_to='avatars/', null=True, blank=True)
    
    def __str__(self):
        return self.user.username
``` Save the file.

To generate and apply the database migration for the new model, run the following commands: shell python manage.py makemigrations python manage.py migrate