How to use ViewSets and Routers | Django REST-Framework

Django REST Framework allows us to combine the logic for a set of related views in a single view class. They are called Viewsets. ViewSets work exactly same as Generic Views. The only difference is using ViewSet we don’t have to create separate views for getting list of objects and detail of one object. We do not need to configure the urls with ViewSets. Routers generates urls automatically and binds methods for different request method types of ViewSet.

Why we should use ViewSets & Routers.

In larger projects multiple endpoints (URLs) can be difficult to maintain . Besides, same lines of code are repeated in the views. These problems can be solved using ViewSets & Routers.

Advantages of using ViewSet.

  • Can speed up API development
  • Additional layer of abstraction
  • A single viewset can replace multiple views
  • Repeated logic can be combined into a single class
  • Combined logic for a set of related views in a single class
  • Write less code – Promotes DRY (Don’t Repeat Yourself)

Firstly, we will see usage of Viewset class and then ModelViewset class.

Read More

How To Export & Import CSV files in Django Admin

Data is very much important. Specially, when you are working on a project which is already in production you must take care of your existing data. If data is lost somehow your client gonna kill you. So, we save the data externally in different format like json or csv. In the first place, we will see how to export data of a table in .csv (Comma Separated Value) format from django’s default admin site and then we will work on restoring that data into table row/model instance.

Export CSV files from Django Admin.

In our admin site we will create a ModelMixin. Let’s name it ‘ExportCsvMixin’. The ‘export_as_csv’ function of the mixin will convert the model instances into CSVs.

class ExportCsvMixin:
    def export_as_csv(self, request, queryset):
        meta = self.model._meta
        field_names = [ for field in meta.fields]
        response = HttpResponse(content_type='text/csv')
        response['Content-Disposition'] = 'attachment; filename={}.csv'.format(meta)
        writer = csv.writer(response)
        for obj in queryset:
            row = writer.writerow([getattr(obj, field) for field in field_names])
        return response
    export_as_csv.short_description = "Export Selected"

Read More

How to Customize Django Admin Site

We already knew that django has a beautiful beautiful admin panel. It is adequate for small and medium sized projects. But if we want to change some defaults and add more functionalities in our admin panel, we will need to customize it. Here, In this tutorial we will see some easy but useful customization techniques.

  1. How to change the ‘Django administration’ text?
  2. Creating two separate admin sites
  3. Pagination in Django admin.
  4. Edit multiple models from one page.
  5. Make a field uneditable.
  6. Add Search Functionality
  7. Add Filter Functionality

Read More

Scheduled Job In Django | Run Tasks Automatically

In many situations, we need to run some tasks automatically in software. Like, sending an automatic email or doing something specific automatically after a definite interval. These are called scheduled tasks.

Today we will see how to implement scheduled tasks in Django. There are many ways to do it. Like using Celery or using python packages like django-cronjob, django-background-tasks, etc.

Here we will use django-background-tasks. It is very lightweight and easy to use.

Read More

Django Authentication With Custom User Model

By default, Django uses a built-in User model for authentication. If you’d like a basic tutorial on how to implement login, log out, sign up you can see the Django Authentication SignUpView -LoginView-LogoutView

However, the Django documentation highly recommends using a custom user model for a real-world project. Because this provides far more flexibility. In todays’ article, we will see how to create a custom user model for Django projects.

The default User model in Django uses a username to uniquely identify a user during authentication. We can create a custom Django user model by either subclassing AbstractUser or AbstractBaseUser. The difference is AbstractUser uses the existing fields of the User model and just allows to remove the username field.

On the contrary, AbstractBaseUser is used if one wants to start from scratch by creating completely a new User model. Here we will use  AbstractBaseUser

Firstly, we have created a Django project called ‘CUSTOM_AUTHENTICATION’ and an app named ‘custom_auth’. Now we are all set to start our work. So, without further ado let’s create our CustomUser model first.

Read More

CRUD (Create Retrieve Update Delete) in DRF.

CRUD is an approach to build a Django web application. CRUD stands for Create Retrieve Update Delete.

In simple words CRUD means performing Create, Retrieve, Update and Delete operations on a table in a database.

Django REST provides some generic view classes for doing these operations easily and there is an HTTP method handler assigned with each of them.

CreatePOST(Creates a new instance of a model)
RetrieveGET(Brings the value of an instance)
UpdatePUT/PATCH(Updates the value of an instance)
DeleteDELETE(Deletes an instance)

In this article we will implement each of the operations in our project. First, we will create one API for each operation. Then we will see how to do multiple operations with only one API endpoint.

Read More

Serializer and ModelSerializer | Django REST Framework

What is a Serializer?

A Serializer takes a data that exists on the server, parses data from complex types into a format (JSON or XML) that can be read by other technologies.


A serializer is a framework that allows complex data such as ‘querysets’ and model instances to be converted to native Python data types. Then, we can easily render these into JSON, XML, or other content types.

There Two types of Serializers in Django.

  • serializers.Serializer &
  • serializers.ModelSerializer

The Serializers and ModelSerializers work in a way similar to Forms and ModelForms. Unlike forms, they are not constrained to dealing with HTML output and form encoded input.

We will discuss both types.

Read More

Django REST Framework | Introduction

Django REST Framework is a library which works on top of Django. It can be called a Microframework. In django we return a HttpResponse object from views. But in DRF we return JSON object. DRF helps to create an  RESTful API endpoint. “Browsable API” was stated as the key factor in picking Django REST framework.

What is an API?

If you are totally new to development, you might have never heard about API. It’s totally okey. But did you ever think how data travel from one application to another?

API does that. It stands for Application Programming Interface. APIs transport data from one app to another. So, API is a messenger that takes request and returns the response or a software intermediary that allows two applications to talk to each other.

Think of a website that compares mobile phones of different brands. The site doesn’t have the information of each model of each brand in its database. Then how do they compare? Each time a user selects a mobile model, the backend of PhoneCompare site sends a request through the API to its manufacturer’s website to send information. If the request is valid the API comes with the response.

This is how it retrieves data and then compares them using it’s own mechanism.

Read More

How to Paginate with Django | Django Pagination

The pagination system is one of the most common features of a modern web application like blogs, search engines, a list of results, etc. It gives a better experience to the users.

How to Paginate with Django? - DEV Community

Seeing the popularity, Django came up with built-in pagination classes for paginating data of an application.

In this article, we will discuss the pagination process with class-based views and function-based views in Django.

We have a model named ‘Person’. We created some objects of that model. Till now we were showing all the objects of our model on the same page. Now we will use pagination on our page.

Read More

Django Signals |Django Tutorial

What is Signal?

We are familiar with signals & we see much usage of different types of signals. Suppose your friends and you are having fun in your classroom. You assigned one of your friends as an informer who will give you a signal if he sees a teacher coming.

In programming, signals are callables which are called before/after an event.

Read More

Page 1 of 4

Powered by WordPress & Theme by Anders Norén