# Install virtualenv
pip install virtualenv
# Create a New Virtual Environment
virtualenv venv # On Windows
python3 -m venv venv # On macOS or Linux# Activate the Virtual Environment
venv\Scripts\activate # On Windowssource venv/bin/activate # On macOS or Linux# Installing Packages
pip install django
# Deactivate the Virtual Environment
deactivate
Project and App Setup
# Create a New Django Project
django-admin startproject project_name
# Create a New Django App
python manage.py startapp app_name
# Run Development Server
python manage.py runserver
Models and Databases
## Define a Modelfrom django.db import models
classMyModel(models.Model):
field1 = models.CharField(max_length=100)
field2 = models.IntegerField()# Add more fields as needed## Create Database Tables
python manage.py makemigrations
python manage.py migrate
## Perform Database Queries# Get all objects
MyModel.objects.all()# Filter objects
MyModel.objects.filter(field1='value')# Get a single object
MyModel.objects.get(pk=1)# Create a new object
obj = MyModel(field1='value', field2=123)
obj.save()# Update an object
obj.field1 ='new_value'
obj.save()# Delete an object
obj.delete()
# Create a Formfrom django import forms
classMyForm(forms.Form):
field1 = forms.CharField(max_length=100)
field2 = forms.IntegerField()# Add more fields as needed
<!-- Render a Form in a Template --><formmethod="post">
{% csrf_token %} {{ form.as_p }}
<buttontype="submit">Submit</button></form>
# Handle Form Submission in a Viewfrom django.shortcuts import render, redirect
from.forms import MyForm
defmy_view(request):if request.method =='POST':
form = MyForm(request.POST)if form.is_valid():# Process form datareturn redirect('success-url')else:
form = MyForm()return render(request,'my_template.html',{'form': form})
Authentication
Ensure 'django.contrib.auth' is included in the INSTALLED_APPS.
Use UserCreationForm and AuthenticationForm from 'django.contrib.auth.forms' for registration and login.
# Restrict Access to Viewsfrom django.contrib.auth.decorators import login_required
@login_requireddefmy_protected_view(request):# View code for authenticated users only
# Create Custom MiddlewareclassMyMiddleware:def__init__(self, get_response):
self.get_response = get_response
def__call__(self, request):# Code to be executed for each request before the view (optional)
response = self.get_response(request)# Code to be executed for each request after the view (optional)return response
# Add Middleware to Settings
MIDDLEWARE =[# Other middleware...'myapp.middleware.MyMiddleware',]
A personal blog by Volkan Uyarer. Developer, Lifelong Learner, Tech Enthusiast.