Hello there, aspiring web developers and creative minds! Are you looking for a fantastic way to showcase your projects, skills, and unique style to the world? A personal portfolio website is your answer! It’s an essential tool for anyone in tech, design, or any creative field to present their work professionally.
In this guide, we’re going to embark on an exciting journey to build a simple portfolio website using Django. Don’t worry if you’re new to web development or Django; we’ll break down every step into easy-to-understand pieces.
Why a Portfolio Website?
Think of a portfolio website as your digital resume and gallery rolled into one. It allows potential employers, clients, or collaborators to see your actual work, understand your capabilities, and get a feel for your style. It’s a powerful way to stand out from the crowd!
Why Django?
You might be wondering, “Why Django?” Good question!
- Django: Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. It’s built by experienced developers, takes care of much of the hassle of web development, so you can focus on writing your app without needing to reinvent the wheel.
- Python: Django is written in Python, a very popular, easy-to-learn, and powerful programming language. If you’re familiar with Python, you’ll feel right at home.
- “Batteries Included”: Django comes with many features built-in, like an admin panel (a ready-to-use interface to manage your website’s content), an ORM (Object-Relational Mapper, which helps you interact with databases using Python code instead of raw SQL), and much more. This means less setup for you!
- MVT Architecture: Django follows the Model-View-Template (MVT) architectural pattern, which helps organize your code logically.
- Model: This is where you define the structure of your data (like your project titles, descriptions, images).
- View: This handles the logic – what data to fetch from the Model and how to process it.
- Template: This is where you define how your data is displayed to the user (usually HTML, CSS, and some Django template language).
Ready to dive in? Let’s get started!
Prerequisites
Before we begin, make sure you have the following installed:
- Python 3: Django is a Python framework, so you’ll need Python installed on your computer. You can download it from the official Python website (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!
Step 1: Setting Up Your Environment
A crucial first step in any Python project is setting up a virtual environment.
- Virtual Environment: Think of a virtual environment as an isolated box or a clean workspace for your project. It keeps your project’s dependencies (like Django) separate from other Python projects you might have on your computer. This prevents conflicts and keeps your project tidy.
Let’s create and activate one:
-
Create a project directory:
bash
mkdir my_portfolio
cd my_portfoliomkdir: This command creates a new directory (folder).cd: This command changes your current directory.
-
Create a virtual environment:
bash
python -m venv venvpython -m venv: This command uses Python’s built-invenvmodule to create a virtual environment.venv: This is the name we’re giving to our virtual environment folder. You can name it anything you like, butvenvis a common convention.
-
Activate the virtual environment:
- On macOS/Linux:
bash
source venv/bin/activate - On Windows (Command Prompt):
bash
venv\Scripts\activate.bat - On Windows (PowerShell):
bash
venv\Scripts\Activate.ps1
You’ll know it’s active when you see(venv)at the beginning of your command line prompt.
- On macOS/Linux:
-
Install Django: Now that your virtual environment is active, let’s install Django!
bash
pip install Django Pillowpip: This is Python’s package installer, used to install libraries.Django: Our web framework.Pillow: This is a Python imaging library that Django often uses for handling image uploads. We’ll need it if we want to add images to our projects.
Step 2: Starting a New Django Project
With Django installed, we can now create our main project.
-
Start the Django project:
bash
django-admin startproject portfolio_project .django-admin: This is Django’s command-line utility.startproject: This command creates the basic structure for a Django project.portfolio_project: This is the name of our main project..: The dot tells Django to create the project in the current directory (my_portfolio) rather than creating another nested folder.
After running this, your
my_portfoliodirectory will look something like this:
my_portfolio/
├── venv/
├── portfolio_project/
│ ├── __init__.py
│ ├── asgi.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
└── manage.py
*manage.py: A command-line utility for interacting with your Django project (running the server, managing the database, etc.).
*portfolio_project/settings.py: This file holds all your project’s configuration.
*portfolio_project/urls.py: This file defines how URLs map to your website’s content.
Step 3: Creating an App for Your Portfolio
In Django, projects are often composed of several “apps.” An app is a self-contained module that does one thing (e.g., a blog app, a user authentication app, or in our case, a portfolio app). This modular design makes your code organized and reusable.
-
Create the portfolio app:
bash
python manage.py startapp projectspython manage.py: We usemanage.pyto run Django-specific commands.startapp: This command creates the basic structure for a Django app.projects: This is the name of our app. We’ll use it to manage our portfolio projects.
Now your
my_portfoliodirectory will look like this:
my_portfolio/
├── venv/
├── portfolio_project/
│ └── ...
├── projects/
│ ├── migrations/
│ ├── __init__.py
│ ├── admin.py
│ ├── apps.py
│ ├── models.py
│ ├── tests.py
│ └── views.py
└── manage.py -
Register your new app: Django needs to know that your
projectsapp exists. Openportfolio_project/settings.pyand find theINSTALLED_APPSlist. Add'projects'to it:“`python
portfolio_project/settings.py
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!
]
“`
Step 4: Defining Your Portfolio Data (Models)
Now, let’s define what information each of your portfolio projects will have. This is done using Django models.
- Models: In Django, models are Python classes that define the structure of your database. Each class represents a table in the database, and each attribute in the class represents a column in that table. Django’s ORM (Object-Relational Mapper) helps you interact with your database using Python objects instead of writing raw SQL queries.
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()
technology = models.CharField(max_length=20)
image = models.ImageField(upload_to='images/') # Requires Pillow to be installed
link = models.URLField(max_length=200, blank=True) # Optional link
def __str__(self):
return self.title
models.CharField: A field for short text strings (like titles or technologies).max_lengthis required.models.TextField: A field for longer text (like descriptions).models.ImageField: A field for uploading image files.upload_to='images/'tells Django to store uploaded images in a subdirectory namedimagesinside yourMEDIA_ROOT.models.URLField: A field for storing URLs.blank=Truemeans this field is optional.__str__(self): This special method tells Django how to represent aProjectobject as a string. It’s useful for the admin panel.
After defining your model, you need to tell Django to create the corresponding database tables.
-
Make migrations:
bash
python manage.py makemigrations
This command creates migration files, which are instructions for Django on how to change your database schema to match your models. -
Apply migrations:
bash
python manage.py migrate
This command executes those instructions, creating the actual tables in your database. Django uses a default SQLite database, which is perfect for development.
Step 5: Making It Visible in the Admin Panel
Django comes with a powerful, ready-to-use admin panel. Let’s make our Project model accessible there so we can easily add and manage our portfolio items.
-
Create a superuser: This will be your login for the admin panel.
bash
python manage.py createsuperuser
Follow the prompts to create a username, email (optional), and password. -
Register your model: Open
projects/admin.pyand add the following:“`python
projects/admin.py
from django.contrib import admin
from .models import Projectadmin.site.register(Project)
“`
Now, let’s start the development server to see our admin panel.
python manage.py runserver
Open your web browser and go to http://127.0.0.1:8000/admin/. Log in with the superuser credentials you just created. You should see “Projects” listed under your PROJECTS app. Click on “Projects” to add new portfolio items! Add a few sample projects.
Step 6: Displaying Your Projects (Views and Templates)
Now that we have data in our database, let’s display it on a webpage. This involves creating a view to fetch the data and a template to render it.
- Views: In Django, a view is a Python function (or class) that takes a web request and returns a web response. It’s where your application’s logic resides, deciding what data to show and how to process user input.
-
Templates: Templates are special HTML files that Django uses to display dynamic information. They combine static HTML with Django’s template language to inject data from your views.
-
Create a view: Open
projects/views.pyand add a simple view to fetch all projects:“`python
projects/views.py
from django.shortcuts import render
from .models import Projectdef all_projects(request):
projects = Project.objects.all() # Fetch all Project objects from the database
return render(request, ‘projects/all_projects.html’, {‘projects’: projects})
``render(request, template_name, context)
*: This function takes therequest, the path to your template, and a dictionary (context`) of data you want to pass to the template. -
Create a templates directory: Inside your
projectsapp folder, create a new folder namedtemplates, and inside that, another folder namedprojects. This naming convention (app_name/template_name.html) helps keep your templates organized and prevents naming conflicts.projects/
├── templates/
│ └── projects/
│ └── all_projects.html
└── ... -
Create your HTML template: Open
projects/templates/projects/all_projects.htmland add some basic HTML to display your projects:“`html
<!DOCTYPE html>
My Portfolio
My Awesome Portfolio
{% for project in projects %} <div class="project-card"> {% if project.image %} <img src="{{ project.image.url }}" alt="{{ project.title }} image"> {% endif %} <h2>{{ project.title }}</h2> <p><strong>Technology:</strong> {{ project.technology }}</p> <p>{{ project.description }}</p> {% if project.link %} <a href="{{ project.link }}" target="_blank">View Project</a> {% endif %} </div> {% empty %} <p>No projects to display yet. Go to the admin panel to add some!</p> {% endfor %}
``{% for project in projects %}
*: This is a Django template tag that loops through eachprojectin theprojectslist (which we passed from our view).{{ project.title }}
*: This is a Django template variable that displays thetitleattribute of the currentprojectobject.{% if project.image %}
*: This checks if an image exists for the project.{{ project.image.url }}
*: This provides the URL to the uploaded image.{% empty %}
*: This block runs if theprojects` list is empty. -
Configure Media Root (for images): For Django to serve uploaded files (like images), you need to tell it where to store them and how to serve them during development.
Openportfolio_project/settings.pyand add these lines at the very bottom:“`python
portfolio_project/settings.py
import os
… (other settings) …
MEDIA_URL = ‘/media/’
MEDIA_ROOT = os.path.join(BASE_DIR, ‘media’)
``MEDIA_URL
*: The URL prefix that will be used to serve media files (e.g.,/media/my_image.jpg).MEDIA_ROOT
*: The absolute path to the directory where uploaded files will be stored on your server.BASE_DIR` is a variable that points to your main project directory.
Step 7: Connecting URLs
Finally, we need to connect our view to a URL so that when someone visits a specific address in their browser, our view is executed and the template is displayed.
-
Create
urls.pyin your app: Inside theprojectsdirectory, create a new file namedurls.py:“`python
projects/urls.py
from django.urls import path
from . import views # Import the views from our current appurlpatterns = [
path(”, views.all_projects, name=’all_projects’), # Map the root URL of this app to our view
]
``path(”, …)
*: An empty string means this URL configuration handles the root of whatever path it's included under.views.all_projects
*: This tells Django to call theall_projectsfunction fromprojects/views.py.name=’all_projects’`: Gives a name to this URL pattern, which is useful for referring to it in templates or other parts of your code.
* -
Include app URLs in the project’s
urls.py: Now, we need to link our app’surls.pyinto the main project’surls.py. Openportfolio_project/urls.py:“`python
portfolio_project/urls.py
from django.contrib import admin
from django.urls import path, include # Add include
from django.conf import settings # Needed for media files
from django.conf.urls.static import static # Needed for media filesurlpatterns = [
path(‘admin/’, admin.site.urls),
path(”, include(‘projects.urls’)), # Include your projects app’s URLs here
]This is only for development! In production, web servers like Nginx handle media files.
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
``path(”, include(‘projects.urls’))
*: This tells Django that any request to the root URL of your website (http://127.0.0.1:8000/) should be directed to theurls.pyfile within yourprojectsapp.static` configuration is crucial for serving media files (like your project images) during development. Remember, this setup is only for development! For a live production website, you’d configure a web server like Nginx or Apache to serve your static and media files.
* The
Step 8: Running Your Development Server
If you stopped your development server earlier, start it again:
python manage.py runserver
Now, open your web browser and go to http://127.0.0.1:8000/.
Voilà! You should now see your “My Awesome Portfolio” page with the projects you added through the admin panel, complete with titles, descriptions, technologies, and images!
Conclusion
Congratulations! You’ve successfully built a basic portfolio website using Django. You’ve learned how to:
- Set up a Django project and app.
- Define data models for your projects.
- Use the Django admin panel to manage content.
- Create views to fetch data.
- Design templates to display information.
- Connect URLs to bring it all together.
This is just the beginning! From here, you can expand your website by:
- Adding CSS and JavaScript: To make your site visually stunning and interactive.
- Creating a detail page: For each project, showing more information.
- Implementing more features: Like an “About Me” page, a contact form, or blog posts.
- Deployment: Learning how to put your website online for the world to see!
Keep experimenting, keep learning, and happy coding!
Leave a Reply
You must be logged in to post a comment.