Junior — Middle
Could you tell how you implemented the MVC pattern in a Django project?
sobes.tech AI
Answer from AI
In Django, the MVC pattern is implemented as MTV (Model-Template-View), where:
- Model — describes the data structure and business logic, usually through model classes in
models.py. - Template — responsible for displaying data, it is an HTML template with the ability to insert dynamic content.
- View — handles requests, interacts with models, and passes data to templates.
Example implementation:
# 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)
# views.py
from django.shortcuts import render
from .models import Product
def product_list(request):
products = Product.objects.all()
return render(request, 'products/list.html', {'products': products})
# templates/products/list.html
{% for product in products %}
<p>{{ product.name }} — {{ product.price }}</p>
{% endfor %}
Thus, the logic is divided into three parts, which simplifies maintenance and development of the application.