Month: June 2021

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.

# EXPORT AS CSV
class ExportCsvMixin:
    def export_as_csv(self, request, queryset):
        meta = self.model._meta
        field_names = [field.name for field in meta.fields]
        response = HttpResponse(content_type='text/csv')
        response['Content-Disposition'] = 'attachment; filename={}.csv'.format(meta)
        writer = csv.writer(response)
        writer.writerow(field_names)
        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

Powered by WordPress & Theme by Anders Norén