杰瑞科技汇

Python Django demo怎么快速入门?

Of course! Here is a complete, step-by-step guide to creating a simple Django "To-Do List" demo application. This will cover everything from setting up the project to deploying it locally.

Python Django demo怎么快速入门?-图1
(图片来源网络,侵删)

What We'll Build

A simple web application where you can:

  1. View a list of all to-do items.
  2. Add a new to-do item.
  3. Mark an item as complete.
  4. Delete an item.

Prerequisites

  • Python 3 installed on your system.
  • pip (Python's package installer), which usually comes with Python.
  • A code editor (like VS Code, PyCharm, or Sublime Text).

Step 1: Project Setup

First, let's create a virtual environment. This is a best practice to keep your project's dependencies isolated.

  1. Create a project directory:

    mkdir django_todo_demo
    cd django_todo_demo
  2. Create and activate a virtual environment:

    Python Django demo怎么快速入门?-图2
    (图片来源网络,侵删)
    • On macOS/Linux:
      python3 -m venv venv
      source venv/bin/activate
    • On Windows:
      python -m venv venv
      .\venv\Scripts\activate

      You'll know it's active because your command prompt will be prefixed with (venv).

  3. Install Django:

    pip install Django
  4. Create the Django project and app:

    • A project is the entire website.
    • An app is a self-contained module within a project (e.g., a blog, a store, a to-do list).
    # Create the project (the period '.' at the end is important!)
    django-admin startproject myproject .
    # Create our to-do app
    python manage.py startapp todos

Your directory structure should now look like this:

Python Django demo怎么快速入门?-图3
(图片来源网络,侵删)
django_todo_demo/
├── venv/
├── myproject/
│   ├── __init__.py
│   ├── asgi.py
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
├── todos/
│   ├── __init__.py
│   ├── admin.py
│   ├── apps.py
│   ├── migrations/
│   ├── models.py
│   ├── tests.py
│   └── views.py
└── manage.py

Step 2: Configure the Project

We need to tell our project about the todos app.

  1. Edit myproject/settings.py: Open myproject/settings.py and add 'todos' to the INSTALLED_APPS list.

    # myproject/settings.py
    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'todos',  # Add our new app here
    ]

Step 3: Create the Data Model (The "Blueprint")

A model is the single, definitive source of information about your data. It contains the essential fields and behaviors of the data you’re storing.

  1. Edit todos/models.py: This file defines the structure of our to-do items.

    # todos/models.py
    from django.db import models
    class TodoItem(models.Model):
        title = models.CharField(max_length=200)
        completed = models.BooleanField(default=False)
        created_at = models.DateTimeField(auto_now_add=True)
        def __str__(self):
            return self.title
    • title: A text field for the task description.
    • completed: A boolean to track if the task is done.
    • created_at: A timestamp that's automatically set when the item is created.
    • __str__: A human-readable representation of the object, useful in the admin panel.
  2. Create and apply database migrations: Django needs to translate our Python model into actual database tables.

    python manage.py makemigrations
    python manage.py migrate

Step 4: Create the Views (The "Logic")

Views are Python functions that take a web request and return a web response. They contain the logic for what data to display.

  1. Edit todos/views.py: We'll create a few views: one to list all todos, one to add a new one, one to toggle completion, and one to delete one.

    # todos/views.py
    from django.shortcuts import render, redirect
    from .models import TodoItem
    def todo_list(request):
        # Get all todo items, order them by creation date (newest first)
        todos = TodoItem.objects.order_by('-created_at')
        # The context dictionary passes data to the template
        context = {
            'todos': todos
        }
        # Render the template and pass the context
        return render(request, 'todos/todo_list.html', context)
    def add_todo(request):
        if request.method == 'POST':
            # Get the title from the form submission
            title = request.POST.get('title')
            if title: # Ensure title is not empty
                # Create a new TodoItem and save it to the database
                TodoItem.objects.create(title=title)
        # Redirect back to the todo list page
        return redirect('todo_list')
    def toggle_todo(request, todo_id):
        # Get the specific todo item by its ID
        todo = TodoItem.objects.get(pk=todo_id)
        # Toggle the completed status
        todo.completed = not todo.completed
        todo.save()
        # Redirect back to the todo list page
        return redirect('todo_list')
    def delete_todo(request, todo_id):
        # Get the specific todo item by its ID and delete it
        todo = TodoItem.objects.get(pk=todo_id)
        todo.delete()
        # Redirect back to the todo list page
        return redirect('todo_list')

Step 5: Create Templates (The "Frontend")

Templates are the HTML files that define the structure of your pages. Django uses its template engine to render these files with dynamic data.

  1. Create the template directory and file: Django looks for templates inside a templates folder within your app.

    mkdir -p todos/templates/todos
  2. Create todos/templates/todos/todo_list.html: This file will display our list of todos and the form to add new ones.

    <!-- todos/templates/todos/todo_list.html -->
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Django To-Do List</title>
        <style>
            body { font-family: sans-serif; max-width: 600px; margin: 40px auto; background-color: #f4f4f9; color: #333; }
            h1 { color: #4a4a4a; }
            ul { list-style: none; padding: 0; }
            li { background: #fff; padding: 15px; margin-bottom: 10px; border-radius: 5px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); display: flex; justify-content: space-between; align-items: center; }
            li.completed { text-decoration: line-through; color: #888; }
            form { display: flex; margin-bottom: 20px; }
            input[type="text"] { flex-grow: 1; padding: 10px; border: 1px solid #ddd; border-radius: 5px 0 0 5px; }
            button { padding: 10px 15px; border: none; background-color: #5c67f2; color: white; cursor: pointer; border-radius: 0 5px 5px 0; }
            button.delete { background-color: #e74c3c; border-radius: 5px; padding: 5px 10px; }
        </style>
    </head>
    <body>
        <h1>My To-Do List</h1>
        <!-- Form to add a new todo -->
        <form action="{% url 'add_todo' %}" method="post">
            {% csrf_token %}
            <input type="text" name="title" placeholder="Add a new task..." required>
            <button type="submit">Add</button>
        </form>
        <!-- List of todos -->
        <ul>
            {% for todo in todos %}
                <li class="{% if todo.completed %}completed{% endif %}">
                    <span>{{ todo.title }}</span>
                    <div>
                        <a href="{% url 'toggle_todo' todo.id %}">✓</a>
                        <a href="{% url 'delete_todo' todo.id %}" class="delete">🗑️</a>
                    </div>
                </li>
            {% empty %}
                <li>No tasks yet. Add one above!</li>
            {% endfor %}
        </ul>
    </body>
    </html>
    • {% csrf_token %}: A crucial security feature in Django forms.
    • {% for todo in todos %} ... {% endfor %}: A loop to iterate through the todos passed from our view.
    • {% if todo.completed %} ... {% endif %}: A conditional to apply styling.
    • {% url 'add_todo' %}: Generates the URL for the add_todo view.

Step 6: Configure URLs (The "Address Book")

URLs map a web address to a specific view.

  1. Create todos/urls.py: Create a new file for the app's URLs.

    touch todos/urls.py

    And add the following content:

    # todos/urls.py
    from django.urls import path
    from . import views
    urlpatterns = [
        # URL for the main todo list page
        path('', views.todo_list, name='todo_list'),
        # URL for adding a new todo
        path('add/', views.add_todo, name='add_todo'),
        # URL for toggling a todo's completion status
        path('toggle/<int:todo_id>/', views.toggle_todo, name='toggle_todo'),
        # URL for deleting a todo
        path('delete/<int:todo_id>/', views.delete_todo, name='delete_todo'),
    ]
    • name='...': This gives the URL a unique name, which we can use in templates with {% url 'name' %}.
  2. Include the app's URLs in the main project: Edit myproject/urls.py to include the URLs from our todos app.

    # myproject/urls.py
    from django.contrib import admin
    from django.urls import path, include  # Make sure to import 'include'
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('', include('todos.urls')),  # Include the todos app's URLs
    ]

Step 7: Run the Server!

We're all set. Let's run the development server and see our demo in action.

  1. Run the server:

    python manage.py runserver
  2. Visit your application: Open your web browser and go to http://127.0.0.1:8000/.

You should see your to-do list! You can add items, mark them as complete, and delete them.


Bonus: Add the App to the Admin Panel

Django has a built-in admin interface, which is incredibly useful for managing your data.

  1. Create a superuser:

    python manage.py createsuperuser

    Follow the prompts to create a username and password.

  2. Register the model in the admin: Edit todos/admin.py:

    # todos/admin.py
    from django.contrib import admin
    from .models import TodoItem
    admin.site.register(TodoItem)
  3. Access the admin panel: Run the server again (if it's not running) and visit http://127.0.0.1:8000/admin/. Log in with the superuser credentials you just created. You'll now be able to see, add, edit, and delete your TodoItems directly from the admin panel.

Congratulations! You've built a fully functional Django application from scratch. This demo covers the fundamental concepts of Django: Models, Views, Templates, and URLs (MTV pattern).

分享:
扫描分享到社交APP
上一篇
下一篇