Django_Notes_Backend_Developer
Django_Notes_Backend_Developer
1. Django Basics
Important Files:
- settings.py: project settings
- urls.py: URL routing
- views.py: request handling
- models.py: database structure
- Django ORM allows interaction with the database using Python objects.
Example Model:
from django.db import models
class Product(models.Model):
name = models.CharField(max_length=100)
price = models.DecimalField(max_digits=5, decimal_places=2)
Migrations:
python manage.py makemigrations
python manage.py migrate
CRUD Operations:
Product.objects.create(name="Item", price=10.99)
Product.objects.all()
Product.objects.get(id=1)
Product.objects.filter(name="Item")
Product.objects.update(price=12.99)
Product.objects.get(id=1).delete()
Views:
from django.http import HttpResponse
def home(request):
return HttpResponse("Hello World")
URL Routing:
Python Notes for Web/Backend Developer Interviews
urlpatterns = [
path('', views.home, name='home'),
]
Types of Views:
- Function-based views (FBV)
- Class-based views (CBV)
4. Templates
Using Template:
return render(request, 'home.html', {'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(forms.Form):
name = forms.CharField()
email = forms.EmailField()
Using ModelForm:
class ProductForm(forms.ModelForm):
class Meta:
model = Product
fields = '__all__'
6. Django Admin
Python Notes for Web/Backend Developer Interviews
Enable Admin:
from django.contrib import admin
from .models import Product
admin.site.register(Product)
Create Superuser:
python manage.py createsuperuser
7. User Authentication
Login:
user = authenticate(username='abhi', password='123')
if user is not None:
login(request, user)
Logout:
logout(request)
Installation:
pip install djangorestframework
Serializers:
from rest_framework import serializers
from .models import Product
class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = '__all__'
Views:
from rest_framework import viewsets
class ProductViewSet(viewsets.ModelViewSet):
queryset = Product.objects.all()
serializer_class = ProductSerializer
Python Notes for Web/Backend Developer Interviews
Routers:
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register(r'products', ProductViewSet)
urlpatterns += router.urls
9. Deployment Tips