Back to Top

Django Tutorial for beginners

Django Tutorial for beginners

I find the Django very useful because it has a faster variable prototype. Django takes away many functionalities and complexities. Django is built in all kind of package full approach and it’s a multiple framework in one. So, let’s understand how Django is the quick variable prototype and ready for production.

The Django Tagline says “The Web Framework for perfectionists with deadlines“. They have made Django keeping in mind that developer can deliver products very quickly and have to be perfect.

The way they have achieved is Django is opinionated framework before it was cool. Now what is opinionated framework? It means, When the develop this framework, they had certain notions of how the each things should be done. Let’s say if you want to connect to database,how connection to database should happen in web framework or if you want to upload file so they have a some notions how to do with the file. They developed Django framework in such way that certain things happen in certain way only so that’s what opinionated framework in all about. Right now so many opinionated frameworks are available in market which includes spring boot and laravel also.

The great thing about the Django framework is they provides many sensible defaults as it works out of the box, you don’t need to configure before you start working on it or start the application.

  • Batteries included approach: It follows the batteries included approach, now many of the framework i have seen they only take care of the one of the part of whole web application development lifecycle. Django is very much different in such case, Django includes everything end to end for developing web application. You name it and django has it. It has own ORM, own templating library, own backend view and also has own server also so that way when you start with Django you don’t have to integrate any other frameworks, it works just out of the box. 🙂 As soon as you install it, you can start working on it.
  • Model view template pattern: Pattern that Django follow is Model View Template pattern. This is bit contrast then the MVC pattern that they follow. MVC pattern works in model,the data come from model , view is the representation part and controller take care of model and view business logic. The Django is contrast that this pattern.

    Here the representation part they called as template which is handled by the Django own templating library, the model part like the connection of database or representation of your domain entities is taken care by own ORM, you don’t need to integrate any other framework. View will accept the request and as per the code, will display the response, rest everything is up to you, whatever you want to do, you can achieve it to display in view. Apart from heading this flexibility, they know the most of the time developers do the CRUD operations. To handle the CRUD operation easily and out of the box, Django provides various views which can take care of the operations, You can simply define the which model you want to use for the CRUD and Django simply provide the generic views which you can use for your application and you don’t need to write single line of code.

  • Mature: Django is very mature framework, it came in July 2005 and it is still going strong and Django listen the feedback from the community and also build features based on that. One of the feature is migration which is great feature to have when you handle the database versioning.
  • Support by vast community: If you search in stackoverflow about Django,you can get help with your query.For a developer it is a great thing that someone who can answer your question if you get stucks somewhere so you can finds the answers easily that is very helpful to the developer.
  • Everything is in App: In Django, there is notion that everything is in app. Every module you create in the Django, for example, comment module, user module or event module is called an App. Why Django have this approach that everything is in app? An App can have everything that handles web stack request, it can have its own template, own views,own models and they are coupled in such a way that they don’t even need to communicate with each other. Django have separate routers and every url or app routed to the specific url. You can plug your apps in Django in such a way it can use particular separate url without communicating with any other.

Also, it supports multiple data stores.You can configure so that app1 can use data store1 and another app can use another data store which is the great way to keep your database separate from your app and third party app.

Now, There are the certain good thing about having this approach,so let’s understand it.

Django-everything-is-in-app

  1. Great isolation: In Django, Every content and static resources to their own Django templates ,model and views. So in a way, they are like a pluggable things.You can simply put in your app and it should work. You just have to provide routing to that app and it will work.
  2. Well defined interface: Django give you well defined interface.When your are doing some loose coupling, Django force you to have well defined interfaces.
  3. Pluggable functionalities: It supports pluggable functionalities. Now suppose Let’s consider your company is running Django stack and there is some functionality like managing users in each and every app. What you can do is, You can develop a separate app which can plug into any app.This way is good for packaging the third party app.
  4. This Good for packaging/distribution of third party app: Django provides pluggable functionalities so which is good for packaging or distribution of third party application. Also,The modular approach provides greater flexibility to the developer while developing Django apps. One of the good example of it is Django provides own admin panel using that you can view the CURD operation on database. Admin panel is a part of core functionality and developed as an app so you can plug it if you want.

Next topic is Django Auth. Let’s understand the Django Auth. I would always recommend that you don’t ever need to write own OAuth implementation.

Auth

  1. Work out of box: First of all, Basic use of auth is user management, permission management and reset or forget password functionalities. Those things are main functionalities in most of the application.Why should you write the functionalities? And the Best is Django framework provides Auth for those functionalities and if you want to use it, you just need to provide url for routing, html template which will point to the view.
  2. Object/action level permission: Django framework have object/action level permission. Let’s have an entity call comment so on model level if you want to define permission based on action can be possible through it. For example, you want to allow specific user to add comment based on roles, you can restrict them in that way. It provides role based control for models.It also provides grouping so you can group various permission together and can create group and assign users to group.
  3. Tools for restricting access: Apart from the permission, Django have tools for restricting the access to users. Let’s say you have created the permission but how to use check those permissions so in your views, whenever you are writing a permission,Django provide a way to check that whether that user (request.user) have the permission,it will redirect to login page or give the permission denied message if user doesn’t have the access.
  4. Customized model: Django built in such a way that you can control each and every level of it.
  5. Pluggable backend -LDAP/oAuth:Authentication in Django is built in concept of Auth backends.one of the default auth backed would be database auth backend which would go to database,check users whether it is valid user or not.

If you want to do LDAP integration,You don’t have to write the whole functionalities all over again. You just have to provide ldap auth Backend instead of checking in the database which will go to LDAP service and validate the user and return the user credentials so that you can club you own auth inside existing app and everything else work as it is. Similar way you can integrate OAuth also.

ORM

ORM is one of the coolest features of Django.The feature I like the most.

First of letting me explain what ORM is for those who are not clear when you write database query, you need to convert to data object so not to allow raw SQL queries so Django came with the concept of Object-Relational mapping(ORM) which maps your object to database tables. You can perform the simple operation on the object and your object imitated with the database and you don’t need to write a single line of SQL queries.

  1. Modelling – Never check your database again. The way the modeling works is you define some class which called model and it extends the interface to define the field. Also support many to many relationship with custom fields. Django provides the configuration to migrate the table so you don’t need to go the database and can do your changes.
  2. Cross Database: It provides the cross database support.Right now it supports SQLite as default and others are MySQL and PostgreSQL.
  3. Extensible: Almost of all kind of functionalities supported by the Database you can use. You can develop your own field also.
  4. Transaction Management: Django works on auto commit mode by default but you can overwrite this using the setting Django provides. Using that setting, when it receive the request,start the transaction and till the time response is actually returned so that will be part of the single transaction otherwise if exception is raised by the Django and rollback the transaction.
  5. Migrations: Migration feature was added in Django as inbuilt feature.

Migrations in Django

After configuring your ORM, ORM takes care of database connection and queries but what if table itself is not present in the database.In that case, you can create ALTER or CREATE query before perfoming operation but not to do that manually, it is perfomed through the code which is the concept of Migration.

  1. Auto change detection:You have created models and you want to create corresponding tables into your database. For that you need to write code so for that Django provides package called South Migrations. You just have to create models and run the single command,it will check the corresponding change available in database,if not it will apply the changes. All the changes is automatically detected by the Django so migration is easy.
  2. Forward and backward: You can apply migration to the simple python file. You can go back and forth whenever you want to.
  3. Data migrations: Data migration is helpful to execute the database specific request to perform the migrations. You can write your own code for migration which actually takes the data from json file and inject into the ORM. That way you have default data and data migrations.
  4. Custom migrations – Automatic FTW!!! This is the feature i would explain through the demo example.

Basic Demo of Django Application

Create an empty migration file.As you can see it contain the main migration class. You can define the dependency on migration class,here it is defined too where dependency of other class can be defined. In that defined some operations where provided list of things.

.py

Whenever apply the migration and something went wrong and not able to connect to the database or any exception raised, you can write callback also so Runpython has two parameters, one is to perform the action and second is to revert the action if any error or exception occur.

Whenever your app is deploy to the production, you want to make some changes like enable elastic search index or to change the path in config so that way you can write code in it so when your migration will apply, this code will be executed.

Automated migration is also provided by Django, Earlier the deployment instruction was like this.

Deployment_instruction file:

  1. Deploy my_app.rar
  2. Extract db_queries.
  3. Run Schema
  4. etc
  5. etc

This is the manual thing. You actually have to go to the database and execute queries. Upload files to the server etc.
If you have Django latest version, you just need to perform two steps:

There are no more steps

Internationalization in Django

This is one of the great features if you want to develop the international site which supports multi languages.

There some good point for Internationalization

  1. Easy to integrate: Internationalization in Django works in two things. First, wrap every string in your application inside a wrapper function.After that, they have the facility to detect all those strings along your app.When you run the command,it will look for wrapper function and put it in standard translation file (.po extension file). In that define the languages you want to use and translate.Anyway, Django does not do the auto translation.It is a manual thing but same as another framework so very easy to understand and apply.
  2. Support for variables / date / plurals / numbers / timezones: It also supports different types of declaration. You can differentiate date format based on the country using timezone, variable, and date. You can manage count for string display using plurals.You can differentiate locale phone number display using numbers.
  3. Automatic locale detection: For auto detection, Django have middleware. Based on that it would actually detect the what is the language and which translator file is for that.If translator not found, it will provide the default language string.
  4. Aligned with gettext: Whole concept of writing string inside the function, detecting it ,creating .po file,generating a translation format and loading it into an application.These all thing can be done using gettext.Gettext is GNU program which is one of the earliest stage to render the serialization.

Why Django?

Here are the some good features of the Django which will convince you to use Django.

  1. Secure by default: Now what Django developer’s believe,is that there should be sensible defaults. So sensible Default is, there are many frameworks which provides so many features but you have to write configuration going in the file before you can use it whereas Django provides sensible defaults for this.
  2. SQL injection prevention: Since you are using ORM and all the data that you query through the ORM so SQL queries like 1=1, all those things will be escaped when use ORM.You don’t have to worry about SQL injection anymore until and unless you are writing your raw queries.In that case, It is up to you to sanitize your input or not.
  3. XSS protection: Cross scripting protection is the way, whenever end user try to injecting a javascript in search,it will execute the JavaScript rather than displaying it if you are not taking care of it. If writing javascript alert hello into some inputs and have facility that whatever inputs in that will be display over the page.it will not execute the javascript because whatever write in Django is auto-escapes.
  4. CSRF protection: CSRF protection works in that,it has middleware which will inject a code in every request in a cookie and called CSRF cookie and in the response,it would ask for the cookie and if the cookie does not exist,it will not allow continuing. Example, If you want to send data through POST,and send malicious link though it and user is already logged to the website so it will execute user’s own session when user click on the button.
  5. Clickjacking protection: Clickjacking protection is to restrict others to load your website in iframe with the x-frame option so others can’t display your content on their site as their content and when user session will get associate with that.Clickjacking protected site will not be loaded into the iframe.
  6. Password Hashing: Many of the times write own custom logic to hash the password when a store in the database for security because it is not available in the database so Django provides you set of choices to do your password hashing. By default, it has MD5 Hashing.Whenever you store it,it will automatically hash your password.

Django Rest Framework:

REST is a Representational State Transfer,every request you do it should be HTTP request and instead of rendering on the server side and output to the browser, the server will just provide data.

Django Rest Framework does not provide concept of REST.

  1. Extend Django philosophy
  2. CRUD in minutes
  3. Customizable to the core
  4. Browsable APIs – Big win for API consumers
  5. API Documentation

Example:

Here is the basic example of Django Rest framework. Here import the MovieSerializer, movie, and ListCreateApiView before the class.

Django Goodies:

Django provides the good list of goodies which helps the developer to easily handles the Django in development and production.

  1. Debug toolbar: Debug toolbar is very helpful goodies Django provides,Developer can easily get the idea when an issue occurs and in production server, you can quickly handle the errors or exception.
    Management commands: Management commands helps to manage the Django.
  2. Error Reporting: You can always use the DEBUG setting. This will make servers to run faster, will prevent a malicious user sees the error page. Django can be configured to generate a report with the details of the error.
  3. Admin: Django provides Build-in ready to use admin interface as admin panel so you can easily do the configuration from the UI.
  4. Config-as-code: You can write the code to for the custom configuration you want to set in Django.

Django HayStack:

Django HayStack is an abstract API provided for the search engines.

  • Built for full text search
  • Seamless integration with Django ORM
  • ORM like querying interface
  • Automatic Sync
  • Spatial Search
  • Pluggable indexing backends – Solr, ElasticSearch and more

HAYSTACK_SIGNAL_PROCESSOR for real-time processing. HAYSTACK_CONNECTIONS is configured using the search engine.

Faster Iteration

  1. No compiling
  2. No build steps required
  3. No packaging required
  4. Hot deploy

I hope this is useful to you. If you find it useful please bookmark RSS.Don’t forget to share your views in the comment box and also share this post on social media and with your friends.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Most Popular Posts

how to use the CSS3 Gradient Effect

Posted on 6 years ago

Zinal

The Readers’ Poll – September 2012

Posted on 5 years ago

Bhumi