Welcome, aspiring web developers! Have you ever wanted to build your own corner of the internet to showcase your skills, projects, or just tell your story? A portfolio website is a fantastic way to do that. And what if I told you that you could build a powerful, professional-grade portfolio using Python, a language many of you might already know?
In this guide, we’re going to dive into the world of Django – a high-level Python web framework – and build a simple portfolio application from scratch. Don’t worry if you’re new to web development or Django; we’ll break down every step with clear explanations and simple language.
What is Django?
Django is a powerful and popular “web framework” built with Python. Think of a web framework as a toolkit that provides all the necessary components and structure to build a website quickly and efficiently. It handles many of the complex parts of web development for you, allowing you to focus on your website’s unique features. Django is known for its “Don’t Repeat Yourself” (DRY) philosophy and robust features, making it a great choice for everything from small personal projects to large-scale, complex applications.
Why Django for a Portfolio?
- Pythonic: If you know Python, you’ll feel right at home.
- Fast Development: Django’s conventions help you get up and running quickly.
- Scalable: Your portfolio can grow with you, easily adding new features.
- Secure: Django takes security seriously, handling many common vulnerabilities for you.
Let’s get started!
Setting Up Your Development Environment
Before we can code, we need to set up our workspace.
1. Install Python
First things first, you need Python installed on your computer. Django requires Python. You can download the latest version from the official Python website (python.org). Make sure to check the box that says “Add Python to PATH” during installation.
2. Create a Virtual Environment
A “virtual environment” is like a clean, isolated space on your computer for your project’s Python packages. This prevents conflicts between different projects that might use different versions of the same package. It’s a best practice in Python development.
Open your terminal or command prompt and navigate to where you want to store your project (e.g., cd Documents/WebProjects). Then, run these commands:
python -m venv env
python -m venv env: This command creates a new virtual environment namedenvin your current directory.venvis Python’s built-in module for creating virtual environments.
Now, activate your virtual environment:
- On macOS/Linux:
bash
source env/bin/activate - On Windows:
bash
.\env\Scripts\activate
You’ll notice(env)appearing at the beginning of your terminal prompt, indicating that the virtual environment is active.
3. Install Django
With your virtual environment active, install Django using pip, Python’s package installer:
pip install django
This command downloads and installs the latest stable version of Django into your virtual environment.
Creating Your First Django Project
In Django, a “project” is the entire web application, including its settings and configuration. An “app” is a smaller, self-contained module within a project that handles a specific feature (like a blog app, a user authentication app, or our portfolio app).
Let’s create our project:
django-admin startproject myportfolio .
django-admin: This is Django’s command-line utility.startproject myportfolio: This tellsdjango-adminto create a new project namedmyportfolio..: The dot at the end tells Django to create the project files in the current directory, rather than creating an extramyportfoliosubfolder.
Now, your project structure should look something like this:
myportfolio/
├── manage.py
└── myportfolio/
├── __init__.py
├── asgi.py
├── settings.py
├── urls.py
└── wsgi.py
manage.py: A command-line utility for interacting with your Django project (e.g., running the development server, creating apps).myportfolio/settings.py: Contains all the configuration for your Django project.myportfolio/urls.py: Where you define the “URL routes” for your entire project (which web address goes to which part of your code).myportfolio/wsgi.pyandasgi.py: Files used for deploying your application to a production web server.
Running the Development Server
Django comes with a lightweight “development server” that allows you to run and test your website on your local machine without needing a full-blown web server setup.
From your project’s root directory (where manage.py is located), run:
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 25, 2023 - 10:00:00
Django version 4.2.5, using settings 'myportfolio.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 celebratory Django welcome page!
127.0.0.1: This is a special IP address that always refers to your own computer (also known aslocalhost).8000: This is the “port number” that the server is listening on.
To stop the server, go back to your terminal and press CONTROL-C.
Creating Your Portfolio App
Remember the difference between a project and an app? Let’s create our first app, which will specifically handle our portfolio’s pages.
python manage.py startapp portfolio
This creates a new directory named portfolio with its own set of files:
portfolio/
├── migrations/
├── __init__.py
├── admin.py
├── apps.py
├── models.py
├── tests.py
└── views.py
1. Register the App
For Django to know about your new app, you need to “register” it in your project’s settings.py file.
Open myportfolio/settings.py and find the INSTALLED_APPS list. Add 'portfolio' to it:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'portfolio', # Add your app here
]
Defining URLs for Your App
Now we need to tell Django which “URLs” (web addresses) should lead to the pages within our portfolio app. This is done in urls.py files.
1. Project-level URLs
First, we’ll configure the main myportfolio/urls.py to include URLs from our portfolio app.
Open myportfolio/urls.py and modify it like this:
from django.contrib import admin
from django.urls import path, include # Import include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('portfolio.urls')), # Include portfolio app's URLs
]
path('', include('portfolio.urls')): This line tells Django that any request to the root URL (e.g.,http://127.0.0.1:8000/) should be handled by the URL patterns defined in ourportfolioapp’surls.pyfile.
2. App-level URLs
Now, create a new file inside your portfolio directory named urls.py:
portfolio/
├── migrations/
├── ...
└── urls.py <-- Create this file
Add the following content to portfolio/urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
]
from . import views: This imports theviews.pyfile from the current directory (ourportfolioapp).path('', views.home, name='home'): This defines a URL pattern. When someone visits the root of our portfolio app (which we linked to the project’s root''earlier), Django will call a function namedhomein ourviews.pyfile.name='home'gives this URL a convenient name for referencing it later.
Creating Views
A “view” in Django is a Python function (or class) that takes a web request and returns a web response, typically rendering an HTML page.
Open portfolio/views.py and add the home function:
from django.shortcuts import render
def home(request):
"""
This view renders the homepage of our portfolio.
"""
context = {
'name': 'Your Name',
'tagline': 'A Passionate Developer & Creator',
}
return render(request, 'portfolio/home.html', context)
render(request, 'portfolio/home.html', context): This is a shortcut function that takes therequestobject, the path to an HTML “template” file, and an optional dictionary ofcontextdata. It then combines the template with the data and returns anHttpResponsecontaining the rendered HTML.
Creating Templates
“Templates” are HTML files that serve as the structure for your web pages. They can contain special Django syntax to display dynamic content passed from your views.
First, we need to tell Django where to find our app’s templates.
1. Configure Template Directories
Open myportfolio/settings.py again. Find the TEMPLATES section and modify the DIRS list within OPTIONS:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR / 'templates'], # Add this line
'APP_DIRS': 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',
],
},
},
]
BASE_DIR / 'templates': This line tells Django to look for project-wide templates in a directory namedtemplatesdirectly under your project’s root. While we are usingAPP_DIRS: Truefor app-specific templates, it’s good practice to set this up for future project-level templates.
Now, create a templates directory inside your portfolio app, and then another portfolio directory inside that templates directory. This pattern (app_name/templates/app_name/) helps prevent template name conflicts if you have multiple apps.
portfolio/
├── migrations/
├── templates/
│ └── portfolio/ <-- Create this directory
│ └── home.html <-- Create this file
├── ...
└── urls.py
└── views.py
2. Create home.html
Now, put some basic HTML in portfolio/templates/portfolio/home.html:
<!-- portfolio/templates/portfolio/home.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 - {{ name }}</title>
<style>
body {
font-family: Arial, sans-serif;
line-height: 1.6;
margin: 0;
padding: 0;
background: #f4f4f4;
color: #333;
text-align: center;
}
.container {
width: 80%;
margin: auto;
overflow: hidden;
padding: 20px 0;
}
header {
background: #333;
color: #fff;
padding-top: 30px;
min-height: 70px;
border-bottom: #77aaff 3px solid;
}
header h1 {
margin: 0;
font-size: 2.5em;
}
header p {
font-size: 1.2em;
}
section {
padding: 40px 0;
margin-bottom: 20px;
background: #fff;
border-bottom: 1px solid #ddd;
}
footer {
padding: 20px;
margin-top: 20px;
color: #fff;
background-color: #333;
text-align: center;
}
</style>
</head>
<body>
<header>
<div class="container">
<h1>{{ name }}</h1>
<p>{{ tagline }}</p>
</div>
</header>
<section id="about">
<div class="container">
<h2>About Me</h2>
<p>Hello! I'm {{ name }}, a passionate individual enthusiastic about technology and creation. This is my simple portfolio where I'll share my journey and projects.</p>
<p>Stay tuned for more updates!</p>
</div>
</section>
<footer>
<p>© 2023 {{ name }}. All rights reserved.</p>
</footer>
</body>
</html>
Notice the {{ name }} and {{ tagline }}? These are “template variables” that Django replaces with the data from the context dictionary we passed from our views.py file.
Let’s See It Work!
Make sure your development server is running:
python manage.py runserver
Now, open your browser and visit http://127.0.0.1:8000/. You should see your simple portfolio homepage, displaying “Your Name” and “A Passionate Developer & Creator”!
Conclusion
Congratulations! You’ve successfully built your very first Django application: a simple portfolio website. You’ve learned how to:
- Set up a Python virtual environment.
- Install Django.
- Create a Django project and app.
- Understand project and app structure.
- Run the Django development server.
- Define URL patterns.
- Create Django views to handle requests.
- Render HTML templates with dynamic data.
This is just the beginning! From here, you can expand your portfolio by:
* Adding more pages (e.g., “Projects”, “Contact”).
* Creating “models” to store data in a database (like details about your projects).
* Adding CSS and JavaScript (called “static files” in Django).
* Implementing forms for user interaction.
Keep exploring, keep building, and have fun with Django!
Leave a Reply
You must be logged in to post a comment.