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
Go to http://localhost:8000/admin
Log in with your superuser credentials
Click on Jobs → Add
Upload an image (e.g., code.jpg) and provide a summary
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
Post a Comment