Category: Django Page 1 of 3

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

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.

Or,

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

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

How to Customize Middlewares In Django

What is middleware?

Middleware is a framework of hooks which works as a ‘plugin’ between Django’s request/response processing. In other words a middleware is a callable that takes a request and returns a response just like a view. Each middleware component is responsible for doing some specific task.

In simple word middlewares are Mediators between client & view.

Let me clear the concept with an example:

Suppose you want to send a letter to your best friend through a post office. You completed the letter & went to post office, but post master told you that you didn't follow the perfect rules to send a letter. Then you corrected it. After that the postmaster received it & sent it to the post office nearer to your friends home. A postman will take the letter from there & deliver it to your friends home. Here, a problem can be happened too. If you make mistake in writing the address then it won't be possible to deliver. But if everything is okey the letter will be delivered on time. Then by following the same procedure your friend can send you a response.

Read More

Serving StaticFiles In Django Project

What are static files?

Files used for making beautiful user interface, interactive user experience and functional web pages are called static files. They do not change when a application is running. They aren’t dynamically generated by Python web server. Most common static-files in a typical web application  are the following types:

  • CSS (Cascading Style Sheets)
  • JavaScript
  • Images

Static files are important for a Django project because the modern web requires more than dynamically generated HTML markup. Let’s see how to configure an application to serve static files. After that we will work with some examples.

Read More

Cookie in Django | Django Tutorial

What is Cookie?

A cookie is a small piece of text file that contains data. The data in the cookie is often a random key or token. The server use a cookie to identify a client. Specific cookie known as HTTP cookie is used to identify a specific user and to keep track of that user's movements within the site.

Suppose, you have visited a shop for the first time & bought some cloths of your favorite color. The owner has given you a membership card. Now, if you go again, he might not remember your face but he will recognize the card issued by his shop & can find your buying history & can serve you well. Here, the shop is the web server, you are the client and the membership card is the cookie. As the membership card will not be valid for other shops similarly a cookie won’t be valid for a different website.

Read More

Django Sessions | Django Tutorial

Communication between web browsers (clients) and servers is completed via HTTP( Hyper Text Transfer Protocol). It is a stateless protocol. This means a HTTP server does not keep track of any state information. The server will not remember whether a client has visited it before. Each time a client visits the server behaves with it as a new client. The sessions make a stateless protocol stateful.

Django has a session framework which handles cookies. In cookies we store session_key. It is a unique 32-character-long random string. A session_key can be considered as a token (a sequence of characters). It identifies a unique session within a particular web application. Sessions are used to abstract the receiving and sending of cookies, data is saved on server-side, and a session_key is stored in the client-side cookie for identification.

Read More

Page 1 of 3

Powered by WordPress & Theme by Anders Norén