Junior
Name the main entities in Django.
sobes.tech AI
Answer from AI
- Project: A set of configurations and applications for a website.
- App: A self-contained module for performing a specific task or a set of related functions. Contains models, views, URLs, and migrations.
- Models: Define the data structure. They are classes that inherit from
django.db.models.Model, with each variable representing a database table field. ActiveRecord pattern.// models.py from django.db import models class Product(models.Model): name = models.CharField(max_length=100) price = models.DecimalField(max_digits=10, decimal_places=2) def __str__(self): return self.name - Views: Functions or classes that handle HTTP requests, interact with models, and return HTTP responses (usually HTML pages).
// views.py from django.shortcuts import render from .models import Product def product_list(request): products = Product.objects.all() return render(request, 'products/product_list.html', {'products': products}) - Templates: Files containing static HTML and special syntax for dynamic content (template tags and variables). Used by views to generate HTTP responses.
<!-- products/product_list.html --> <h1>Product List</h1> <ul> {% for product in products %} <li>{{ product.name }} - ${{ product.price }}</li> {% endfor %} </ul> - URLs: Map URLs to views. Defined in
urls.pyfiles.// urls.py from django.urls import path from . import views urlpatterns = [ path('products/', views.product_list, name='product_list'), ] - Forms: Handle user input. Provide classes for creating HTML forms, validating data, and saving to models.
// forms.py from django import forms from .models import Product class ProductForm(forms.ModelForm): class Meta: model = Product fields = ['name', 'price'] - Migrations: Changes to the database schema based on models. Managed with
makemigrationsandmigratecommands.
These entities work together in a pattern similar to MVC, where Models are data, Views are request handling logic, and Templates are the presentation layer (UI). Django is often described as MVT (Model-View-Template).