display data from database in django
- Models: Define a model in your
models.py
file to represent the data structure. For example: ```python from django.db import models
class YourModel(models.Model): field1 = models.CharField(max_length=100) field2 = models.IntegerField() # Add other fields as needed ```
Migrations: Create and apply migrations to update the database schema based on your model changes.
bash python manage.py makemigrations python manage.py migrate
Admin Panel (Optional): Register your model in the
admin.py
file to easily manage data through Django admin. ```python from django.contrib import admin from .models import YourModel
admin.site.register(YourModel) ```
- Views: Create a view in
views.py
to fetch data from the database. ```python from django.shortcuts import render from .models import YourModel
def your_view(request): data = YourModel.objects.all() return render(request, 'your_template.html', {'data': data}) ```
- Templates: Create an HTML template in the
templates
folder to display the data. ```html
Your Data
-
{% for item in data %}
- {{ item.field1 }} - {{ item.field2 }} {% endfor %}
```
- URLs: Configure a URL pattern in
urls.py
to link the view. ```python from django.urls import path from .views import your_view
urlpatterns = [ path('your-url/', your_view, name='your-view-name'), ] ```
- Settings: Include the app's URL configuration in the project's
urls.py
. ```python # in your project's urls.py from django.contrib import admin from django.urls import include, path
urlpatterns = [ path('admin/', admin.site.urls), path('your-app/', include('your_app.urls')), ] ```
Run Server: Start the development server.
bash python manage.py runserver
Access: Open a web browser and navigate to the specified URL (e.g., http://127.0.0.1:8000/your-app/your-url/) to view the data from the database.