Virtual Environment1. Open the terminal by entering cmd in the path bar of the target folder2. Create: path>python -m venv your_env_name3. Activate: path>your_env_name\Scripts\activate4. Deactivate: (your_env_name) path>deactivateDjango: Web Framework1. Install Django in the virtual environment(your_env_name) path>pip install Django2. Create a project(your_env_name) path>django-admin startproject project_name . Commanddir to view the directory under the path Filemanage.py for managing the database and running the server Commanddir project_name to view the directory under the folder3. Create the database(your_env_name) path>python manage.py migrate4. Run tests(your_env_name) path>python manage.py runserver Webpagehttp://localhost:8000/ TerminalCtrl+C to stop the test5. Create an application(your_env_name) path>python manage.py startapp app_name Filemodels.py for basic model functionality In project_folder\settings.py add ‘app_name’ to INSTALLED_APPS6. Create a user application(your_env_name) path>python manage.py startapp users In project_folder\settings.py add ‘users’ to INSTALLED_APPS7. Modify the database In app_folder\models.py modify or add model classes(your_env_name) path>python manage.py makemigrations app_name(your_env_name) path>python manage.py migrate8. Rebuild the database(your_env_name) path>python manage.py flush9. Create a superuser(your_env_name) path>python manage.py createsuperuser Webpagehttp://localhost:8000/admin/10. Register custom models with the admin site In app_folder\admin.py addfrom app_name.models import ModelClassNameadmin.site.register(ModelClassName)11. Use the interactive terminal to view data(your_env_name) path>python manage.py shell TerminalCtrl+Z, Enter to end the session
>>>from learning_logs.models import Topic
>>>Topic.objects.all()# Returns a list (QuerySet) <QuerySet [<Topic:Chess>,<Topic:Rock Climbing>]>>>>Topic.objects.order_by('date_added')# Returns a QuerySet ordered by date
>>>t=Topic.objects.get(id=1)# View properties of the model with id=1
>>>t.text# Get the text property 'Chess'
>>>t.date_added# Get the date property datetime.datetime(2025,8,4,9,51,32,69210,tzinfo=datetime.timezone.utc)
>>>t.entry_set.all()# Returns entries associated with the topic <QuerySet [<Entry:...>,<Entry:...>]
12.models.pyclass Abc(models.Model): Inherit modelmodels.CharField() to store short text max_length maximum character length null=False allows null values blank=False allows empty values in forms default default value unique=False uniqueness constraintmodels.EmailField() validates email format for short textmodels.URLField() validates URL format for short textmodels.TextField() stores long textmodels.IntegerField() stores integersmodels.FloatField() stores floating-point numbersmodels.BooleanField() stores boolean valuesmodels.DateTimeField() stores date and time auto_now=True records the update time auto_now_add=True records the creation timemodels.ForeignKey(to, on_delete) foreign key representing a many-to-one relationship to associated model Associate with User from django.contrib.auth.models import User on_delete cascading delete rules model.CASCADE cascade delete model.PROTECT prevents deletion model.SET_NULL sets to null (null=True) model.SET_DEFAULT sets to default value (default=*) model.SET() custom logic model.DO_NOTHING lets the database handle it related_name=None reverse query name related_query_name=None reverse query field name limit_choices_to=None limit selectable options to_field=None specify foreign key field db_constraint=True create database foreign key constraint db_index=True create index editable=True allows editing null=False allows null values blank=False allows empty values unique=False uniqueness constraint help_text=” help text verbose_name=None display name in admin error_messages=None custom error messagesclass Meta: plural=’entries’ nested extra informationdef __str__(self): return self.text displays full text return self.text[:50]+”…” displays text within 50 characters13. Web Framework
'''urls.py file urlpatterns list example'''# View function
from my_app import views
path('', views.home, name='home')# Class-based view
from other_app.views import Home
path('', Home.as_view(), name='home')# Include other URLs
from django.urls import include, path
path('blog/', include('blog.urls'))
URL Mapping: The urlpatterns list in project_folder\urls.py includes other URLs
from django.urls import include, path# Import include, path
#admin.site.urls defines all URLs requested in the admin site
path('admin/', admin.site.urls)
#apps.urls maps the urls.py file of apps folder
#namespace parameter distinguishes apps' URLs from other URLs in the project
path('', include(('apps.urls', 'apps'), namespace='apps'))
path('users/', include(('users.urls', 'users'), namespace='users'))
Define URLs: In app_folder\urls.py the urlpatterns list directs to view functions
from django.urls import path, re_path# Import path, re_path
from . import views# The dot imports views from the current folder
from django.contrib.auth.views import LoginView# Import login view
#views.home maps to the home function in views.py
#http://localhost:8000/path('', views.home, name='home')
#http://localhost:8000/home/path('home/', views.home, name='home')
#http://localhost:8000/homes/2/path('homes/<int:home_id>/', views.home, name='home')
#users\urls.py\urlpatterns list
#LoginView.as_view class view maps the internal template_name parameter
#http://localhost:8000/users/login/path('login/', LoginView.as_view(template_name='users/login.html'), name='login')
# Use logout_view function to distinguish from logout function
#http://localhost:8000/users/logout/path('logout/', view.logout_view, name='logout')
Write Views: Define functions in app_folder\views.py
from django.shortcuts import render# Import render
from .models import Topic# Import Topic class from the current folder's models.py
# Import Http response redirect, redirect to a specified page after form submission
from django.http import HttpResponseRedirect
from django.http import Http404# 404 response
from django.urls import reverse# Import reverse, determine URL from specified URL pattern
from django.contrib.auth import logout# Import logout function
from django.contrib.auth import login, authenticate# Login, authentication
from django.contrib.auth.forms import UserCreationForm# User registration form
from django.contrib.auth.decorators import login_required# Require login status
# Restrict login status, redirect to login page if not logged in
# You can add LOGIN_URL='/users/login/' at the end of project_folder\settings.py
@login_required
def home(request):# Parameter request corresponds to the original request
Topic.objects.all()# Returns QuerySet
Topic.objects.order_by('date_added')# Returns QuerySet ordered by date
# filter filter, only get QuerySet for specified user
Topic.objects.filter(owner=request.user).order_by('date_added')
t=Topic.objects.get(id=2)# Returns model with id=2
t.text# Returns text
t.date_added# Returns timestamp
t.entry_set.all()# Returns all entries associated with the topic
t.entry_set.order_by('-date_added')# Returns entries ordered by date in descending order
# Confirm that the requested topic belongs to the current user
if topic.owner != request.user:
raise Http404# raise exception statement, return 404 error page
logout(request)# User logout
# The form first checks the web type, POST requires form submission, GET only reads data
# Check request method, if not POST, it's an empty form, if POST, it's a filled form
if request.method != 'POST':
form=TopicForm()# Empty form instance
form=TopicForm(instance=entry)# Example parameter original content
else:
# request.POST returns user input data
form=TopicForm(request.POST)# Filled form instance
form=TopicForm(instance=entry, data=request.POST)# Modified form
# is_valid function can verify that required fields are filled and match the required field types
if form.is_valid():
form.save()# Save data from the form to the database
# Parameter commit does not submit save, first associate topic then save to database
entry=form.save(commit=False)
entry.topic=topic
entry.save()# Login verifies the same username and password as the registered form
new_user=form.save()
auth_user=authenticate(username=new_user.username, password=request.POST['password2'])
login(request, auth_user)
# reverse function can get the URL of apps/topics.html
# reverse parameter args list contains all parameters in the URL [topic_id]
# HttpResponseRedirect redirects to the page topics.html
return HttpResponseRedirect(reverse('apps:topics'))
context={'topics':topics}# Context dictionary, name: data
# Return data rendering for the requested page of the html template
# Parameter context can display data
return render(request, 'apps/home.html', [context])
Write Templates: In app_folder\templates\app_name\html files
<p>Paragraph text content</p><!-- a link to the internal apps/home.html URL --><a href="{% url 'apps:home' %}">Link Text</a><!-- Define URL requiring parameter home_id, can add attribute home.id --><a href="{% url 'apps:home' home.id %}">{{ home }}</a><!-- ul unordered list, bullet point numbering, li list element --><ul><li>List Element</li></ul><!-- for iterate over list output elements, empty if the list is empty, must end with endfor -->{% for topic in topics %} {{ topic }}<!-- Variable uses double curly braces --> <!-- Pipe is a filter, modifies the variable --> {{ entry.date_added|date:'M d, Y H:i' }} <!-- linebreaks automatically wrap according to window --> {{ entry.text|linebreaks }}{% empty %}{% endfor %}<!-- if judgment -->{% if form.errors %}<!-- Form error attributes are set -->{% else %}{% endif %}<!-- user.is_authenticated authentication, logged in True, not logged in False -->{% if user.is_authenticated %} {{ user.username }}<!-- Username --><!-- from form --><!-- Parameter action form data sent to internal apps/home.html URL --><!-- Parameter method submits data in POST request --><form action="{% url 'apps:home' %}" method='post'> <!-- Prevent cross-site request forgery (access unauthorized pages using forms) --> {% csrf_token %} <!-- Modifier as_p renders all form elements in paragraph format --> {{ form.as_p }} <!-- input input box, / slash shows hint on mouse hover --><!-- Parameter type hidden, name next, value redirects after successful login --><input type="hidden" name="next" value="{% url 'apps:index' %}" /></form><!-- button button, name submit form --><button name="submit">Button Text</button>
<!-- Content placeholder block in parent template base.html -->{% block content %}{% endblock content %}<!-- Child template inherits content from apps/base.html -->{% extends "apps/base.html" %}{% block content %}Details unique to the child template{% endblock content %}
Forms: In app_name\forms.py
from django import forms# Import forms
from .models import Topic, Entry# Import classes from models.py in the current folder
class EntryForm(forms.ModelForm):# Inherit ModelForm class class Meta:# Nested extra information model=Entry# Create form based on model fields={'text'}# Field types labels={'text':''}# Labels generated for fields # widget a form element, such as single-line text box, multi-line text area, drop-down list # Override default widgets by setting attributes widgets # forms.Textarea text area attrs attribute cols width 80 columns widgets={'text':forms.Textarea(attrs={'cols':80})}
‘”Documentation”’https://docs.djangoproject.com/en/5.2/