0% found this document useful (0 votes)
12 views7 pages

Django Todo Guide Full

Uploaded by

barielnenlivinus
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views7 pages

Django Todo Guide Full

Uploaded by

barielnenlivinus
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Complete Django Setup and To-Do App Guide

1. Setting Up Django

1. Install Python: Download Python from https://www.python.org and install it.

2. Create a virtual environment:

python -m venv env

source env/bin/activate (Linux/Mac)

env\Scripts\activate (Windows)

3. Install Django:

pip install django djangorestframework

4. Start a Django project:

django-admin startproject todoproject

cd todoproject

5. Create an app:

python manage.py startapp todo

6. Add 'rest_framework', 'todo', and 'rest_framework.authtoken' to INSTALLED_APPS in settings.py.

7. Run migrations:

python manage.py migrate

8. Start development server:

python manage.py runserver

2. Models and Serializers (with Examples)

Models define your database structure. Example model for a To-Do item:

from django.db import models


from django.contrib.auth.models import User

class ToDo(models.Model):

user = models.ForeignKey(User, on_delete=models.CASCADE)

name = models.CharField(max_length=255)

details = models.TextField()

start_time = models.DateTimeField()

end_time = models.DateTimeField()

completed = models.BooleanField(default=False)

Serializers convert models to JSON. Example using ModelSerializer:

from rest_framework import serializers

from .models import ToDo

class ToDoSerializer(serializers.ModelSerializer):

class Meta:

model = ToDo

fields = '__all__'

Other serialization techniques:

1. Manual Serializer:

class SimpleSerializer(serializers.Serializer):

name = serializers.CharField()

2. Partial field selection:

fields = ['name', 'completed']

3. Nested Serializers for related objects.


4. ReadOnlyField for computed values.

5. Custom create/update methods.

3. Views: CRUD Functions for To-Do App

Views handle logic. Here's a CRUD setup using APIView:

from rest_framework.views import APIView

from rest_framework.response import Response

from rest_framework import status

from .models import ToDo

from .serializers import ToDoSerializer

class ToDoList(APIView):

def get(self, request):

todos = ToDo.objects.filter(user=request.user)

serializer = ToDoSerializer(todos, many=True)

return Response(serializer.data)

def post(self, request):

serializer = ToDoSerializer(data=request.data)

if serializer.is_valid():

serializer.save(user=request.user)

return Response(serializer.data, status=status.HTTP_201_CREATED)

return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

class ToDoDetail(APIView):
def get_object(self, pk):

return ToDo.objects.get(pk=pk)

def put(self, request, pk):

todo = self.get_object(pk)

serializer = ToDoSerializer(todo, data=request.data)

if serializer.is_valid():

serializer.save()

return Response(serializer.data)

return Response(serializer.errors, status=400)

def delete(self, request, pk):

todo = self.get_object(pk)

todo.delete()

return Response(status=204)

4. Routing in Django REST Framework

In Django, URLs are managed using a URL dispatcher.

1. In app/urls.py:

from django.urls import path

from .views import ToDoList, ToDoDetail

urlpatterns = [

path('todos/', ToDoList.as_view(), name='todo-list'),

path('todos/<int:pk>/', ToDoDetail.as_view(), name='todo-detail'),


]

2. In project/urls.py:

from django.contrib import admin

from django.urls import path, include

urlpatterns = [

path('admin/', admin.site.urls),

path('api/', include('todo.urls')),

5. Step-by-Step: Build a To-Do App with User Authentication

1. Set up User Authentication using Django Rest Framework Token Auth:

from rest_framework.authtoken.views import obtain_auth_token

urlpatterns += [

path('auth/', obtain_auth_token),

2. Create User Serializer and View:

from rest_framework.authtoken.models import Token

from rest_framework import generics

from django.contrib.auth.models import User

from rest_framework.permissions import AllowAny

from rest_framework.serializers import ModelSerializer


class UserSerializer(ModelSerializer):

class Meta:

model = User

fields = ['username', 'password']

extra_kwargs = {'password': {'write_only': True}}

class RegisterUser(generics.CreateAPIView):

queryset = User.objects.all()

serializer_class = UserSerializer

permission_classes = [AllowAny]

def perform_create(self, serializer):

user = serializer.save()

Token.objects.create(user=user)

Add to urls.py:

path('register/', RegisterUser.as_view()),

3. Use Token Authentication in settings.py:

REST_FRAMEWORK = {

'DEFAULT_AUTHENTICATION_CLASSES': [

'rest_framework.authentication.TokenAuthentication',

}
4. Models, Serializers, Views, URLs ? all work together for a fully functional to-do app.

You might also like