Here’s a draft for a simple Django project with an explanation:
Steps to Create a Simple Django Project
Install Django
Make sure you have Django installed. Use the following command:
pip install django
1.
Start a New Project
Create a new project by running:
django-admin startproject myproject
2.
Create an Application
Navigate to your project directory and create an app:
cd myproject
python manage.py startapp myapp
3.
Code Structure
1. settings.py
Register your app in the INSTALLED_APPS section:
INSTALLED_APPS = [
...
'myapp',
2. models.py (Defining a Database Model)
Define a simple model for storing articles:
from django.db import models
class Article(models.Model):
title = models.CharField(max_length=100) # Title of the article
content = models.TextField() # Content of the article
created_at = models.DateTimeField(auto_now_add=True) # Timestamp for creation
def __str__(self):
return self.title # Representation of the object
Run migrations to create the database schema:
python manage.py makemigrations
python manage.py migrate
3. views.py (Defining Views)
Create a view to display articles:
from django.shortcuts import render
from .models import Article
def article_list(request):
articles = Article.objects.all() # Fetch all articles
return render(request, 'article_list.html', {'articles': articles})
4. urls.py (Configuring URLs)
Create a urls.py file in your app and map the view:
from django.urls import path
from . import views
urlpatterns = [
path('', views.article_list, name='article_list'),
]
Include your app’s urls.py in the project’s urls.py:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('myapp.urls')), # Include app URLs
5. templates/article_list.html (HTML Template)
Create a template to display the articles:
<!DOCTYPE html>
<html>
<head>
<title>Article List</title>
</head>
<body>
<h1>Articles</h1>
<ul>
{% for article in articles %}
<li>{{ article.title }} - {{ article.created_at }}</li>
{% endfor %}
</ul>
</body>
</html>
6. Run the Development Server
Start the Django development server:
python manage.py runserver
Visit http://127.0.0.1:8000/ in your browser to see the article list.
Explanation of Key Concepts
1. models.py
○ Defines the structure of your database table using Django's ORM.
○ The Article model includes fields for title, content, and created_at.
2. views.py
○ Handles the logic for fetching data from the database and passing it to the template.
3. urls.py
○ Maps a URL path to a view function.
4. Templates
○ Use Django's templating language to dynamically display data in HTML.
This setup is a foundational Django application demonstrating the MVC (Model-View-Controller) pattern.
Let me know if you'd like more details or want to extend this project!