Building Social Media Apps · Course book
Chapter 2: A Social Network in Django
A front-end page can look like a social network, but it becomes one only when people can sign up, post, like, follow and search, and when all of that is saved and shown back to the right people. That is the job of the back end. Django, a mature Python web framework, provides most of the pieces out of the box: URL routing, templates, an object-relational mapper for the database, user accounts with secure password storage, and an admin site. This chapter explains how a complete social media app is assembled with Django, from project setup and routing to models, authentication, uploads, likes, follows, a personalised feed, search and suggestions, with the database logic worked through by hand.
Projects, apps, routes and templates
A Django project holds the settings for a whole site, and it contains one or more apps, each a package for one area of features. A social site might have a single app called core. Creating them takes two commands, django-admin startproject and python manage.py startapp, and the app is then registered in the project's INSTALLED_APPS setting.
Requests flow through a simple chain. The project's urls.py includes the app's URL patterns; each pattern maps a path, such as signup or profile/<str:pk>, to a view function; the view gathers data and returns a response, usually by rendering a template. Templates are HTML files with Django's template language mixed in: {{ user_profile.bio }} inserts a value, {% for post in posts %} loops, and {% if %} chooses between versions of a page. Static files such as CSS, JavaScript and images used by the design are stored in a static folder and referenced with the {% static %} tag, after {% load static %} at the top of the template, so that Django can serve them correctly in development and production.
Converting a ready-made HTML design into templates is a large part of a project like this. The designer's files usually arrive as complete pages with hard-coded names, pictures and posts. Each repeated piece, such as one post in the feed, is replaced by a loop over real data, and each hard-coded value, such as a username, by a template variable. Links between pages are written with the {% url %} tag and the name of a route rather than a fixed path, so that changing a URL pattern later does not break every link. Shared parts such as the header can be moved into a base template that other pages extend, which removes duplication and keeps the look of every page consistent.
Models: the data behind the app
A model is a Python class that describes a database table; Django creates and updates the tables with migrations, generated by makemigrations and applied by migrate. Django's built-in User model already stores usernames, emails and hashed passwords, so the app only adds what is specific to it.
| Model | Key fields | Purpose |
|---|---|---|
| Profile | user (link to User), bio, location, profile image | Extra details for each account |
| Post | id (UUID), user, image, caption, created date, number of likes | One uploaded post |
| LikePost | post id, username | Records who liked which post |
| FollowersCount | follower, user | Records who follows whom |
The Profile links to User with a foreign key or one-to-one relationship, so each account has exactly one profile. Posts use a UUID, a random 128-bit identifier, as their primary key, rather than counting 1, 2, 3; this makes post addresses impossible to guess or enumerate. Images are stored with an ImageField, which needs the Pillow library, and uploaded files go to a media folder configured with MEDIA_URL and MEDIA_ROOT. Registering each model in admin.py makes it visible in Django's admin site, a convenient way to inspect data while developing.
Sign up, sign in and account settings
The sign-up view handles two cases. A GET request shows the empty form. A POST request reads the username, email and two password fields, then validates: the passwords must match, and the username and email must not already be taken. If everything is valid, User.objects.create_user creates the account, storing the password as a salted hash rather than plain text, the user is logged in, and a Profile is created for them before redirecting to the settings page. When validation fails, Django's messages framework shows an error such as "Email taken" on the next page.
The sign-in view passes the submitted credentials to auth.authenticate, which returns the user if the password is correct, and auth.login starts a session. Logout ends it. Views that only logged-in users may see are protected with the @login_required decorator, which redirects anyone else to the sign-in page. Every form that sends a POST request includes {% csrf_token %}, which protects against cross-site request forgery: a hidden token proves that the form was really served by the site.
The account settings page lets users update their bio, location and profile picture. The view must handle two situations: the user uploaded a new picture, found in request.FILES, or left it unchanged, in which case the existing image is kept. Forms that upload files need enctype="multipart/form-data", or the file never reaches the server.
A session works through a cookie. After a successful login, Django stores a random session identifier in the user's browser and keeps the matching record, which user it belongs to and when it expires, on the server. Every later request carries the cookie, so request.user is available in every view and template without the user signing in again. Because the identifier is long and random, it cannot be guessed, and logging out deletes the server-side record so the old cookie becomes useless. Sites served over HTTPS should also mark the cookie as secure, so browsers never send it over an unencrypted connection.
Posts, likes and follows
Uploading a post creates a Post row with the image and caption. Likes use the LikePost table as a record of who liked what. When a user clicks the like button, the view looks for a LikePost row with that post and username. If none exists, it creates one and adds 1 to the post's like count; if one exists, it deletes it and subtracts 1, so the same button toggles between like and unlike. The rule that one person can like a post only once is enforced by checking before inserting.
Follows work the same way with FollowersCount. A profile page shows the user's posts and their numbers of posts, followers and following, each computed with a query. For example, a user's follower count is the number of FollowersCount rows whose user field is that user.
The feed is built by collecting the usernames the current user follows and fetching all their posts, newest first. Search filters users whose username contains the search text, using username__icontains, a case-insensitive "contains" lookup. A download link simply points to the post's image file in the media folder.
Efficient queries and moving towards production
A common performance trap in database-backed pages is the N + 1 query problem. If a view fetches 20 posts with one query and the template then asks for each post's author profile, Django runs one extra query per post: 1 + 20 = 21 queries. With 100 posts it becomes 101. Using select_related for single related objects, or prefetch_related for lists of them, fetches the related data in one or two queries in total, however many posts there are.
Storing a running like count on each post, as this design does, is another performance choice: the feed can show counts without counting LikePost rows every time. The cost is that the two must be kept in step, so updates belong inside a database transaction, or the count can be recalculated periodically. Before going live, a Django site also needs DEBUG turned off, a secret key kept out of the code, allowed host names set, uploaded media stored somewhere durable such as cloud storage, and a production-grade database instead of the default SQLite file.
Practice tasks
- Add a fifth user, eve, who follows ana and chi. Recompute each user's follower count and ana's suggestions.
- Write the steps the like view takes when a user who already liked a post clicks the button again.
- A profile page lists 40 posts and shows each author's picture. How many queries run with the naive approach, and how many with related data fetched in advance?
- Explain why passwords must never be stored as plain text, and what
create_userdoes instead. - Why do posts use UUIDs rather than counting numbers as their identifiers?
- List three settings you would change before deploying the app to production, and why.
This course book is available to read online only at tech-academy.chrysolites.org.