Welcome, aspiring web developers! Have you ever wanted to showcase your projects, skills, and creativity online but felt overwhelmed by all the technical jargon? You’re in the right place! In this blog post, we’re going to embark on an exciting journey to build a simple portfolio website using a powerful and popular web framework called Django.
This guide is designed for absolute beginners. We’ll break down each step, explain technical terms in plain language, and make sure you understand why we’re doing things, not just how. By the end, you’ll have a basic, functional portfolio site that you can expand upon and be proud of!
What is a Portfolio Website and Why Do You Need One?
A portfolio website is essentially your personal online showcase. It’s a digital space where you can display your work, highlight your skills, share your experiences, and provide contact information. Think of it as an online resume that’s much more interactive and visually engaging.
Why is it important?
* Showcase Your Work: Whether you’re a developer, designer, writer, or artist, a portfolio allows you to demonstrate your capabilities.
* Professional Presence: It establishes your online identity and makes you look professional to potential employers or clients.
* Accessibility: Your work is available 24/7 to anyone, anywhere in the world.
* Networking: It provides a hub for people to learn more about you and connect.
Why Choose Django for Your Portfolio?
There are many ways to build a website, so why are we picking Django?
Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. It’s often called “the web framework for perfectionists with deadlines.”
Here’s why it’s great for beginners and for this project:
- “Batteries Included”: This means Django comes with a lot of built-in features for common web development tasks. You don’t have to search for separate tools for things like user authentication, an administration panel, or database interaction – it’s all ready to go!
- Python-based: If you’re familiar with Python (or want to learn it), Django uses Python exclusively, making it very readable and beginner-friendly.
- Scalable: While we’re starting simple, Django is used by huge companies like Instagram and Pinterest. This means your project can grow with you.
- Clear Structure: Django promotes a clear way of organizing your project into “apps,” which makes managing your website’s different functionalities much easier.
Prerequisites: What You’ll Need
Before we dive into coding, make sure you have the following ready:
- Python 3: Django is built with Python, so you’ll need it installed on your computer. You can download it from python.org.
- Basic Command Line Knowledge: We’ll be using your computer’s terminal or command prompt to run commands. Don’t worry, we’ll guide you through each one!
Setting Up Your Environment
First things first, let’s set up a clean workspace for our project.
1. Create a Project Folder
Open your terminal or command prompt and navigate to a place where you want to store your project. Then, create a new folder:
mkdir my_portfolio
cd my_portfolio
mkdir: This command means “make directory” and creates a new folder.cd: This command means “change directory” and moves you into that folder.
2. Create a Virtual Environment
A virtual environment is a self-contained directory that has its own Python installation and a separate set of installed packages. It keeps your project’s dependencies isolated from other Python projects on your computer, preventing conflicts. It’s a best practice!
Inside your my_portfolio folder, run:
python3 -m venv venv
python3 -m venv: This command tells Python to create a virtual environment.venv: This is the name we’re giving to our virtual environment folder. You could name it anything, butvenvis a common convention.
Now, activate your virtual environment:
- On macOS/Linux:
bash
source venv/bin/activate - On Windows (Command Prompt):
bash
venv\Scripts\activate.bat - On Windows (PowerShell):
powershell
venv\Scripts\Activate.ps1
You’ll know it’s active when you see (venv) at the beginning of your terminal prompt.
3. Install Django
With your virtual environment activated, let’s install Django:
pip install django
pip: This is Python’s package installer. It’s how we add external libraries and frameworks (like Django) to our Python projects.
Creating Your First Django Project
Now that Django is installed, we can create our main project. A Django project is the entire collection of settings and applications that make up a particular website.
django-admin startproject portfolio_project .
django-admin startproject: This is the Django command to create a new project.portfolio_project: This is the name we’re giving to our main project folder..: The dot at the end is important! It tells Django to create the project files in the current directory (ourmy_portfoliofolder), rather than creating another nestedportfolio_projectfolder.
If you list the contents of your my_portfolio folder (using ls on macOS/Linux or dir on Windows), you’ll see something like this:
my_portfolio/
├── venv/
├── portfolio_project/
│ ├── __init__.py
│ ├── asgi.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
└── manage.py
manage.py: This is a very important script. You’ll use it for almost all interactions with your Django project (running the server, creating apps, managing the database, etc.).portfolio_project/settings.py: This file holds all the configuration for your Django project.portfolio_project/urls.py: This file handles the main URL routing for your entire project.
Running the Development Server
Let’s see if everything is working! Navigate into your portfolio_project folder (if you’re not already there) and run the development server:
cd my_portfolio # Make sure you are in the outer directory where manage.py is
python manage.py runserver
You should see output similar to this:
Performing system checks...
System check identified no issues (0 silenced).
You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
September 29, 2023 - 14:30:00
Django version 4.2.5, using settings 'portfolio_project.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
Open your web browser and go to http://127.0.0.1:8000/. You should see a “The install worked successfully! Congratulations!” page. This means your Django project is up and running!
To stop the server, go back to your terminal and press CONTROL-C.
Creating Your Portfolio App
In Django, an app is a web application that does something specific – for example, a blog app, a comments app, or in our case, a portfolio app. A project can have multiple apps. This modular approach keeps your code organized.
Make sure you are in the same directory as manage.py (which is my_portfolio in our case) and run:
python manage.py startapp projects
This creates a new folder named projects inside your my_portfolio directory:
my_portfolio/
├── venv/
├── portfolio_project/
│ └── ...
├── projects/
│ ├── migrations/
│ ├── admin.py
│ ├── apps.py
│ ├── models.py
│ ├── tests.py
│ └── views.py
└── manage.py
Registering Your App
Django doesn’t automatically know about new apps you create. You need to tell your project’s settings.py file about it.
Open portfolio_project/settings.py and find the INSTALLED_APPS list. Add 'projects' to it:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'projects', # Add your new app here
]
Designing Your Data Model (models.py)
A model in Django is a Python class that defines the structure of your data. It’s essentially a blueprint for how your data will be stored in a database. Each model usually maps to a table in your database.
For our portfolio, let’s imagine each project has a title, a brief description, maybe an image, and a link to the live project or its source code.
Open projects/models.py and add the following code:
from django.db import models
class Project(models.Model):
title = models.CharField(max_length=100)
description = models.TextField()
image = models.ImageField(upload_to='images/') # Placeholder for image, we'll configure later
url = models.URLField(blank=True) # Optional URL field
def __str__(self):
return self.title
Let’s break down the fields:
* models.CharField(max_length=100): A field for short text, like a title. max_length is required.
* models.TextField(): A field for longer text, like a description.
* models.ImageField(upload_to='images/'): A field for uploading images. upload_to specifies a subdirectory within your MEDIA_ROOT where images will be stored. (Note: Handling images fully requires additional setup, but this is a good starting point.)
* models.URLField(blank=True): A field for a web address. blank=True means this field is optional.
* def __str__(self):: This method tells Django how to represent an object of this class when it needs to display it (e.g., in the admin panel).
Making and Applying Migrations
Whenever you change your models.py file, you need to tell Django to update your database schema. This is done with migrations.
- Make Migrations: Django inspects your models and creates files describing the changes needed for your database.
bash
python manage.py makemigrations projects - Apply Migrations: Django applies those changes to your database.
bash
python manage.py migrate
This command applies all pending migrations, including the initial ones for Django’s built-in apps and now, ourprojectsapp.
Making Your Website Interactive (views.py)
A view in Django is a Python function (or class) that takes a web request and returns a web response. It contains the logic to fetch data, process it, and decide what to show the user.
Open projects/views.py and add the following code:
from django.shortcuts import render
from .models import Project # Import our Project model
def project_list(request):
projects = Project.objects.all() # Fetch all Project objects from the database
return render(request, 'projects/project_list.html', {'projects': projects})
render(request, 'template_name', context): This is a convenient function that takes therequest, the path to a template (an HTML file), and a dictionary of data (thecontext). It combines the data with the template and returns anHttpResponse.Project.objects.all(): This is how we query our database to get all instances of ourProjectmodel.
Connecting URLs (urls.py)
URLs (Uniform Resource Locators) are the web addresses people type into their browser to reach specific pages on your site. In Django, you define URL patterns that map to specific views.
We’ll need two urls.py files:
1. Project-level urls.py: This is the main router for your entire website. It directs requests to the appropriate app.
2. App-level urls.py: Each app defines its own URL patterns for its specific functionality.
1. Create an App-level urls.py
Inside your projects app folder, create a new file named urls.py: projects/urls.py.
from django.urls import path
from . import views # Import the views from our app
urlpatterns = [
path('', views.project_list, name='project_list'),
]
path('', views.project_list, name='project_list'): This line defines a URL pattern.'': An empty string means this URL pattern will match the root of the app (e.g.,/projects/).views.project_list: This tells Django to call ourproject_listview function when this URL is accessed.name='project_list': This gives a name to our URL pattern, which is useful for referring to it programmatically in templates or other parts of our code.
2. Include App URLs in Project urls.py
Now, let’s tell our main project urls.py to include the URLs from our projects app.
Open portfolio_project/urls.py:
from django.contrib import admin
from django.urls import path, include # Import 'include'
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('projects.urls')), # Add this line
]
path('', include('projects.urls')): This tells Django that any requests to the root URL (/) should be handled by theurls.pyfile inside ourprojectsapp.
Displaying Content (Templates)
A template in Django is an HTML file that contains static HTML along with special Django template language syntax to insert dynamic content. It’s how we separate our presentation logic from our business logic (in views).
1. Create a templates Directory
Django needs to know where to find your template files. We’ll create a templates folder inside our projects app.
cd projects
mkdir templates
cd templates
mkdir projects # Nested folder for clarity
So your structure will be my_portfolio/projects/templates/projects/. This nested projects folder inside templates helps prevent naming conflicts if you have multiple apps with templates of the same name (e.g., index.html).
2. Configure Template Directory in settings.py
Django needs to be told to look for templates in our new templates directory.
Open portfolio_project/settings.py and find the TEMPLATES setting. Modify the 'DIRS' list:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR / 'templates'], # Add this line
'APP_DIRS': True, # Keep this as True
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
The BASE_DIR / 'templates' tells Django to look for a templates folder at the root of your project. This is a common place for base templates, but for app-specific templates, APP_DIRS: True ensures Django also looks inside each app’s templates folder.
3. Create Your Template File
Now, let’s create the HTML file that will display our projects.
Create a file named project_list.html inside my_portfolio/projects/templates/projects/:
<!-- my_portfolio/projects/templates/projects/project_list.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My Portfolio</title>
<style>
body { font-family: Arial, sans-serif; margin: 20px; background-color: #f4f4f4; color: #333; }
h1 { color: #0056b3; }
.project-container { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 20px; }
.project-card { background-color: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
.project-card h2 { color: #007bff; margin-top: 0; }
.project-card p { font-size: 0.9em; line-height: 1.6; }
.project-card a { color: #007bff; text-decoration: none; font-weight: bold; }
.project-card a:hover { text-decoration: underline; }
.project-card img { max-width: 100%; height: auto; border-radius: 4px; margin-bottom: 10px; }
</style>
</head>
<body>
<h1>Welcome to My Portfolio!</h1>
<div class="project-container">
{% for project in projects %}
<div class="project-card">
{% if project.image %}
<!-- Note: To display images, you'd need to configure MEDIA_URL and MEDIA_ROOT in settings.py and handle URL patterns for media files. -->
<!-- For now, we'll just show the image if it exists. -->
<img src="{{ project.image.url }}" alt="{{ project.title }} Image">
{% endif %}
<h2>{{ project.title }}</h2>
<p>{{ project.description }}</p>
{% if project.url %}
<p><a href="{{ project.url }}" target="_blank">View Project</a></p>
{% endif %}
</div>
{% empty %}
<p>No projects to display yet. Check back soon!</p>
{% endfor %}
</div>
</body>
</html>
{% for project in projects %}: This is Django’s template tag for looping. It iterates over theprojectslist that we passed from our view.{{ project.title }}: This is how you display the value of an attribute of an object. Here, it displays thetitleof the currentproject.{% if project.image %}: This is a conditional template tag. It checks ifproject.imageexists before trying to display it.{% empty %}: This block within aforloop is displayed if the list (projects) is empty.
Populating Data (Admin Panel)
Django comes with a fantastic, automatically generated admin panel. It allows you to easily manage your website’s content (like adding, editing, and deleting projects) without writing complex backend forms.
1. Create a Superuser
A superuser is an account with full administrative privileges.
python manage.py createsuperuser
Follow the prompts to create a username, email (optional), and password.
2. Register Your Model with the Admin Panel
By default, Django doesn’t show your custom models in the admin panel. You need to register them.
Open projects/admin.py:
from django.contrib import admin
from .models import Project # Import your Project model
admin.site.register(Project) # Register your model
3. Access the Admin Panel and Add Data
Start your development server again:
python manage.py runserver
Go to http://127.0.0.1:8000/admin/ in your browser. Log in with the superuser credentials you just created.
You should now see “Projects” listed under your PROJECTS app. Click on “Projects” and then “Add Project”. Fill in the details for a few of your portfolio projects and click “Save”.
Now, go to http://127.0.0.1:8000/ (your website’s homepage), and you should see your projects displayed!
Next Steps
Congratulations! You’ve successfully built a basic portfolio website using Django. This is just the beginning. Here are some ideas for what you can do next:
- Styling with CSS: The website looks a bit plain. Learn how to link external CSS files and make it look beautiful.
- Handle Images Properly: To fully support image uploads, you’ll need to configure
MEDIA_ROOTandMEDIA_URLinsettings.pyand add a URL pattern to serve media files inportfolio_project/urls.py. - Detail Pages: Create a separate page for each project to show more details, using
projects/<int:pk>/in yoururls.pyand aproject_detailview. - About Me/Contact Page: Add more pages to your site.
- Deployment: Learn how to deploy your Django website to a live server so others can see it (e.g., using platforms like Heroku, Vercel, Render, or traditional VPS).
- Version Control: Start using Git and GitHub to track your code changes and collaborate.
Building this simple portfolio site is a fantastic first step into the world of web development with Django. Keep experimenting, keep learning, and happy coding!
Leave a Reply
You must be logged in to post a comment.