Creating and Displaying Django Model Objects with Admin Panel

Creating and Displaying Django Model Objects with Admin Panel

In this tutorial, we'll walk through creating a Django superuser, registering a model with the admin panel, uploading objects, and displaying those objects dynamically on a web page using Django templates.


๐Ÿ‘ค Step 1: Create a Superuser

To access Django's admin panel and manage your database through a GUI, create a superuser:

python manage.py createsuperuser


You’ll be prompted to enter:

  • Username

  • Email (optional)

  • Password

Once created, your superuser will be able to log in at:

๐Ÿ“ http://localhost:8000/admin


๐Ÿงพ Step 2: Register the Model in admin.py

Open jobs/admin.py and register the Job model:

from django.contrib import admin

from .models import Job

admin.site.register(Job)

This makes the Job model accessible and editable via the Django admin panel.


๐Ÿ–ผ️ Step 3: Add a Job via Admin Panel

  1. Go to http://localhost:8000/admin

  2. Log in with your superuser credentials

  3. Click on Jobs → Add

  4. Upload an image (e.g., code.jpg) and provide a summary

  5. Click Save

✅ This action creates a Job object in your PostgreSQL database and stores the uploaded image in the /images/ folder of your project (as defined by models.ImageField(upload_to='images/')).


๐Ÿงฒ Step 4: Pull Job Objects from the Database

Now, instead of viewing your data only in the admin panel, let’s display the jobs on the main page.

Update jobs/views.py:

from django.shortcuts import render

from .models import Job


def homepage(request):

    jobs = Job.objects  # Fetch all Job objects

    return render(request, 'jobs/home.html', {'jobs': jobs})  # Pass to template


  • Job.objects returns a queryset of all Job records.

  • {'jobs': jobs} passes this data into the template context.


๐Ÿ–ฅ️ Step 5: Update home.html Template

Inside jobs/templates/jobs/home.html, update the file to loop through the job entries:

<h1>All My Jobs</h1>


{% for job in jobs.all %}

    <p>{{ job.summary }}</p>

{% endfor %}


This will display all job summaries stored in your database.


๐Ÿ“‚ Output: Image Folder

When you upload images via the admin panel, Django automatically saves them to the images/ folder in your project directory. This is handled by the line in models.py:

image = models.ImageField(upload_to='images/')



✅ Summary

  • ✅ Created a superuser for the Django admin panel

  • ✅ Registered the Job model for CRUD operations

  • ✅ Uploaded job objects including images via the admin

  • ✅ Rendered model data dynamically in the front-end template

This is a key part of building a dynamic portfolio site or job listing board using Django.


Next: Integrate Bootstrap into Your Django Project – Quick & Simple


Comments

Popular posts from this blog

React + TypeScript Setup and Usage Guide

Python Coding Interview Questions (Beginner to Advanced)