Welcome back to CodeYourCraft! Today, we're diving deep into Django's app structure. If you're new here, don't worry, we'll start from the ground up and explain everything you need to know. By the end of this lesson, you'll be able to create your own Django applications with confidence! π
Every Django application is built around reusable applications, each containing a specific functionality. The structure of a Django app is organized in a way that promotes modularity, making it easy to manage and scale your projects. π‘
Before we dive into the app structure, let's create a new Django app. Open your terminal and type:
$ cd myproject
$ python manage.py startapp myappReplace myproject with your project's name, and myapp with the name of the app you want to create.
Now, let's explore the structure of our new app.
Navigate to the app directory by running:
$ cd myappHere's a breakdown of the app's directory structure:
migrations/: Contains all the database migrations.static/: Stores static files like CSS, JavaScript, and images.templates/: Holds HTML templates for rendering dynamic content.__init__.py: The file that tells Python this is a Python package.admin.py: Configures the administrative interface.models.py: Defines the database schema and data models.tests.py: Contains tests for the app.views.py: Handles the app's URLs and rendering of templates.Let's take a closer look at each of these components.
Models in Django represent the database schema and define the relationships between tables.
# myapp/models.py
from django.db import models
class MyModel(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
def __str__(self):
return self.nameViews in Django are responsible for rendering templates and handling user requests.
# myapp/views.py
from django.shortcuts import render
from .models import MyModel
def my_view(request):
my_models = MyModel.objects.all()
context = {'my_models': my_models}
return render(request, 'my_template.html', context)Templates are HTML files that are dynamically rendered by Django. They can contain dynamic content and can be reused across different views.
<!-- myapp/templates/myapp/my_template.html -->
{% for model in my_models %}
<h1>{{ model.name }}</h1>
<p>{{ model.description }}</p>
{% endfor %}What is the purpose of the `__init__.py` file in a Django app?
We've covered the basic structure of a Django app and explored important components like models, views, and templates. In the next lesson, we'll dive deeper into Django's ORM and learn how to work with databases.
Stay tuned and happy coding! π