Wednesday, April 16, 2025

Getting Started with Django: Templates, Static Files, URLs, Views, and More

Getting Started with Django: Templates, Static Files, URLs, Views, and More






If you're new to Django, this post will walk you through some of the foundational concepts that are essential to building a Django project—from managing HTML templates and static files to handling routes, dynamic data, and user authentication.

Let’s break everything down step by step.

.


🧱 1. Templates: Where HTML Lives

In Django, if you want to create webpages using HTML, you store your HTML files inside a folder named templates.

Why?
Django uses its own templating engine to render HTML dynamically. So, keeping your HTML files in a dedicated templates folder is a best practice.

Example structure:

myapp/ ├── templates/ │ └── index.html

After this you add templates folder name in Templates oobject in  settings.py file like this 

        'DIRS': [BASE_DIR,"./templates"],

🎨 2. Static Files: CSS, JS, Images

Static files refer to your CSS, JavaScript, images, or any fonts that don’t change frequently.

To manage these in Django, you create a static folder:

Example structure:

myapp/ ├── static/ │ ├── css/style.css │ ├── js/script.js │ └── images/

In your HTML file, use Django’s {% load static %} tag to access them:

{% load static %} <link rel="stylesheet" href="{% static 'css/style.css' %}">

🖼️ 3. Media Files: User-Uploaded Content

All Static Media files are uploaded by users—like profile pictures, documents, or any other dynamic content.

To store these files, Django uses a media folder, and you need to configure it in your settings.py:


⚙️ 4. The settings.py File

Django's settings.py is the brain of your project. It controls:

  • Database configuration

  • Installed apps

  • Static and media file paths

  • Middleware

  • Templates configuration

  • Security settings

You’ll often come back to this file when changing configurations or integrating third-party apps.
 

🚀 5. Running the Django Project

Once your setup is ready and you've created your app, you can start the development server to run your Django project locally.

Use this command:

python manage.py runserver

By default, the server runs at http://127.0.0.1:8000/ — just open it in your browser to see your project live!

🧪 6. Migrations: Creating Database Tables

To create tables in the database (based on models you define), you use Django’s migration system.

Run this command:

python manage.py migrate

This applies all the built-in or custom model changes to your database. It's like syncing your database with your models.

👮 7. Creating a Superuser (Admin Panel)

Django has a built-in admin panel. To access it, you need a superuser account.

Create it using this command:

python manage.py createsuperuser

Fill in the username, email, and password. Then you can log into /admin and manage your data via an intuitive UI.

To go on admin dashboard you write /admin on after IP address then you can see your admin dashboard


📍 8. Routing in Django

In Django, routing means connecting a URL to a view function.

➕ Static Routes

  1. Create a function in views.py:

from django.http import HttpResponse
def aboutUs(request): return HttpResponse("Hello world")
  1. Add it in urls.py:

from django.urls import path from myproject import views myproject means your pproject folder name where you add your settings.py file urlpatterns = [ path('about-us/', views.aboutUs), ]

🔁 Dynamic Routes

Django allows you to create dynamic URL patterns to capture and use data directly from the URL.

You can define the type of data expected in the route using converters.

There are three commonly used types:

1. int → Accepts only integers
path('about/<int:courseid>/', views.courseDetail)
Example URL: /about/123/s

2. str → Accepts any non-empty string (excluding slashes)
path('about/<str:courseid>/', views.courseDetail)
Example URL: /about/python/

3. slug → Accepts letters, numbers, underscores, and hyphens
path('about/<slug:courseid>/', views.courseDetail)
Example URL: /about/hello-123/

Example View

Inside views.py, you can access the dynamic value like this:

from django.http import HttpResponse def courseDetail(request, courseid): return HttpResponse(f"Course ID is {courseid}")

This is useful for pages like course detail pages, product pages, blog posts, etc.

📦 9. Sending and Receiving Dynamic Data

Sometimes you want to send data from views to templates.

In views.py:

def homepage(request):
data = { "title": "Home Page", "name": "Welcome to my Django website" } return render(request, "index.html", data)

In index.html, receive it like this:

<title>{{ title }}</title>
<h1>{{ name }}</h1>

🔗 9. Linking URLs in Templates

Django provides the {% url %} tag for safe and dynamic internal linking.

Make sure your route in urls.py has a name:

path('about/<int>/', views.courseDetail, name='about')

Then in your template:

<a href="{% url 'about' %}">About</a>

🕵️ 10. Current Page Path

Want to know which page you're on?

In your template, you can use:

{{ request.path }}

This will return the current URL path, useful for active menu highlighting or logging.

🛠️ How to Create a Model in Django

Now we’ll walk through the steps to create a basic model in Django — from setting up your app to registering your model in the Django admin panel. Let's get started!

📁 Step 1: Create a New App

Before creating any models, you need to create a new Django app. In this example, we’ll call it service. Run the following command in your terminal: python manage.py startapp service This will generate a service folder with default files including models.py, admin.py, and more

✍️ Step 2: Define Your Model

Open service/models.py and define your model class. Here’s an example model for a service:

from django.db import models

class Service(models.Model): service_icon = models.CharField(max_length=50) service_title = models.CharField(max_length=50) service_des = models.TextField()

This creates a model with three fields: icon, title, and description.

🧱 Step 3: Create Migrations

Once the model is defined, generate the migration file that Django uses to create the corresponding database table:

python manage.py makemigrations

This will create a migration file under the migrations/ folder of your service app.

🗃️ Step 4: Apply Migrations

Now, apply the migration to actually create the table in your database:

python manage.py migrate

Your Service model is now part of the database!

⚙️ Step 5: Register the Model in Django Admin

To manage the Service model from the Django admin panel, register it in service/admin.py:

from django.contrib import admin

from service.models import Service class ServiceAdmin(admin.ModelAdmin): list_display = ('service_icon', 'service_title', 'service_des') admin.site.register(Service, ServiceAdmin)

This will show the service records with icon, title, and description columns in the Django admin dashboard.

Previous Post
Next Post

post written by:

0 comments: