Python Notes for Web/Backend Developer Interviews
1. Django Basics
- Django is a high-level Python web framework for rapid development.
- Follows the MTV pattern (Model-Template-View).
- Commands to start project:
django-admin startproject projectname
python [Link] startapp appname
Important Files:
- [Link]: project settings
- [Link]: URL routing
- [Link]: request handling
- [Link]: database structure
2. Models and ORM
- Django ORM allows interaction with the database using Python objects.
Example Model:
from [Link] import models
class Product([Link]):
name = [Link](max_length=100)
price = [Link](max_digits=5, decimal_places=2)
Migrations:
python [Link] makemigrations
python [Link] migrate
CRUD Operations:
[Link](name="Item", price=10.99)
[Link]()
[Link](id=1)
[Link](name="Item")
[Link](price=12.99)
[Link](id=1).delete()
3. Views and URLs
Views:
from [Link] import HttpResponse
def home(request):
return HttpResponse("Hello World")
URL Routing:
Python Notes for Web/Backend Developer Interviews
from [Link] import path
from . import views
urlpatterns = [
path('', [Link], name='home'),
]
Types of Views:
- Function-based views (FBV)
- Class-based views (CBV)
4. Templates
- Django uses a templating engine to render dynamic HTML.
Using Template:
return render(request, '[Link]', {'name': 'Abhinav'})
Template Tags:
{{ variable }}
{% if user.is_authenticated %}
{% for item in items %}
{% csrf_token %}
5. Forms
Django Forms:
from django import forms
class ContactForm([Link]):
name = [Link]()
email = [Link]()
Handling Form in Views:
if [Link] == 'POST':
form = ContactForm([Link])
if form.is_valid():
# process form data
Using ModelForm:
class ProductForm([Link]):
class Meta:
model = Product
fields = '__all__'
6. Django Admin
Python Notes for Web/Backend Developer Interviews
- Powerful admin interface for managing models
Enable Admin:
from [Link] import admin
from .models import Product
[Link](Product)
Create Superuser:
python [Link] createsuperuser
7. User Authentication
Built-in User Auth:
- Login, logout, password change, reset
from [Link] import authenticate, login, logout
Login:
user = authenticate(username='abhi', password='123')
if user is not None:
login(request, user)
Logout:
logout(request)
8. Django REST Framework (DRF)
Installation:
pip install djangorestframework
Serializers:
from rest_framework import serializers
from .models import Product
class ProductSerializer([Link]):
class Meta:
model = Product
fields = '__all__'
Views:
from rest_framework import viewsets
class ProductViewSet([Link]):
queryset = [Link]()
serializer_class = ProductSerializer
Python Notes for Web/Backend Developer Interviews
Routers:
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
[Link](r'products', ProductViewSet)
urlpatterns += [Link]
9. Deployment Tips
- Use gunicorn + nginx for production
- Use PostgreSQL in production
- Set DEBUG = False
- Configure ALLOWED_HOSTS
- Use environment variables for secrets