models.py
models.Model
, field definitions, and metadata.
from django.db import models
class MyModel(models.Model):
my_field = models.CharField(max_length=100)
views.py
from django.http import HttpResponse
from django.views import View
from django.views.generic import TemplateView
def my_view(request):
return HttpResponse("Hello, World!")
class MyView(View):
def get(self, request):
return HttpResponse("Hello, World from Class-Based View!")
class MyTemplateView(TemplateView):
template_name = "base/home.html"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['custom_data'] = "This is custom data"
return context
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('hello-func/', views.my_view, name='my-func-view'),
path('hello-class/', views.MyView.as_view(), name='my-class-view'),
path('', views.MyTemplateView.as_view(), name='home'),
]
templates/
<html>
<head>
<title>My Page</title>
</head>
<body>
<h1>{{ page_title }}</h1>
</body>
</html>
admin.py
from django.contrib import admin
from .models import MyModel
admin.site.register(MyModel)
forms.py
(Optional)
from django import forms
from .models import MyModel
class MyForm(forms.ModelForm):
class Meta:
model = MyModel
fields = ['my_field']
tests.py
from django.test import TestCase
from .models import MyModel
class MyModelTests(TestCase):
def test_str_representation(self):
entry = MyModel(my_field="Test")
self.assertEqual(str(entry), entry.my_field)
static/
(Optional)
/static/
/css/
/js/
/images/
migrations/
/migrations/
0001_initial.py
0002_auto_20230101_1234.py