<?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: Conrad </title>
    <description>The latest articles on DEV Community by Conrad  (@conrad).</description>
    <link>https://dev.to/conrad</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%2F1048310%2F0bbea889-6ce2-4b22-b670-c17eb13fbecc.png</url>
      <title>DEV Community: Conrad </title>
      <link>https://dev.to/conrad</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/conrad"/>
    <language>en</language>
    <item>
      <title>Django REST Framework for Beginners: How to Create Your First API</title>
      <dc:creator>Conrad </dc:creator>
      <pubDate>Tue, 16 Jan 2024 07:37:36 +0000</pubDate>
      <link>https://dev.to/conrad/django-rest-framework-for-beginners-how-to-create-your-first-api-47g</link>
      <guid>https://dev.to/conrad/django-rest-framework-for-beginners-how-to-create-your-first-api-47g</guid>
      <description>&lt;p&gt;As a developer, beginner or seasoned, I am sure you have come across the word api or REST api before. So what does it mean? API stands for Applicatin Programming Interface and is a set of rules and instructions that allow different software components to communicate with one another. APIs make it easier of developers to create services and applications by using existing features or data from other platforms or applications. For example you can create a weather app by using data from weather forecasting companies, saving time from having to gather the data yourself.&lt;/p&gt;

&lt;p&gt;REST API or RESTful API is an API that follows a set architectural contstraints for creating web services. REST APIs use HTTP requests to perform standard database functions such as creating, reading, updating and deleting. For more details, I suggest reading this &lt;a href="https://restfulapi.net/" rel="noopener noreferrer"&gt;article&lt;/a&gt; .&lt;br&gt;
Now that we have some understanding on APIs, let's build a simple API using django REST framework.&lt;/p&gt;

&lt;p&gt;Django REST framework is a popular and powerful library for creating web APIs in Python. It provides a range of features and tools that make it easy to build, test, and document RESTful services. In this article, we will learn how to use Django REST framework to create a simple API with CRUD functionality. We will cover the following topics:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;How to install Django REST framework&lt;/li&gt;
&lt;li&gt;How to create models, serializers, and views.&lt;/li&gt;
&lt;li&gt;How to use URL patterns to define our API endpoints&lt;/li&gt;
&lt;li&gt;How to test our API&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;By the end of this article, you will have some understanding of how to use the Django REST framework to build your own web APIs. Let’s get started!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Setup&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;As we are using python and django, ensure you have django installed on your system. Install the django rest framework by running the command ‘pip install djangorestframework’. Add the django rest framework into your installed apps list in your setting.py file. Create a new django app which will be used to build the api and add it to the installed apps list. For the sake of this project, name the new app api.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;INSTALLED_APPS = [
    ...
    'rest_framework',
    'api',
]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Serializers and models&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Serializers are a very important part of Django REST framework , they handle convertion between complex data types such as model instances and primitive values such as JSON or other content types. They are also responsible for deserialization and check the input data for errors and convert it back to complex types.&lt;br&gt;
To create serializers, start by creating a new file called ‘serializers.py’ inside the api app folder. Before you start working with serializers, ensure you create your models and make necessary migrations. Here is the model used for this project&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from django.db import models
import uuid
# Create your models here.
class Posts(models.Model):
    id = models.UUIDField(primary_key=True,default=uuid.uuid4,editable=False,unique = True)
    post_name = models.CharField(max_length = 150,blank=False,null=True)
    post_user = models.CharField(max_length=50,blank=False,null=True)
    created = models.DateTimeField(auto_now_add=True,blank=False,null=True)


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

&lt;/div&gt;



&lt;p&gt;You can choose to use custom id like in the case above, if not, you can skip that line of code entirely. If all this is new to you I suggest reading about &lt;a href="https://docs.djangoproject.com/en/5.0/" rel="noopener noreferrer"&gt;django&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now in the serializers.py file, import the serializers module from rest_framework and all the models you want to work with.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from rest_framework import serializers
from .models import Posts
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now create a new serializer class as shown below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class PostsSerializer(serializers.ModelSerializer):
    class Meta:
        model = Posts
        fields ='__all__'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;PostsSerializers&lt;/code&gt; is the name of of the serializer class. &lt;/li&gt;
&lt;li&gt;
&lt;code&gt;model=Posts&lt;/code&gt; tells the class what model it will serialize.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;fields='__all__'&lt;/code&gt; tells the serializer which fields of the model will be serialized.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If you want to serialize more that one model, ensure you create a serializer class for each model.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Views and urls&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Inside your main project folder, open the urls.py file and include the urls for the api app.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from django.contrib import admin
from django.urls import path, include
urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/',include('api.urls')),
]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Inside your api app folder create a urls.py file and add url patterns. You can add just one path for testing purposes.&lt;br&gt;
&lt;/p&gt;

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

urlpatterns = [
    path('',views.index,name='index'),
]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Within the api app folder, open the views.py file. This is where the api logic will be written on. There are several imports needed:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from .models import Posts
from .serializers import PostsSerializer
from rest_framework.decorators import api_view
from rest_framework.response import Response
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;from .models import Posts&lt;/code&gt; : imports the model Posts created in the models.py file&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;from .serializers import PostsSerializer&lt;/code&gt; : imports the PostsSerializer created in the serializers.py file. It will be used to convert instances of the model Posts into a format that can be easily rendered in JSON format.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;from rest_framework.decorators import api_view&lt;/code&gt; : imports the api_view decorator from the django rest framework. This decorator is used to define views for handling different HTTP requests such as GET , POST and others.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;from rest_framework.response import Response&lt;/code&gt; : imports the response class which is used to create HTTP responses in views.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Now create a view for the api:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@api_view(['GET'])
def index(request):
   urls = {
        'All Posts':'posts',
        'View single post':'post/&amp;lt;uuid:id&amp;gt;',
        'Create post':'create-post',
        'Delete post':'delete-post/&amp;lt;uuid:id&amp;gt;',
        'Edit post':'edit-post/&amp;lt;uuid:id&amp;gt;',
    }
    return Response(urls)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;There are 2 main differences between this view and ordinary django view which are @api_view(['GET']) and the return Response(urls).&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;@api_view(['GET'])&lt;/code&gt; : This decorator specifies the index view to only respond to HTTP GET requests&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;Response(urls)&lt;/code&gt; : Creates a HTTP response with a JSON payload of the data urls.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Test the api by running the server and navigating to &lt;code&gt;http://127.0.0.1:8000/api/&lt;/code&gt;. If done correctly you should see the following page&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%2Fdvgu3hb0e7e9m9ey739a.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%2Fdvgu3hb0e7e9m9ey739a.png" alt="API view" width="800" height="352"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Congrats! You have an api up and running! Now let's add CRUD functionality to the api. CRUD stands for create, read, update, delete.&lt;/p&gt;

&lt;p&gt;Before that, we want the api to be able to list all data in the model Posts, for that do 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;@api_view(['GET'])
def listPosts(request):
    posts = Posts.objects.all()
    list = PostsSerializer(posts,many=True)
    return Response(list.data)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;@api_view(['GET'])&lt;/code&gt;: this decorator specifies the view listPosts will only accept HTTP GET requests&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;posts = Posts.objects.all()&lt;/code&gt;: Retrieves all posts from the database&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;list = PostsSerializer(posts,many=True)&lt;/code&gt;: Creates an instance of the PostsSerializer class, which is responsible for converting multiple instances of posts( all data retrieved from the model Posts). &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;return Response(list.data)&lt;/code&gt;: Generates a HTTP response using the Response class from django rest framework. The serializer.data contains the serialized data of the model. This response is in JSON format which is common in most APIs.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Create a url path in the urls.py file inside the api app folder.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;path('posts/',views.listPosts,name='posts'),
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then navigate to &lt;code&gt;http://127.0.0.1:8000/api/posts&lt;/code&gt; and you should see the following page.&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%2Fnipbffj5g4zkfzuu0h0m.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%2Fnipbffj5g4zkfzuu0h0m.png" alt="Posts list image" width="800" height="451"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;You can add some data through the django admin panel, which will display on this page.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;CRUD Functionality&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Create&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;For the API to accept data input, there are a few changes that need to be made&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@api_view(['POST'])
def makePost(request):
    serializer = PostsSerializer(data=request.data)
    if serializer.is_valid():
        serializer.save()

    return Response(serializer.data)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;@api_view(['POST']&lt;/code&gt; : This decorator specifies the view makePost should only accept HTTP Post requests.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;serializer = PostsSerializer(data=request.data)&lt;/code&gt; : Creates an instance of the PostsSerializer class. The serializer converts the request data into a Python dictionary that can be used to create or update a Post model instance.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;if serializer.is_valid():serializer.save()&lt;/code&gt; : This checks whether the data provided in the request is valid according to the rules defined in the serializer. If the data is valid, this line saves the data to the database using the serializer.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;return Response(serializer.data)&lt;/code&gt; : returns a Response object that contains the serializer’s data as the body.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Create a new url path in your urls.py file inside your api app folder.&lt;br&gt;
&lt;code&gt;path('create-post/',views.makePost,name='create-post'),&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Navigate to this url and you should see something similar to this&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%2Flcvfvj03j7vzvhha9yin.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%2Flcvfvj03j7vzvhha9yin.png" alt="Create post view" width="800" height="516"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;You can add data on content input. The data you add should be in  JSON format, for example&lt;br&gt;
&lt;code&gt;{&lt;br&gt;
        "id": "04c62826-14ee-489c-ba5e-56dc98d8d2a7",&lt;br&gt;
        "post_name": "Home is 127.0.0.1",&lt;br&gt;
        "post_user": "X53Tq0Ui",&lt;br&gt;
        "created": "2024-01-11T11:55:41.126952+03:00"&lt;br&gt;
    }&lt;/code&gt;&lt;br&gt;
Change the properties which are, id, post_name to match the fields your model has. Once complete, submit the form.&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%2Fkr6vtoviarwimc932v6v.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%2Fkr6vtoviarwimc932v6v.png" alt="Create post view" width="800" height="278"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;After submitting the data, you should see the following:&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%2Fm2iy8r4zzno0w12tj3vv.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%2Fm2iy8r4zzno0w12tj3vv.png" alt="Post submit view" width="465" height="216"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Also on the posts list you should be able to see it&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%2Fa4s7zr6f9rjwmyfqzrhv.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%2Fa4s7zr6f9rjwmyfqzrhv.png" alt="Post list view" width="524" height="651"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Read&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Reading is simply viewing a specific post. It is done by passing the id of the post you want to view and it will be retrieved and a response will be rendered.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@api_view(['GET'])
def postDetails(request,id):
    post = Posts.objects.get(id=id)
    serializer = PostsSerializer(post,many=False)
    return Response(serializer.data)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;@api_view(['GET'])&lt;/code&gt; : This decorator specifies the view makePost should only accept HTTP Post requests.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;post = Posts.objects.get(id=id)&lt;/code&gt; : Retrieves a specific post from the database.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;serializer=PostsSerializer(post,many=False)&lt;/code&gt; : Creates a serializer instance for a single instance of the Posts model.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;return Response(serializer.data)&lt;/code&gt; : Returns a Response object that contains the serializer’s data as the body.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Create url path for this view inside the urls.py file in the api app folder &lt;code&gt;path('post/&amp;lt;uuid:id&amp;gt;/',views.postDetails,name='post'),&lt;/code&gt;, then navigate to the link &lt;code&gt;http://127.0.0.1:8000/api/post/(add the id here without brackets)&lt;/code&gt;. You should see the following&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%2F8fuwalg9k6rivwbtrsrk.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%2F8fuwalg9k6rivwbtrsrk.png" alt="single post view" width="800" height="298"&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Update&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;For update, you pass in the id of the object that you want to update. The api will respond with the object which can be edited as needed and submitted. Let's do it practically.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@api_view(['POST'])
def editPost(request,id):
    post = Posts.objects.get(id=id)
    serializer = PostsSerializer(instance=post,data=request.data)
    if serializer.is_valid():
        serializer.save()

    return Response(serializer.data)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;post = Posts.objects.get(id=id)&lt;/code&gt; : Retrieves the specific object from the database.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;serializer = PostsSerializer(instance=post,data=request.data)&lt;/code&gt; : This is using the PostsSerializer to update the existing post with the new data prodived from request.data.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The rest of the code checks whether the data is valid and returns a JSON response of the new data.&lt;/p&gt;

&lt;p&gt;Create another url route in the urls.py file inside the api app folder. &lt;br&gt;
&lt;code&gt;path('edit-post/&amp;lt;uuid:id&amp;gt;/',views.editPost,name='edit-post'),&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;To test it, copy the id of an object you want to update and paste it to the url, example &lt;code&gt;http://127.0.0.1:8000/api/edit-post/c34fcfe4-dc69-4080-ace3-bcc0c02b79ef/&lt;/code&gt;. It should open a new page similar to create post page where you can input a JSON data. Once you submit, it will replace the existing data with the new data. &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%2Fa7f2fp0iqgmb8twvl48n.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%2Fa7f2fp0iqgmb8twvl48n.png" alt="Update page" width="800" height="278"&gt;&lt;/a&gt;&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%2F8oo5e3dsiiu13njx4qa9.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%2F8oo5e3dsiiu13njx4qa9.png" alt="Updated object" width="424" height="319"&gt;&lt;/a&gt;&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%2F3uc8xfl4g8mbu6a3d14u.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%2F3uc8xfl4g8mbu6a3d14u.png" alt="Updated object on list" width="561" height="535"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Delete&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Just like read and update, pass the id of the object to the api view through the url, then the object will be retrieved from the database then finally it will be deleted. The HTTP request used in this case is DELETE. Let's see it in action&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@api_view(['DELETE'])
def deletePost(request,id):
    post = Posts.objects.get(id=id)
    post.delete()
    return Response('Post Deleted!')
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;@api_view(['DELETE'])&lt;/code&gt; : This decorator specifies that the deletePost view should only respond to HTTP DELETE requests.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;post = Posts.objects.get(id=id)&lt;/code&gt; : Retrieves the Post instance with the given id from the database.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;post.delete()&lt;/code&gt; :  If the Post instance is found, it is deleted from the database using the delete() method.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;return Response('Post Deleted!')&lt;/code&gt; : After successful deletion, the view returns a response indicating that the post has been deleted.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&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%2Fm55lsvowq8blhwzm506f.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%2Fm55lsvowq8blhwzm506f.png" alt="Delete post view" width="800" height="266"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;After successful deletion&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%2Flsb9u2sl3uojyfuhksa4.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%2Flsb9u2sl3uojyfuhksa4.png" alt="Successful deletion" width="298" height="335"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;And there you have it, a REST API with full CRUD functionality.You can read more on django rest framework from their site &lt;a href="https://www.django-rest-framework.org/" rel="noopener noreferrer"&gt;here&lt;/a&gt;. From here on, I recommend building a similar api on your own to solidify your understanding. You can research on how to add more features such as file upload, user registration and login. You can also build a to do list api and connect it to the frontend using frontend frameworks such as React, Vue or just use plain JavaScript. The possibilities are endless, it your job to research and build bigger, better and more secure APIs. Happy coding!&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>django</category>
      <category>api</category>
      <category>python</category>
    </item>
    <item>
      <title>Mastering File Uploads in Django: A Comprehensive Guide.</title>
      <dc:creator>Conrad </dc:creator>
      <pubDate>Mon, 21 Aug 2023 16:30:00 +0000</pubDate>
      <link>https://dev.to/conrad/mastering-file-uploads-in-django-a-comprehensive-guide-84</link>
      <guid>https://dev.to/conrad/mastering-file-uploads-in-django-a-comprehensive-guide-84</guid>
      <description>&lt;p&gt;&lt;strong&gt;INTRODUCTION&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;File upload is a very important feature in web and mobile app development. It allows us to upload images for our online profile pictures, share funny videos with friends, send emails with school assignments, upload music and much more.&lt;br&gt;
When it comes to building web applications using Django, a Python web framework, handling file uploads becomes not only feasible but also streamlined. Whether you're creating a platform for sharing images, documents, or any other type of file, understanding the inner working of file uploads in Django is essential. &lt;br&gt;
In this comprehensive guide, we will walk through the process step by step and by the end, you'll have the knowledge and confidence to seamlessly integrate file upload functionality into your Django projects, enriching user experiences and expanding the capabilities of your web applications.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;File Upload in Django: The Steps&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Assuming you have already created you django project and linked your app to your main project: &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Configure media settings&lt;/strong&gt;: In the settings.py file in your project create media root and media url&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;MEDIA_URL = '/uploads/'
MEDIA_ROOT = os.path.join(BASE_DIR,'static')
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Update URLs confugirations&lt;/strong&gt;: In your urls.py file add the following line of code&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from django.urls import path
from . import views
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    .
    .
    .
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Create file upload model&lt;/strong&gt;: Design a model to manage uploaded files. For example a model for uploading profile pictures.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from django.db import models

class ProfilePics(models.Model):
    name = models.CharField(max_length=20)
    nickname = models.CharField(max_length=20)
    image = models.FileField(upload_to='profile')
    uploaded_at = models.DateTimeField(auto_now_add=True)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Prepare Storage Directory&lt;/strong&gt;: Inside your static folder, ensure you have another folder called 'profile' where the image will be uploaded to.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Upload Form Setup&lt;/strong&gt;: Create a form for file upload.Ensure you include all necessary fields.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from django import forms
from .models import ProfilePics
class ProfilePicsForm(forms.ModelForm):
    class Meta:
        model = ProfilePics
        fields = ('name', 'nickname','image')
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Upload View Setup&lt;/strong&gt;: Finally create a view to handle the file upload using the form. In the templates folder, ensure your have created the html template where the form will be rendered to.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from django.shortcuts import render, redirect
from .forms import ProfilePicForm

def upload_file(request):
    if request.method == 'POST':
        form = ProfilePicsForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return redirect('uploaded_files')  # Redirect to a view showing uploaded file(s)
    else:
        form = ProfilePicsForm()
    return render(request, 'upload-pic.html', {'form': form})

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Testing&lt;/strong&gt;: Now run the server and test the functionality.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Some Explanation&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;MEDIA_URL&lt;/strong&gt; specifies the url that will be used to serve your uploaded media files. When you want to display or access uploaded files, you'll prepend this URL to the file's path. For instance, if you have an uploaded image at &lt;em&gt;media/images/my_image.jpg&lt;/em&gt;, and MEDIA_URL is set to '/images/', you can reference the image's URL as &lt;em&gt;{ MEDIA_URL }my_image.jpg&lt;/em&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;MEDIA_ROOT&lt;/strong&gt; is the absolute filesystem path to the directory where uploaded media files are stored. In this case, you're setting it to a directory named static at the root of your project &lt;em&gt;(BASE_DIR)&lt;/em&gt;. &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;upload_to='profile'&lt;/strong&gt; this line simply means that the file will be uploaded into the folder called profile within your main static folder.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; It is important to understand that when uploading a file, what is saved to the database is not the actual file itself but the path to the file. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;CONCLUSION&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Understanding the art of file uploads in Django opens up a world of possibilities for creating dynamic and interactive web applications. Through the correct integration of models, forms, and views, Django streamlines the process of handling file uploads and storage. By carefully configuring settings for static and media files, and leveraging the power of the FileField and ImageField fields, developers can seamlessly facilitate the uploading and presentation of various file types, be it images, PDFs, documents, or more.&lt;/p&gt;

&lt;p&gt;It is important to note that this article provides a basic understanding of file uploads in Django, and there is plenty of room for customization and further research and exploration. &lt;br&gt;
Remember, while you are integrating file upload feature or any other feature django has to offer, stick to Django's rules and keep up with the latest advancements to ensure that you create applications that deliver a polished, engaging user experience. Happy coding!&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Image by &lt;a href="https://pixabay.com/users/tumisu-148124/?utm_source=link-attribution&amp;amp;utm_medium=referral&amp;amp;utm_campaign=image&amp;amp;utm_content=1990405" rel="noopener noreferrer"&gt;Tumisu&lt;/a&gt; from &lt;a href="https://pixabay.com//?utm_source=link-attribution&amp;amp;utm_medium=referral&amp;amp;utm_campaign=image&amp;amp;utm_content=1990405" rel="noopener noreferrer"&gt;Pixabay&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

</description>
      <category>python</category>
      <category>django</category>
      <category>webdev</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Unleashing the Power of Elegance: A Guide to Styling Django Forms</title>
      <dc:creator>Conrad </dc:creator>
      <pubDate>Sat, 05 Aug 2023 15:26:09 +0000</pubDate>
      <link>https://dev.to/conrad/unleashing-the-power-of-elegance-a-guide-to-styling-django-forms-3oi7</link>
      <guid>https://dev.to/conrad/unleashing-the-power-of-elegance-a-guide-to-styling-django-forms-3oi7</guid>
      <description>&lt;p&gt;&lt;strong&gt;Introduction&lt;/strong&gt;&lt;br&gt;
In web development, Django forms come in handy in speeding up development and making the data collection process much simpler. They however lack the visually appealing look and feel we desire. So, how do we style them?  In this article, we shall explore 2 effective ways of styling Django forms and make them visually appealing and leave a lasting impression on your users.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Styling Django Forms: The Two Approaches&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Django crispy-forms&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This is a popular third-party Django app that improves the rendering and styling of Django forms. It is built on top of Django’s built in Django forms framework and makes it easy to control the way forms are represented in the website. With Crispy Forms, you can quickly specify how your forms should be rendered on the frontend, making the process of styling and customizing the form layouts easier and more standardized. You can learn more about Django crispy forms from their official documentation &lt;a href="https://django-crispy-forms.readthedocs.io/en/latest/" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;To use crispy forms, we must first install it to our local machine using the command: &lt;em&gt;pip install django-crispy-forms&lt;/em&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;After a successful install, add it to the installed apps list in your Django application&lt;br&gt;
&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;INSTALLED_APPS = [
    .
    .
    .
    'crispy_forms',
]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;On your html template that contains the django form, add the load crispy for tags at the top of your page.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;code&gt;{% load crispy_forms_tags %}&lt;/code&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Finally add the ‘|crispy’ filter to your form content as shown:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;form action="" method="post"&amp;gt;  
    {{form|crispy}}
    &amp;lt;input type="submit"/&amp;gt;
&amp;lt;/form&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now refresh your page and see the results. For more in-depth information and advanced usage of Django Crispy Forms, refer to their official documentation.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Manual Styling&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Manual styling involves assigning custom classes or id attributes to individual form fields, similar to traditional HTML forms. By doing so, you gain complete control over the form's appearance and behavior, enabling you to tailor it to their specific design preferences. This method proves particularly advantageous when seeking to achieve a fully customized and unique styling for Django forms, as it allows for seamless integration with CSS, empowering the creation of visually stunning and user-centric web interfaces. Let’s now see how it’s done.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Create a new file ‘forms.py’ in your apps root folder&lt;/li&gt;
&lt;/ul&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%2Fj74ul7mtwp0sie0i17dr.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%2Fj74ul7mtwp0sie0i17dr.png" alt="Image showing where to place you forms.py file" width="127" height="219"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;In the forms.py file, import forms and other necessary modules.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;code&gt;from django import forms&lt;/code&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Start by creating a form using the default Django form creation method.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class UserRegister(UserCreationForm):
    class Meta:
        model = User
        fields = ['username','email','password1','password2']
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Now customize the fields as desired.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;username = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control','placeholder':'Your username'}))

 email = forms.EmailField(widget=forms.EmailInput(attrs={'class':'form-control','placeholder':'Your email Eg: sample@sample.com'}))

password1 = forms.CharField(widget=forms.PasswordInput(attrs={'class':'form-control','id':'pass-one','placeholder':'Enter password'}))

 password2 = forms.CharField(widget=forms.PasswordInput(attrs={'class':'form-control','id':'pass-two','placeholder':'Repeat password'}))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Some explanation:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;username=forms.CharField(widget=forms.TextInput(attrs={'class':'form-control','placeholder':'Your username'}))&lt;/code&gt;: By changing the 'username' field's widget to a TextInput and adding some HTML attributes using the attrs dictionary, this line personalizes the field. In this instance, the field will be displayed as a text input with the placeholder text "Your username" and the class "form-control," which is frequently used in Bootstrap-based projects.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;email=forms.EmailField(widget=forms.EmailInput(attrs={'class':'form-control','placeholder':'Your email Eg: sample@sample.com'}))&lt;/code&gt;: The 'email' field is modified by this line, which changes the widget to an EmailInput and adds HTML attributes by using the attrs dictionary. The field's placeholder text will read, "Your email Eg: &lt;a href="mailto:sample@sample.com"&gt;sample@sample.com&lt;/a&gt;," and the field will be shown as an email input with the class "form-control."&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;password1=forms.CharField(widget=forms.PasswordInput(attrs={'class':'form-control','id':'pass-one','placeholder':'Enter password'}))&lt;/code&gt;: This line alters the 'password1' field by changing its widget to a PasswordInput and adding HTML attributes using the attrs dictionary. The field will display as a password input with the class "form-control," an id of "pass-one," and the default text "Enter password."&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;password2=forms.CharField(widget=forms.PasswordInput(attrs={'class':'form-control','id':'pass-two','placeholder':'Repeat password'}))&lt;/code&gt;: This line alters the 'password2' field, similar to the 'password1' field, but with a different id attribute ('pass-two') and a placeholder text 'Repeat password'.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Now with these adjustments, the UserRegister form will display with the desired styles and placeholder texts for each field, making the user registration process more aesthetically pleasing and user-friendly. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Using these 2 methods guarantees your Django forms will be visually appealing and will certainly leave a lasting impression on your users. Remember to keep user experience at the forefront of your design choices. A user centric interface will not only enhance the overall usability of your application but also pave the way for increased user satisfaction and loyalty.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>django</category>
      <category>python</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Understanding *args &amp; **kwargs</title>
      <dc:creator>Conrad </dc:creator>
      <pubDate>Tue, 21 Mar 2023 16:32:57 +0000</pubDate>
      <link>https://dev.to/conrad/understanding-args-kwargs-3gil</link>
      <guid>https://dev.to/conrad/understanding-args-kwargs-3gil</guid>
      <description>&lt;p&gt;If you have ever needed to pass a variable number of arguments to a Python function you may have come across the *args and **kwargs syntax. These powerful tools allow you to pass a variable number of non-keyword and keyword arguments, respectively. In this post, lets dive into what *args and **kwargs are, how they work, and provide some examples to help you better understand these Python features.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What is *args?&lt;/strong&gt;&lt;br&gt;
It is a special syntax used in python function definition to pass a variable/unlimited number of non-keyword arguments to the function. Let’s use an example to make things more clear.&lt;/p&gt;

&lt;p&gt;Example 1: Create a python function that takes in any number of values and sum all values passed to it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def add(*args):
    sum = 0
    for arg in args:
        sum += arg
    print(f"The sum is: {sum}")

add(1,2,3,4,5,6,7,8,9)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Output: &lt;em&gt;The sum is: 45&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Example 2: Create a python function to display all car brand names passed to it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def names(*args):
    print("The car brands are:")
    for arg in args:
        print(arg)

names('Jeep','Volkswagen','Toyota','Ford','Rivian','Tesla')

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Output: &lt;br&gt;
&lt;em&gt;The car brands are:&lt;br&gt;
Jeep&lt;br&gt;
Volkswagen&lt;br&gt;
Toyota&lt;br&gt;
Ford&lt;br&gt;
Rivian&lt;br&gt;
Tesla&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What is **kwargs?&lt;/strong&gt;&lt;br&gt;
It is a special syntax used to pass keyword arguments to a function. These keyword arguments can be of any number just like in args. A keyword argument is where you give a name to the argument as you pass it to the function. Let’s use some examples to make things clear.&lt;/p&gt;

&lt;p&gt;Example 1:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def names(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

names(Fname="John",Lname="Doe",work="Doctor")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Output: &lt;br&gt;
&lt;em&gt;Fname: John&lt;br&gt;
Lname: Doe&lt;br&gt;
work: Doctor&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;It is important to note that args and kwargs are just names and can be replaced with whatever names you like. What is important is the * and ** operators which are called unpacking operators. These operators must be included whenever you want to create such functions. To prove this, lets rename args and kwargs in the above examples.&lt;/p&gt;

&lt;p&gt;Example 1:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def names(*cars):
    print("The car brands are:")
    for x in cars:
        print(x)

names('Jeep','Volkswagen','Toyota','Ford','Rivian','Tesla')
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Output: &lt;br&gt;
&lt;em&gt;The car brands are:&lt;br&gt;
Jeep&lt;br&gt;
Volkswagen&lt;br&gt;
Toyota&lt;br&gt;
Ford&lt;br&gt;
Rivian&lt;br&gt;
Tesla&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Example 2:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def names(**names):
    for key, value in names.items():
        print(f"{key}: {value}")

names(Fname="John",Lname="Doe",work="Doctor")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Output:&lt;br&gt;
Fname: John&lt;br&gt;
Lname: Doe&lt;br&gt;
work: Doctor&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why use *args and **kwargs.&lt;/strong&gt;&lt;br&gt;
These two python features are very useful in creating functions which the number of arguments to be provided is not known.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;*args passes a variable number of non-keyword arguments.&lt;/li&gt;
&lt;li&gt;**kwargs passes a variable number of keyword arguments.&lt;/li&gt;
&lt;li&gt;Keyword arguments are arguments that have a key and value. For example, fname=”name”&lt;/li&gt;
&lt;li&gt;The names args and kwargs can be changed to whatever you want, the most important part are the &lt;strong&gt;unpacking operators&lt;/strong&gt; * and **.&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>python</category>
      <category>beginners</category>
      <category>programming</category>
    </item>
  </channel>
</rss>
