pip install django
django-admin startproject myproject
cd myproject
python manage.py startapp myapp
python manage.py runserver
python manage.py migrate
manage.py
: Command-line utility for administrative tasksmyproject/
: Project directory
__init__.py
: Empty file that tells Python this directory is a packagesettings.py
: Project settings/configurationurls.py
: Project URL declarationsasgi.py
: Entry-point for ASGI-compatible web serverswsgi.py
: Entry-point for WSGI-compatible web serversmyapp/
: Application directory
migrations/
: Database migrations__init__.py
: Empty file that tells Python this directory is a packageadmin.py
: Admin interface configurationapps.py
: App configurationmodels.py
: Data modelstests.py
: Unit testsviews.py
: View functionsfrom django.db import models
class Person(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
birth_date = models.DateField()
def __str__(self):
return f"{self.first_name} {self.last_name}"
person = Person(first_name="John", last_name="Doe", birth_date="1990-01-01")
person.save()
# Get all persons
all_persons = Person.objects.all()
# Filter persons
johns = Person.objects.filter(first_name="John")
# Get a single person
try:
person = Person.objects.get(id=1)
except Person.DoesNotExist:
print("Person not found")
from django.shortcuts import render
from django.http import HttpResponse
def hello_world(request):
return HttpResponse("Hello, World!")
def person_detail(request, person_id):
person = Person.objects.get(id=person_id)
return render(request, 'person_detail.html', {'person': person})
from django.views import View
from django.views.generic import ListView, DetailView
class PersonList(ListView):
model = Person
template_name = 'person_list.html'
context_object_name = 'persons'
class PersonDetail(DetailView):
model = Person
template_name = 'person_detail.html'
context_object_name = 'person'
from django.urls import path
from . import views
urlpatterns = [
path('', views.hello_world, name='hello_world'),
path('person/<int:person_id>/', views.person_detail, name='person_detail'),
path('persons/', views.PersonList.as_view(), name='person_list'),
path('person/<int:pk>/', views.PersonDetail.as_view(), name='person_detail'),
]
<!DOCTYPE html>
<html>
<head>
<title>{{ person.first_name }} {{ person.last_name }}</title>
</head>
<body>
<h1>{{ person.first_name }} {{ person.last_name }}</h1>
<p>Birth Date: {{ person.birth_date }}</p>
</body>
</html>
<!-- base.html -->
<!DOCTYPE html>
<html>
<head>
<title>{% block title %}My Site{% endblock %}</title>
</head>
<body>
{% block content %}
{% endblock %}
</body>
</html>
<!-- person_detail.html -->
{% extends "base.html" %}
{% block title %}{{ person.first_name }} {{ person.last_name }}{% endblock %}
{% block content %}
<h1>{{ person.first_name }} {{ person.last_name }}</h1>
<p>Birth Date: {{ person.birth_date }}</p>
{% endblock %}
from django import forms
from .models import Person
class PersonForm(forms.ModelForm):
class Meta:
model = Person
fields = ['first_name', 'last_name', 'birth_date']
from django.shortcuts import render, redirect
from .forms import PersonForm
def create_person(request):
if request.method == 'POST':
form = PersonForm(request.POST)
if form.is_valid():
form.save()
return redirect('person_list')
else:
form = PersonForm()
return render(request, 'create_person.html', {'form': form})
from django.contrib import admin
from .models import Person
admin.site.register(Person)
from django.contrib import admin
from .models import Person
@admin.register(Person)
class PersonAdmin(admin.ModelAdmin):
list_display = ('first_name', 'last_name', 'birth_date')
list_filter = ('birth_date',)
search_fields = ('first_name', 'last_name')
python manage.py makemigrations
python manage.py migrate
from django.db import connection
def my_custom_sql():
with connection.cursor() as cursor:
cursor.execute("SELECT * FROM myapp_person WHERE birth_date > %s", [date(1990, 1, 1)])
row = cursor.fetchone()
return row
from django.contrib.auth import authenticate, login
from django.shortcuts import render, redirect
def user_login(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect('home')
else:
return render(request, 'login.html', {'error': 'Invalid credentials'})
return render(request, 'login.html')
from django.contrib.auth import logout
from django.shortcuts import redirect
def user_logout(request):
logout(request)
return redirect('home')
from django.contrib.auth.decorators import login_required
@login_required
def protected_view(request):
return render(request, 'protected.html')
# settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = [
BASE_DIR / "static",
]
{% load static %}
<img src="{% static 'images/logo.png' %}" alt="Logo">
<link rel="stylesheet" href="{% static 'css/style.css' %}">
from django.test import TestCase
from .models import Person
class PersonModelTest(TestCase):
def setUp(self):
Person.objects.create(first_name="John", last_name="Doe", birth_date="1990-01-01")
def test_person_creation(self):
person = Person.objects.get(first_name="John")
self.assertEqual(person.last_name, "Doe")
python manage.py test
# settings.py
DEBUG = False
ALLOWED_HOSTS = ['www.example.com']
# Security settings
SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
python manage.py collectstatic
gunicorn myproject.wsgi:application
2024 © All rights reserved - buraxta.com