<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Sarah Hudaib</title>
    <description>The latest articles on DEV Community by Sarah Hudaib (@sarahhudaib).</description>
    <link>https://dev.to/sarahhudaib</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F930060%2F0bd8c818-726b-43e5-839b-b9a69f620405.png</url>
      <title>DEV Community: Sarah Hudaib</title>
      <link>https://dev.to/sarahhudaib</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/sarahhudaib"/>
    <language>en</language>
    <item>
      <title>Testing and Modules</title>
      <dc:creator>Sarah Hudaib</dc:creator>
      <pubDate>Wed, 18 Jan 2023 07:50:17 +0000</pubDate>
      <link>https://dev.to/sarahhudaib/testing-and-modules-a3a</link>
      <guid>https://dev.to/sarahhudaib/testing-and-modules-a3a</guid>
      <description>&lt;h2&gt;
  
  
  What are Unit tests and TDD?
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Unit tests:
&lt;/h3&gt;

&lt;p&gt;Unit tests are some pieces of code that exercise the input, the output, and the behavior of your code.&lt;/p&gt;

&lt;h3&gt;
  
  
  TDD tests:
&lt;/h3&gt;

&lt;p&gt;Test-Driven Development is a strategy that entails first thinking about (and writing!) tests.&lt;/p&gt;

&lt;h2&gt;
  
  
  Baby Steps:
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;what is the smaller test that we can do against a function?
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;  &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;test_should_return_female_when_the_name_is_from_female_gender&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt;
    &lt;span class="n"&gt;detector&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;GenderDetector&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
    &lt;span class="n"&gt;expected_gender&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;detector&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;run&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="err"&gt;‘&lt;/span&gt;&lt;span class="n"&gt;Ana&lt;/span&gt;&lt;span class="err"&gt;’&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;assert&lt;/span&gt; &lt;span class="n"&gt;expected_gender&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="err"&gt;‘&lt;/span&gt;&lt;span class="n"&gt;female&lt;/span&gt;&lt;span class="err"&gt;’&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;&lt;p&gt;There are some details to pay attention. The first one is the test name. The tests can be considered as your live documentation.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The test file name should follow the same name as the module name.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;It’s ideal to separate the tests folder from the production code (the implementation)&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Another thing to care about is the structure. A convention widely used is the &lt;code&gt;AAA&lt;/code&gt;: &lt;strong&gt;Arrange, Act and Assert&lt;/strong&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;blockquote&gt;
&lt;blockquote&gt;
&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Arrange: you need to organize the data needed to execute that piece of code (input)&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Act: here you will execute the code being tested (exercise the behaviour)&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Assert: after executing the code, you will check if the result (output) is the same as you were expecting&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/blockquote&gt;


&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  The Cycle:
&lt;/h2&gt;

&lt;h3&gt;
  
  
  The cycle is made by three steps:
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;🆘 Write a unit test and make it fail (it needs to fail because the feature isn’t there, right? If this test passes, call the Ghostwriters, really)&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;✅ Write the feature and make the test pass! (you can dance after that)&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;🔵 Refactor the code — the first version doesn’t need to be the beautiful one (don’t be shy)&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Takeaways
&lt;/h2&gt;

&lt;h3&gt;
  
  
  &lt;a href="https://code.likeagirl.io/in-tests-we-trust-tdd-with-python-af69f47e6932" rel="noopener noreferrer"&gt;To remember:&lt;/a&gt;
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;The greatest advantage of TDD is to craft the software design first.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Your code will be more reliable: after a change, you can run your tests and be in peace.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The beginning may be hard — and that’s fine. You just need to practice!&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>mentalhealth</category>
      <category>discuss</category>
    </item>
    <item>
      <title>How to create a REST API with Django REST framework</title>
      <dc:creator>Sarah Hudaib</dc:creator>
      <pubDate>Wed, 18 Jan 2023 07:46:21 +0000</pubDate>
      <link>https://dev.to/sarahhudaib/how-to-create-a-rest-api-with-django-rest-framework-4e08</link>
      <guid>https://dev.to/sarahhudaib/how-to-create-a-rest-api-with-django-rest-framework-4e08</guid>
      <description>&lt;h2&gt;
  
  
  What is a REST API?
&lt;/h2&gt;

&lt;p&gt;A &lt;code&gt;REST&lt;/code&gt; API is a popular way for systems to expose useful functions and data. REST, which stands for representational state transfer, can be made up of one or more resources that can be accessed at a given URL and returned in various formats, like JSON, images, HTML, and more.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why Django REST framework?
&lt;/h2&gt;

&lt;p&gt;Django REST framework (DRF) is a powerful and flexible toolkit for building Web APIs. Its main benefit is that it makes serialization much easier.&lt;/p&gt;

&lt;p&gt;Django REST framework is based on Django’s class-based views, so it’s an excellent option if you’re familiar with Django. It adopts implementations like class-based views, forms, model validator, QuerySet, and more.&lt;/p&gt;

&lt;h2&gt;
  
  
  Setting up Django REST framework
&lt;/h2&gt;

&lt;p&gt;Ideally, you’d want to create a virtual environment to isolate dependencies, however, this is optional. Run the command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;python -m venv django_env
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;from inside your projects folder to create the virtual environment. Then, run this command to turn it on.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;source ./django_env/bin/activate
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Keep in mind that you’ll need to reactivate your virtual environment in every new terminal session. You’ll know that it is turned on because the environment’s name will become part of the shell prompt.&lt;/p&gt;

&lt;p&gt;Navigate to an empty folder in your terminal and install Django and Django REST framework in your project with the commands below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;pip install django
pip install django_rest_framework
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Create a Django project called &lt;code&gt;todo&lt;/code&gt; with the following command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;django-admin startproject todo
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then, &lt;code&gt;cd&lt;/code&gt; into the new &lt;code&gt;todo&lt;/code&gt; folder and create a new app for your API:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;django-admin startapp todo_api
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Run your initial migrations of the built-in user model:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;python manage.py migrate
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next, add &lt;code&gt;rest_framework&lt;/code&gt; and &lt;code&gt;todo&lt;/code&gt; to the INSTALLED_APPS inside the &lt;code&gt;todo/todo/settings.py&lt;/code&gt; file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'todo_api'
]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Create a &lt;code&gt;serializers.py&lt;/code&gt; and &lt;code&gt;urls.py&lt;/code&gt; file in &lt;code&gt;todo/todo_api&lt;/code&gt; and add new files as configured in the directory structure below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;├── todo
│   ├── __init__.py
│   ├── settings.py
│   ├── urls.py
├── db.sqlite3
├── manage.py
└── todo_api
    ├── admin.py
    ├── serializers.py
    ├── __init__.py
    ├── models.py
    ├── urls.py
    └── views.py
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Be sure to include &lt;code&gt;rest_framework&lt;/code&gt; and URLs as shown below in your main &lt;code&gt;urls.py&lt;/code&gt; file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# todo/todo/urls.py : Main urls.py
from django.contrib import admin
from django.urls import path, include
from todo_api import urls as todo_urls

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api-auth/', include('rest_framework.urls')),
    path('todos/', include(todo_urls)),
]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next, create a superuser. We’ll come back to this later:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;python manage.py createsuperuser
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  RESTful structure: &lt;code&gt;GET&lt;/code&gt;, &lt;code&gt;POST&lt;/code&gt;, &lt;code&gt;PUT&lt;/code&gt;, and &lt;code&gt;DELETE&lt;/code&gt; methods
&lt;/h2&gt;

&lt;p&gt;In a RESTful API, endpoints define the structure and usage with the &lt;code&gt;GET&lt;/code&gt;, &lt;code&gt;POST&lt;/code&gt;, &lt;code&gt;PUT&lt;/code&gt;, and &lt;code&gt;DELETE&lt;/code&gt; HTTP methods. You must organize these methods logically.&lt;/p&gt;

&lt;p&gt;To show how to build a RESTful app with Django REST framework, we’ll create an example to-do API.&lt;/p&gt;

&lt;h2&gt;
  
  
  Creating models for our Django app
&lt;/h2&gt;

&lt;p&gt;Let’s start by creating the model for our to-do list:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# todo/todo_api/models.py
from django.db import models
from django.contrib.auth.models import User

class Todo(models.Model):
    task = models.CharField(max_length = 180)
    timestamp = models.DateTimeField(auto_now_add = True, auto_now = False, blank = True)
    completed = models.BooleanField(default = False, blank = True)
    updated = models.DateTimeField(auto_now = True, blank = True)
    user = models.ForeignKey(User, on_delete = models.CASCADE, blank = True, null = True)

    def __str__(self):
        return self.task
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After creating the model, migrate it to the database.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;python manage.py makemigrations
python manage.py migrate
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Model serializer
&lt;/h2&gt;

&lt;p&gt;To convert the &lt;code&gt;Model&lt;/code&gt; object to an API-appropriate format like JSON, Django REST framework uses the &lt;code&gt;ModelSerializer&lt;/code&gt; class to convert any model to &lt;code&gt;serialized JSON objects&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# todo/todo_api/serializers.py
from rest_framework import serializers
from .models import Todo
class TodoSerializer(serializers.ModelSerializer):
    class Meta:
        model = Todo
        fields = ["task", "completed", "timestamp", "updated", "user"]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Creating API views in Django
&lt;/h2&gt;

&lt;p&gt;In this section, we’ll walk through how to create two API views, list view and detail view.&lt;/p&gt;

&lt;h3&gt;
  
  
  List view
&lt;/h3&gt;

&lt;p&gt;The first API view class deals with the &lt;code&gt;todos/api/&lt;/code&gt; endpoint, in which it handles &lt;code&gt;GET&lt;/code&gt; for listing all to-dos of a given requested user and &lt;code&gt;POST&lt;/code&gt; for creating a new to-do. Notice that we’ve added &lt;code&gt;permission_classes&lt;/code&gt;, which allows authenticated users only:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# todo/todo_api/views.py
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework import permissions
from .models import Todo
from .serializers import TodoSerializer

class TodoListApiView(APIView):
    # add permission to check if user is authenticated
    permission_classes = [permissions.IsAuthenticated]

    # 1. List all
    def get(self, request, *args, **kwargs):
        '''
        List all the todo items for given requested user
        '''
        todos = Todo.objects.filter(user = request.user.id)
        serializer = TodoSerializer(todos, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)

    # 2. Create
    def post(self, request, *args, **kwargs):
        '''
        Create the Todo with given todo data
        '''
        data = {
            'task': request.data.get('task'), 
            'completed': request.data.get('completed'), 
            'user': request.user.id
        }
        serializer = TodoSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;&lt;p&gt;The &lt;code&gt;GET()&lt;/code&gt; method first fetches all the objects from the model by filtering with the requested user ID.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Then, it serializes from the model object to a JSON serialized object.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Next, it returns the response with serialized data and status as &lt;code&gt;200_OK&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The &lt;code&gt;POST()&lt;/code&gt; method fetches the requested data and adds the requested user ID in the data dictionary.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Next, it creates a serialized object and saves the object if it’s valid.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;If valid, it returns the &lt;code&gt;serializer.data&lt;/code&gt;, which is a newly created object with status as &lt;code&gt;201_CREATED&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Otherwise, it returns the &lt;code&gt;serializer.errors&lt;/code&gt; with status as &lt;code&gt;400_BAD_REQUEST&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Create an endpoint for the class-based view above:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# todo/todo_api/urls.py : API urls.py
from django.conf.urls import url
from django.urls import path, include
from .views import (
    TodoListApiView,
)

urlpatterns = [
    path('api', TodoListApiView.as_view()),
]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Run the Django server:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;python manage.py runserver
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, we’re ready for the first test. Navigate to &lt;code&gt;http://127.0.0.1:8000/todos/api&lt;/code&gt;. Make sure you’re logged in with your superuser credentials:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fpp7mprucjzro3bgte8ey.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fpp7mprucjzro3bgte8ey.png" alt="REST1" width="728" height="401"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;You can create a new to-do by posting the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
    "task": "New Task",
    "completed": false
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Detail view
&lt;/h3&gt;

&lt;p&gt;Now that we’ve successfully created our first endpoint view, let’s create the second endpoint &lt;code&gt;todos/api/&amp;lt;int:todo_id&amp;gt;&lt;/code&gt; API view.&lt;/p&gt;

&lt;p&gt;In this API view class, we need to create three methods for handling the corresponding HTTP methods, &lt;code&gt;GET&lt;/code&gt;, &lt;code&gt;PUT&lt;/code&gt;, and &lt;code&gt;DELETE&lt;/code&gt;, as discussed above:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# todo/api/views.py
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from todo.models import Todo
from .serializers import TodoSerializer
from rest_framework import permissions

class TodoDetailApiView(APIView):
    # add permission to check if user is authenticated
    permission_classes = [permissions.IsAuthenticated]

    def get_object(self, todo_id, user_id):
        '''
        Helper method to get the object with given todo_id, and user_id
        '''
        try:
            return Todo.objects.get(id=todo_id, user = user_id)
        except Todo.DoesNotExist:
            return None

    # 3. Retrieve
    def get(self, request, todo_id, *args, **kwargs):
        '''
        Retrieves the Todo with given todo_id
        '''
        todo_instance = self.get_object(todo_id, request.user.id)
        if not todo_instance:
            return Response(
                {"res": "Object with todo id does not exists"},
                status=status.HTTP_400_BAD_REQUEST
            )

        serializer = TodoSerializer(todo_instance)
        return Response(serializer.data, status=status.HTTP_200_OK)

    # 4. Update
    def put(self, request, todo_id, *args, **kwargs):
        '''
        Updates the todo item with given todo_id if exists
        '''
        todo_instance = self.get_object(todo_id, request.user.id)
        if not todo_instance:
            return Response(
                {"res": "Object with todo id does not exists"}, 
                status=status.HTTP_400_BAD_REQUEST
            )
        data = {
            'task': request.data.get('task'), 
            'completed': request.data.get('completed'), 
            'user': request.user.id
        }
        serializer = TodoSerializer(instance = todo_instance, data=data, partial = True)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_200_OK)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    # 5. Delete
    def delete(self, request, todo_id, *args, **kwargs):
        '''
        Deletes the todo item with given todo_id if exists
        '''
        todo_instance = self.get_object(todo_id, request.user.id)
        if not todo_instance:
            return Response(
                {"res": "Object with todo id does not exists"}, 
                status=status.HTTP_400_BAD_REQUEST
            )
        todo_instance.delete()
        return Response(
            {"res": "Object deleted!"},
            status=status.HTTP_200_OK
        )
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;GET()&lt;/code&gt; method first fetches the object with the ID &lt;code&gt;todo_id&lt;/code&gt; and user as request user from the to-do model.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;If the requested object is not available, it returns the response with the status as &lt;code&gt;400_BAD_REQUEST&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Otherwise, it serializes the model object to a JSON serialized object and returns the response with &lt;code&gt;serializer.data&lt;/code&gt; and status as &lt;code&gt;200_OK&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The &lt;code&gt;PUT()&lt;/code&gt; method fetches the to-do object if it is available in the database, updates its data with requested data, and saves the updated data in the database.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;DELETE()&lt;/code&gt; method fetches the to-do object if is available in the database, deletes it, and responds with a response.&lt;/p&gt;

&lt;p&gt;Update the API &lt;code&gt;urls.py&lt;/code&gt; as demonstrated below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# todo/api/urls.py : API urls.py
from django.conf.urls import url
from django.urls import path, include
from .views import (
    TodoListApiView,
    TodoDetailApiView
)

urlpatterns = [
    path('api', TodoListApiView.as_view()),
    path('api/&amp;lt;int:todo_id&amp;gt;/', TodoDetailApiView.as_view()),
]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, if you navigate to &lt;code&gt;http://127.0.0.1:8000/todos/api/&amp;lt;id&amp;gt;/&lt;/code&gt;, it will show the detail API view page. Notice that you correctly navigate to a valid ID. In the screenshot below, I used &lt;code&gt;7&lt;/code&gt; as the ID:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5dfi6tam033zhz7exf68.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5dfi6tam033zhz7exf68.png" alt="REST2" width="730" height="383"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Congratulations! You’ve successfully built your first fully functional CRUD Django REST API.&lt;/p&gt;

&lt;p&gt;Building a RESTful API can be complicated, but Django REST framework handles complexity fairly well. I hope you have fun building new APIs using the Django REST framework, and be sure to leave a comment if you have any questions. Happy coding!&lt;/p&gt;

</description>
      <category>beginners</category>
      <category>tutorial</category>
      <category>developer</category>
    </item>
    <item>
      <title>Why Virtualenv is Important for Django Development</title>
      <dc:creator>Sarah Hudaib</dc:creator>
      <pubDate>Wed, 18 Jan 2023 07:28:05 +0000</pubDate>
      <link>https://dev.to/sarahhudaib/why-virtualenv-is-important-for-django-development-58fp</link>
      <guid>https://dev.to/sarahhudaib/why-virtualenv-is-important-for-django-development-58fp</guid>
      <description>&lt;h2&gt;
  
  
  Create a separate virtual environment for each project:
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;Virtualenv&lt;/code&gt; is a tool that allows you to create a separate Python environment for each &lt;code&gt;Django&lt;/code&gt; project you work on. This can be particularly useful if you need to work with different versions of &lt;code&gt;Django&lt;/code&gt; and/or different libraries and packages for different projects.&lt;/p&gt;

&lt;h2&gt;
  
  
  Example:
&lt;/h2&gt;

&lt;p&gt;For example, imagine that you are working on two Django projects, &lt;code&gt;Project A&lt;/code&gt; and &lt;code&gt;Project B&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;&lt;code&gt;Project A&lt;/code&gt; requires &lt;strong&gt;Django 2.2&lt;/strong&gt; and a specific version of the library X, while &lt;code&gt;Project B&lt;/code&gt; requires &lt;strong&gt;Django 3.1&lt;/strong&gt; and a different version of library X. Without using virtualenv, you would need to install both &lt;strong&gt;Django 2.2&lt;/strong&gt; and &lt;strong&gt;Django 3.1&lt;/strong&gt;, as well as the two different versions of library X on your system. This could lead to conflicts between the different versions of Django and library X, which could make it difficult or impossible to run one or both of the projects.&lt;/p&gt;

&lt;p&gt;However, if you use virtualenv, you can create a separate virtual environment for each project, with its own copy of Django and the required libraries. This way, you can have &lt;strong&gt;Django 2.2&lt;/strong&gt; and the specific version of library X installed in the virtual environment for &lt;code&gt;Project A&lt;/code&gt;, and &lt;strong&gt;Django 3.1&lt;/strong&gt; and the other version of library X installed in the virtual environment for &lt;code&gt;Project B&lt;/code&gt;. This allows you to run both projects concurrently without any conflicts.&lt;/p&gt;

&lt;h2&gt;
  
  
  Install and manage packages and libraries:
&lt;/h2&gt;

&lt;p&gt;In addition to helping you manage dependencies, virtualenv also makes it easier to install and manage the packages and libraries that your project depends on. You can use tools like pip to install and update these dependencies within the virtual environment, without affecting the packages and libraries installed on your system.&lt;/p&gt;

&lt;h2&gt;
  
  
  Steps to create a virtual environment with Python:
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;Install virtualenv:&lt;br&gt;
&lt;/p&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;pip install virtualenv
&lt;/code&gt;&lt;/pre&gt;

&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Create a virtual environment with Python 3.6:&lt;br&gt;
&lt;/p&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;virtualenv -p python3.6 myenv
&lt;/code&gt;&lt;/pre&gt;

&lt;/li&gt;
&lt;/ol&gt;

&lt;blockquote&gt;
&lt;p&gt;This will create a new directory called "myenv" that contains the Python 3.6 interpreter and other files needed for the virtual environment.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;Activate the virtual environment:&lt;br&gt;
&lt;/p&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;source myenv/bin/activate
&lt;/code&gt;&lt;/pre&gt;

&lt;/li&gt;
&lt;/ol&gt;

&lt;blockquote&gt;
&lt;p&gt;This will activate the virtual environment, and you should see the name of the virtual environment in the command prompt, like this:&lt;br&gt;
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;(myenv)$
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;Install the packages you need for your project:&lt;br&gt;
&lt;/p&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;pip install django
&lt;/code&gt;&lt;/pre&gt;

&lt;/li&gt;
&lt;/ol&gt;

&lt;blockquote&gt;
&lt;p&gt;You can install multiple packages by separating them with spaces, like this:&lt;br&gt;
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;pip install django requests
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;Freeze the installed packages:
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;pip freeze &amp;gt; requirements.txt
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;This will create a file called "requirements.txt" that lists all the packages and their versions that are installed in the virtual environment. You can use this file to install the same packages in a different environment or on a different machine.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;To install the packages from the requirements file, use the following command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;pip install -r requirements.txt
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Sum it up!
&lt;/h2&gt;

&lt;p&gt;Overall, virtualenv is a valuable tool for Django developers, as it allows you to easily manage dependencies and avoid conflicts between different versions of libraries and packages. By using virtualenv, you can ensure that your Django projects are isolated and easy to maintain.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;It allows you to isolate the dependencies for different Django projects, so that you can have different versions of libraries and packages installed for each project.&lt;/li&gt;
&lt;li&gt;It makes it easier to manage the packages and libraries that your project depends on, as you can use tools like pip to install and manage these dependencies within the virtual environment.&lt;/li&gt;
&lt;li&gt;It can help you avoid conflicts between different versions of libraries and packages that may be required by different projects.&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>webdev</category>
      <category>security</category>
      <category>privacy</category>
    </item>
    <item>
      <title>Maximizing Your Django Development: 6 Expert Tips</title>
      <dc:creator>Sarah Hudaib</dc:creator>
      <pubDate>Wed, 18 Jan 2023 07:25:10 +0000</pubDate>
      <link>https://dev.to/sarahhudaib/maximizing-your-django-development-6-expert-tips-12k3</link>
      <guid>https://dev.to/sarahhudaib/maximizing-your-django-development-6-expert-tips-12k3</guid>
      <description>&lt;h2&gt;
  
  
  Maximizing Your Django Development
&lt;/h2&gt;

&lt;p&gt;Django is a powerful web framework, but there are a few things you should keep in mind to make your work smoother and more effective. Here are the top tips that will make a difference in your Django project:&lt;/p&gt;

&lt;h3&gt;
  
  
  1. Use virtualenv
&lt;/h3&gt;

&lt;p&gt;Virtualenv is a tool that allows you to create isolated Python environments for your projects. This is important because it allows you to install and use different versions of libraries and packages for each project, without worrying about conflicts or version issues. Using virtualenv also makes it easier to deploy your code, as you can specify exactly which libraries and versions your project depends on in a requirements.txt file. Without virtualenv, you may run into issues when you try to deploy your code, or when you work on multiple projects that require different library versions.&lt;/p&gt;

&lt;h3&gt;
  
  
  2. Use PostgreSQL
&lt;/h3&gt;

&lt;p&gt;PostgreSQL is a powerful and widely recommended database for Django projects. It offers a number of advantages over other databases, including robust support for transactions, foreign keys, and stored procedures. While it may take a little extra effort to learn how to use PostgreSQL effectively, it's worth it in the long run. We recommend working with PostgreSQL locally while you are learning, so that you can get a feel for how it works and how to troubleshoot any issues that arise.&lt;/p&gt;

&lt;h3&gt;
  
  
  3. Use class-based views
&lt;/h3&gt;

&lt;p&gt;While function-based views may seem simpler at first, class-based views can be easier to work with in medium to large projects. They offer a number of benefits, such as mixins (which allow you to reuse common code across multiple views), forms (which make it easy to handle user input), and a more organized structure for your view code. Additionally, class-based views are the way that REST APIs are typically implemented, so learning to use them will make it easier for you to work with REST APIs in the future.&lt;/p&gt;

&lt;h3&gt;
  
  
  4. Enable SSL/HTTPS after deployment
&lt;/h3&gt;

&lt;p&gt;SSL certificates are essential for secure communication between the server and the site, and should be included in your project from the outset. Without an SSL certificate, your site will use HTTP instead of HTTPS, which is less secure and may cause issues with some browsers or services. If you are deploying on Heroku, this is a built-in feature that you can easily configure in your settings.py file. If you are deploying on Digital Ocean, you can use the free Let's Encrypt library to enable SSL on your site.&lt;/p&gt;

&lt;h3&gt;
  
  
  5. Use the recommended project layout
&lt;/h3&gt;

&lt;p&gt;The way you organize your project's files and folders is important for ease of use and maintainability. Django's recommended layout, which includes separate folders for templates, static files, and more, makes it easy to work with the admin templates or package your code for reuse by other developers. By following this layout, you'll know exactly where to find the files you need, and you'll be able to more easily understand the structure of other Django projects you encounter.&lt;/p&gt;

&lt;h3&gt;
  
  
  6. Do most of the logic in the models
&lt;/h3&gt;

&lt;p&gt;While it's not always possible, it's generally a good idea to put as much logic as possible into your models. This keeps your views cleaner and easier to understand, and can make your code more reusable and maintainable in the long run. For example, if you have a complex calculation that needs to be performed in multiple views, you could put that calculation in a model method and call it from the views. This way, you don't have to repeat&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;In conclusion, Django is a powerful and flexible web framework that can help you build scalable and maintainable web applications. By following these six tips, you can maximize your productivity and success when working with Django. Whether you are a beginner or an experienced developer, these tips will help you avoid common pitfalls and make the most of Django's many features. By using virtualenv, PostgreSQL, class-based views, SSL/HTTPS, the recommended project layout, and putting logic in models, you can take your Django development to the next level and build high-quality applications that meet the needs of your users.&lt;/p&gt;
&lt;/blockquote&gt;

</description>
      <category>webdev</category>
      <category>django</category>
      <category>tutorial</category>
      <category>python</category>
    </item>
    <item>
      <title>Context Processors in Django</title>
      <dc:creator>Sarah Hudaib</dc:creator>
      <pubDate>Wed, 18 Jan 2023 07:21:58 +0000</pubDate>
      <link>https://dev.to/sarahhudaib/context-processors-in-django-15h2</link>
      <guid>https://dev.to/sarahhudaib/context-processors-in-django-15h2</guid>
      <description>&lt;h2&gt;
  
  
  Introduction:
&lt;/h2&gt;

&lt;p&gt;Django is a powerful web framework that follows the principles of the Don't Repeat Yourself (DRY) philosophy. One way that Django achieves this is through the use of Context Processors. In this article, we'll take a closer look at what context processors are, how they work, and how to use them in your own Django projects.&lt;/p&gt;

&lt;h2&gt;
  
  
  What are Context Processors?
&lt;/h2&gt;

&lt;p&gt;A context processor is a function that takes the current HttpRequest object as an argument and returns a dictionary of variables that can be made available to all templates. These variables are added to the context of the request, meaning that they can be accessed in any template that is rendered as a result of that request. This allows you to include common information, such as a site logo or user details, on every page of your website, without having to include the same code in multiple views.&lt;/p&gt;

&lt;h2&gt;
  
  
  How do Context Processors work?
&lt;/h2&gt;

&lt;p&gt;When a request is made to your Django application, the framework goes through a series of middleware and view functions to process the request and generate a response. Once the view function has returned a TemplateResponse object, Django begins to render the template that is associated with the view.&lt;/p&gt;

&lt;p&gt;As the template is rendered, Django looks for context processors that have been defined in your application's settings. For each context processor that is found, Django calls the associated function and adds the returned dictionary of variables to the template context. This means that, once the template has been rendered, all of the variables that have been added by context processors are available to the template.&lt;/p&gt;

&lt;h2&gt;
  
  
  When to use Context Processors?
&lt;/h2&gt;

&lt;p&gt;Context Processors are useful when you have information that needs to be available on every page of your website. Examples of this include:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;A user's cart on an e-commerce site&lt;/li&gt;
&lt;li&gt;Site-wide navigation or a site logo&lt;/li&gt;
&lt;li&gt;User details, such as a username or avatar&lt;/li&gt;
&lt;li&gt;Information that is needed to render the site's footer
etc.&lt;/li&gt;
&lt;/ol&gt;

&lt;blockquote&gt;
&lt;p&gt;Without context processors, you would need to include the code to fetch this information in every view, making your codebase repetitive and hard to maintain. By using context processors instead, you can define the code to fetch this information in one place and make it available to all templates without having to repeat yourself.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  How to Use Context Processors in Django?
&lt;/h2&gt;

&lt;p&gt;To use context processors in Django, you'll first need to create a new folder within your Django project. This folder can be named anything you like, and should be located near your other apps. Inside this folder, you should create a new file called context_processors.py (or similar) and write the function that retrieves the relevant information.&lt;/p&gt;

&lt;p&gt;Here's an example of how you could use a context processor to add a site logo and footer information to all pages:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Create a folder called &lt;code&gt;utils&lt;/code&gt; in your project.&lt;/li&gt;
&lt;li&gt;Inside the &lt;code&gt;utils&lt;/code&gt; folder, create a file called &lt;code&gt;context_processors.py&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;In the &lt;code&gt;context_processors.py&lt;/code&gt;, import the models you need, and define two context processor functions: one to handle the site logo, and one to handle the footer information.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# context_processors.py
from myapp.models import SiteLogo, FooterInfo

def logo_context(request):
    logo = SiteLogo.objects.first()
    return {'logo': logo}

def footer_context(request):
    footer_info = FooterInfo.objects.first()
    return {'footer_info': footer_info}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;In this example, we have defined two context processors: &lt;br&gt;
&lt;code&gt;logo_context&lt;/code&gt; and &lt;code&gt;footer_context&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;Each context processor imports the appropriate model (&lt;code&gt;SiteLogo&lt;/code&gt; and &lt;code&gt;FooterInfo&lt;/code&gt; in this case) and retrieves an instance of that model. The context processor then returns a dictionary containing the information that we want to make available to the template. In this case, the &lt;code&gt;logo_context&lt;/code&gt; function returns a dictionary containing the logo information, and the &lt;code&gt;footer_context&lt;/code&gt; function returns a dictionary containing the &lt;code&gt;footer_info&lt;/code&gt;.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;ol&gt;
&lt;li&gt;In the &lt;code&gt;settings.py&lt;/code&gt; file, add the &lt;code&gt;context_processors.py&lt;/code&gt; file to the context_processors list in the &lt;code&gt;TEMPLATES&lt;/code&gt; section.&lt;/li&gt;
&lt;/ol&gt;

&lt;blockquote&gt;
&lt;p&gt;Once you have defined your context processors, you need to add them to the &lt;code&gt;context_processors&lt;/code&gt; list in the &lt;code&gt;TEMPLATES&lt;/code&gt; section of your &lt;code&gt;settings.py&lt;/code&gt; file. The &lt;code&gt;context_processors&lt;/code&gt; list should include the full Python path to your context processor function. In the example above, where the context processors are in &lt;code&gt;context_processors.py&lt;/code&gt; and located in the &lt;code&gt;utils&lt;/code&gt; folder within your project, the &lt;code&gt;context_processors&lt;/code&gt; list in the &lt;code&gt;settings.py&lt;/code&gt; file should look like this:&lt;br&gt;
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;TEMPLATES = [
    {
        ...
        'OPTIONS': {
            'context_processors': [
                ...
                'utils.context_processors.logo_context',
                'utils.context_processors.footer_context',
            ],
        },
    },
]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;Now you can access the logo and footer information in any template, without the need to include the code to fetch this information in every view.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;You need to make sure that the function names is the same of that in the &lt;code&gt;context_processors.py&lt;/code&gt; file.&lt;/p&gt;

&lt;p&gt;With this setup, the &lt;code&gt;logo&lt;/code&gt; and &lt;code&gt;footer_info&lt;/code&gt; variables will be available in all of your templates, and you can use them to display the appropriate information on your website. &lt;/p&gt;

&lt;p&gt;For example, you could use the &lt;code&gt;logo&lt;/code&gt; variable to display the site &lt;code&gt;logo&lt;/code&gt; in the header of your site and the &lt;code&gt;footer_info&lt;/code&gt; variable to display the footer information on all pages of your site.&lt;/p&gt;

&lt;h2&gt;
  
  
  Additional information about context processors:
&lt;/h2&gt;

&lt;p&gt;It is worth mentioning that context processors can also take additional arguments such as request user, session, etc.&lt;br&gt;
For example, you can use the user object in the context processor and conditionally show or hide certain elements on the website based on user permissions and authentication.&lt;/p&gt;

&lt;p&gt;In addition, if you are working with a large project or have multiple context processors, you can organize them in different files and different folders for better organization.&lt;/p&gt;

&lt;p&gt;Another important thing to consider is the performance of your context processors. As context processors are called on every request, it's important to make sure that the code inside your context processors is optimized for performance. This may include caching or pre-fetching certain data to reduce the number of database queries.&lt;/p&gt;

&lt;h2&gt;
  
  
  Sum it up:
&lt;/h2&gt;

&lt;p&gt;Finally, it is important to keep in mind that Django also provides a built-in context processor called &lt;code&gt;django.template.context_processors.request&lt;/code&gt;, which adds the request object to the template context. This context processor is included by default and can be useful when you need access to the request object in your templates, so you can use the request object to retrieve information that is not available in your context processors&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;In summary, context processors are a powerful tool in Django that allows you to make information available to all templates, without having to repeat yourself. With context processors, you can define the code to fetch common information in one place and make it available to all templates, improving the maintainability and readability of your code. To start using context processors, you need to create a new folder inside your Django project, create a new file called context_processors.py and write the function that retrieves the relevant information. Finally, add the context processors to the context_processors list in the TEMPLATES section in your settings.py file.&lt;/p&gt;
&lt;/blockquote&gt;

</description>
      <category>discuss</category>
    </item>
    <item>
      <title>Django Channels - Building Real-time Web Applications with Django</title>
      <dc:creator>Sarah Hudaib</dc:creator>
      <pubDate>Wed, 18 Jan 2023 07:18:53 +0000</pubDate>
      <link>https://dev.to/sarahhudaib/django-channels-building-real-time-web-applications-with-django-fa5</link>
      <guid>https://dev.to/sarahhudaib/django-channels-building-real-time-web-applications-with-django-fa5</guid>
      <description>&lt;p&gt;Django is a widely used web framework for building web applications with Python. However, it's built mainly for handling HTTP requests and responses in a synchronous manner. With the rise of real-time web applications such as online multiplayer games, chat applications, and real-time dashboards, Django developers faced challenges in building such applications. Django Channels came to the rescue, it's an extension to Django that enables developers to handle &lt;code&gt;WebSockets&lt;/code&gt; and other real-time communication in a way that is familiar to Django developers.&lt;/p&gt;

&lt;h2&gt;
  
  
  What is Django Channels?
&lt;/h2&gt;

&lt;p&gt;Django Channels is a powerful tool that allows developers to build asynchronous, real-time web applications using the popular Django framework. &lt;/p&gt;

&lt;h2&gt;
  
  
  Handling WebSockets with Channels
&lt;/h2&gt;

&lt;p&gt;Channels allows you to handle &lt;code&gt;WebSockets&lt;/code&gt;, chat protocols, and other types of real-time communication in a way that is familiar to Django developers. It works by creating a separate layer between Django's request-response cycle and the underlying transport layer. This allows Django to handle long-running connections, such as &lt;code&gt;WebSockets&lt;/code&gt;, in addition to &lt;code&gt;traditional HTTP requests&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Consumer-based Handling
&lt;/h2&gt;

&lt;p&gt;One of the key features of Channels is its support for consumer-based handling of WebSockets. Consumers are Python classes that handle WebSocket connections, similar to how views handle &lt;code&gt;HTTP requests&lt;/code&gt; in &lt;code&gt;Django&lt;/code&gt;. They can be used to handle different types of messages and events, such as connecting, disconnecting, and sending messages. This allows for a more organized and modular approach to &lt;code&gt;WebSocket&lt;/code&gt; handling.&lt;/p&gt;

&lt;h2&gt;
  
  
  Routing System
&lt;/h2&gt;

&lt;p&gt;Channels also includes a built-in routing system, which allows you to specify which consumers should handle different types of messages and events. This routing system is similar to &lt;code&gt;Django's URL&lt;/code&gt; routing system and allows for easy and flexible handling of different types of connections.&lt;/p&gt;

&lt;h2&gt;
  
  
  Other Real-time Communication
&lt;/h2&gt;

&lt;p&gt;In addition to WebSockets, Channels also supports other types of real-time communication, such as &lt;code&gt;HTTP/2 Server Push&lt;/code&gt;, and other protocols that can be layered on top of it.&lt;/p&gt;

&lt;h2&gt;
  
  
  Setting up Channels in your Django Project
&lt;/h2&gt;

&lt;p&gt;To use Channels in your Django project, you need to install the Channels package and configure your Django project to use it. This involves adding a few lines of code to your project's &lt;code&gt;settings.py&lt;/code&gt; file and creating a new routing file to handle WebSocket connections.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;First, you need to install the Channels package by running the following command:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;pip install channels
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Next, you need to add the Channels layer to your Django project's &lt;code&gt;settings.py&lt;/code&gt; file. You can do this by adding the following lines of code:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import os
from channels.routing import ProtocolTypeRouter, URLRouter
from django.urls import path
from .consumers import MyConsumer

application = ProtocolTypeRouter({
    'http': get_asgi_application(),
    'websocket': URLRouter(
        path('ws/my-path/', MyConsumer.as_asgi()),
    )
})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;This code sets up the Channels layer and specifies the URL routing for WebSockets connections. In this example, all WebSocket connections to the URL path 'ws/my-path/' will be handled by the 'MyConsumer' class.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;ul&gt;
&lt;li&gt;Next, you need to create a file called routing.py in your Django project's root folder and add the following code to it:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from django.urls import re_path
from . import consumers

websocket_urlpatterns = [
    re_path(r'ws/my-path/$', consumers.MyConsumer.as_asgi()),
]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;This code sets up the URL routing for the WebSocket connections. In this example, all WebSocket connections to the URL path 'ws/my-path/' will be handled by the 'MyConsumer' class.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;ul&gt;
&lt;li&gt;Finally, you need to add the routing.py file to your project's main urls.py file:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from django.urls import path, include

urlpatterns = [
    path('', include('routing.websocket_urlpatterns')),
]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;This code tells Django to use the URLs defined in the routing.py file for handling WebSocket connections.&lt;/p&gt;

&lt;p&gt;That's it! Now you're ready to start handling WebSocket connections in your Django project using Channels.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  To Sum it up:
&lt;/h2&gt;

&lt;p&gt;Django Channels is a powerful tool that allows developers to build real-time, asynchronous web applications using the familiar Django framework. Its support for WebSockets, consumer-based handling, and built-in routing system make it easy to handle real-time communication in a modular and organized way. &lt;/p&gt;

&lt;p&gt;With Django Channels, developers can now build real-time web applications such as chat applications, multiplayer games, and real-time dashboards with ease while still leveraging the power and simplicity of the Django framework. It's a great tool for any developer looking to build real-time web applications with Django.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>django</category>
      <category>programming</category>
      <category>python</category>
    </item>
  </channel>
</rss>
