YOU NEED to Learn Python in 2022! (Business Perspective)

Python is one of the easiest programming languages to get started with. For this reason, the community keeps growing every month.

Because of its simplicity (of the Syntax), Python has become the most popular language.

Besides, Python helps Engineers build great products in many industries and professional domains.
The Programmer’s life gets easier when it comes to having a look at Python.



What about the Python Business Market size?

market-size-market-share.jpg

Python is an open-source language, which means that anyone can use it. However, if you look to an industry such as data analytics, in which Python can be used, the market value is over $10 billion.

Shared by futurelearn.com



Here are the top 10 most common uses of Python by industry

pandemic-hero.png

▪ Insurance: Creating business insights with machine learning.

▪ Retail Banking: Flexible data transformation and manipulation.

▪ Aerospace: Meeting software system deadlines.

▪ Finance: Data mining to identify cross-sell opportunities.

▪ Business Services: API access to financial information

▪ Hardware: Automating network administration

▪ Healthcare: Predicting disease prognosis

▪ Consulting Services: Bespoke web development

▪ InfoTech: IT modernization

▪ Software: Adding extensibility to legacy applications

Shared by appdevelopermagazine.com



Here are 5 World-Class Software Companies That Use Python

COTW-TechAcquisitions-Shareable-2.jpg
(Photo by Visual Capitalist)

Google, Meta (Facebook), Instagram, Netflix, Instagram.
There are plenty of companies searching for Python Developers around the globe.



Hence, I created this Blog to help you out!

Design-Blog-Page-Python.jpg

Hence, Learning Python helps you create Opportunities from jobs to Building Products people use.
I just got into Full-stack development using Python Software Development, React + Python as Tech Stack.



Make sure to follow CodeWithKenn for more articles about:

➞ Learning Python in simple terms

➞ Building Side Projects and SaaS using React + Python

➞ Getting useful Resources and tips for your coding Journey

Stay tuned! More articles are coming out! Feel free to comment and share the articles to support me 🤙



🌎 Let’s connect

Want to start blogging? 🔥Join NOW!




Source link

How to host a Django project on Heroku (for free)

This step-by-step beginner tutorial will teach you how to host your local Django project on Heroku for free. I haven’t found many easy to follow tutorials on this topic so I decided to make my own after hosting many projects with the mentioned steps. Enjoy!



Steps

  • Create and activate a virtualenv, install dependancies.
python -m venv <env_name> # Windows
python3 -m venv <env_name> # Other

envScriptsactivate # Windows
source venv/bin/activate # Other
  • Initialize a git repository (git init)
  • Add a .gitignore file

Suggested gitignore for Django

  • Add the following to settings.py:
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
python-3.10.1
  • Install gunicorn:
pip install gunicorn
  • Create Procfile and add the following:
web: gunicorn myproject.wsgi
  • Install django-on-heroku:
pip install django-on-heroku
  • Add the following to settings.py:
# Configure Django App for Heroku.
import django_on_heroku
django_on_heroku.settings(locals())
  • Add requirements.txt by running:
pip freeze > requirements.txt
  • Commit your changes:
git add .
git commit -m "Init commit"
  • Login to heroku from the command line:
heroku login
  • Create a new app:
heroku create app_name
  • Add your heroku app to ALLOWED_HOSTS:
ALLOWED_HOSTS = ['your_app_name.herokuapp.com', ...]
  • Commit your changes:
git add .
git commit -m "Configure ALLOWED_HOSTS"
  • Push your changes to heroku branch:
git push heroku master # Or branch name
  • Migrate your database:
heroku run python manage.py migrate
  • Make sure you have DEBUG = False in your settings.py file.



Extras

  • Open your app online:
heroku open
  • Create admin account:
heroku run python manage.py createsuperuser
  • If you have static files, run:
heroku run python manage.py collectstatic

Source link

Telegram bot with Django

Hi everyone. Recently I faced a problem with integrating the Telegram bot with Django. At first look, it looks very simple. There are several ways you can connect them. I think most of you will use API to integrate them. But it is a hard way of implementing this. Using this method you will need to open API in Django, make the authorization through REST API, write methods separately for Telegram bot and so more… It is an effective way if you have a simple Django application. But in my project, It would take much more time, because it was a complicated project. So I started looking for a simpler way of implementing it. After surfing the internet for several days and finding several wrong ways of it, I found the right method. And this method made my work much simpler, so I don’t need to open the API from Django and write separate methods for the Telegram bot. The bot works directly from the Django server. It turns on when you start the Django server and turns off when you shut the server off. And I want to share this method with you.

First, you should set a webhook for your bot, so Telegram knows where to send requests for your bot. In this step, you will need a production server set, because the localhost is not reachable for Telegram. If you want to set webhook with your local machine, I recommend you use NGROK. It allows you to make your local server for public usage. After you configure your production server go to https://api.telegram.org/botYOUR-TOKEN/setWebhook?url=YOUR-URL . This website should return a response like below

"ok":true,"result":true,"description":"Webhook was set"

After the webhook is set, just copy the code from my GitHub Gist and paste it to your Django project. And, of course, write your bot token in the appropriate place.

I hope you will like this method.


Source link

Django Basics: Creating Models



Introduction

We have seen the basics of Django templating in the previous parts of the series. Now, we can move on to the more backend stuff in Django which deals with the Databases, queries, admin section, and so on. In this particular part, we’ll cover the fundamental part of any application in Django i.e the Model. We’ll understand what the model is, how to structure one, how to create relationships and add constraints on the fields, etc.



What are Models?

A model is a Django-way(Pythonic) to structure a database for a given application. It is technically a class that can act as a table in a database generally and inside of the class, the properties of it act as the attributes of that database. It’s that simple. Just a blueprint to create a table in a database, don’t worry about what and where is our database. We will explore the database and its configuration in the next part.

By creating a model, you don’t have to write all the basic SQL queries like

CREATE TABLE NAME(
attrb1_name type,
attrb2_name type,
.
.
.
);

If your application is quite big or is complex in terms of the relations among the entities, writing SQL queries manually is a daunting task and also quite repetitive at times. So Django handles all the SQL crap out of the way for the programmer. So Models are just a Pythonic way to create a table for the project/application’s database.



How to create a Model?

Creating a model for an application is as easy as creating a class in python. But hey! It’s more than that as there are other questions to address while designing the class. You need to design the database before defining the fields in the model.

OK, well it’s not straightforward as it seems to but still for creating simple and dummy projects to start with. You can use certain tools like lucidchart, dbdiagrams.io, and other tools you are comfortable with. It’s important to visualize the database schema or the structure of the application before tinkering with the actual database inside the project. Let’s not go too crazy and design a simple model to understand the process.

Here’s a basic model for a Blog:

#from django.db import models
from django.contrib.auth.models import User

class Article(models.Model):
    title = models.CharField(max_length=255)
    post = models.TextField()
    author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="Article")
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

Ignore the from django.db import models as it is already in the file created by Django. If not, please uncomment the line and that should be good to go.
This is a basic model you might wanna play with but don’t dump it anywhere.

We define or create our models in the application inside the project. Inside the application there is already a file called models.py just append the above code into it. The application can be any application which makes the most sense to you or better create a app if not already created and name it as article or post or anything you like.

If you are familiar with Python OOP(object-oriented programming), we have basically inherited the models.Model class from the django.db module into our model.

If you want more such examples, let’s see more such models :

An E-Mail application core model. Attributes like sender, subject of the mail, body of the mail, recipients_list i.e. the To: section in a mail system and the attachment_file for a file attachment to a mail if any.

#from django.db import models
from user import EmailUser

class EMail(models.Model):
    sender = models.EmailField(max_length = 255) 
    subject = models.CharField(max_length = 78)
    body = models.CharField(max_length = 40000)
    recipients_list = models.ManyToManyField(EmailUser, related_name="mail_list")
    attachment_file = models.FileField(blank=True)

A sample model for a note-taking app, consisting of a Note and a Book. A book might be a collection of multiple notes i.e. a single book can have multiple notes so we are using a ManyToManyField, what is that? We’ll see that shortly.

from django.db import models
from user.models import User

class Notes(models.Model):
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField(max_length = 1024)
    content = models.Textfield()
    created = models.DateTimeField(auto_now_add = True)
    modified = models.DateTimeField(auto_now = True)
    book = models.ManyToManyField(Book, related_name="book")

class Book():
    name = models.CharField(max_length = 1024)

These are just dummies and are not recommended to use anywhere especially in a serious project.
So, we have seen a model, but what are these fields and the constraints like on_delete, max_length, and others in the upcoming section on fields.



Fields in Django

Fields are technically the attributes of the class which here is the model, but they are further treated as a attribute in a table of a database. So the model becomes a list of attributes which will be then parsed into an actual database.

By creating attributes inside a class we are defining the structure for a table. We have several types of fields defined already by django for the ease of validating and making a constrained setup for the database schema.

Let’s look at some of the types of fields in Django Models.



Types of Fields

Django has a lot of fields defined in the models class. If you want to go through all the fields, you read through the django docs field references. We can access the fields from the models module like name = models.CharField(max_length=10), this is a example of defining a attributes name which is a CharField. We can set the max_length which acts a constraint to the attribute as we do not want the name field to be greater than 10 and hence parsing the parameter max_length to 10.

We have other field types like:

  • IntegerField -> for an integer value.
  • TextField -> for long input of text (like text area in html).
  • EmailField -> for an single valid email field.
  • DateField -> for inputting in a date format.
  • URLField -> for input a URL field.
  • BooleanField -> for a boolean value input.

And there are other fields as well which can be used as per requirements.

We also have some other fields which are not directly fields so to speak but are kind of relationship defining fields like:

  • ForeignKey -> Define a many-to-one relationship to another model/class.
  • ManyToManyField -> define a many-to-many relationship to another model/class.
  • OneToOneField -> define a one to one relationship between different tables/model/class.

So, that’s about the field types for just a feel of how to structure or design a database table using a model with some types of attributes. We also need to talk about constraints which needs to added to the fields inside the models.



Field Options/Arguments

We can add constraints and pass arguments to the fields in the models. We can add arguments like null, blank, defualt, choices, etc.

  • null=True/False -> Set a check for the entry in the table as not null in the database.
  • blank=True/False -> Set a check for the input validation to empty or not.
  • unique=True/False -> Set a constraint to make the entry unique throughout the table.
  • defualt=anyvalue -> Set a default value for the field.
  • choices=list -> Set a list of defined choices to select in the field (a list of two valued tuple).

We also have another constraint specific to the fields like max_length for CharField, on_delete for ForeignKey which can be used as a controller for the model when the related model is deleted, verbose_name to set a different name for referencing the entry in the table/model from the admin section compared to the default name of the model, verbose_name_plural similar to the verbose_name but for referencing the entire table/model. Also auto_now_add and auto_now for DateTimeField so as to set the current date-time by default.

More options and arguments that can be passed to the fields in models are given in the django docs field options

These are some of the options or arguments that we can or need to pass to the fields to set up a constrained schema for our database.



Meta class

Meta class is a nested class inside the model class which is most of the times used for ordering the entries(objects) in the table, managing permissions for accessing the model, add constraints to the models related to the attributes/fields inside it, etc.

You can read about the functionalities of the Meta class in the documentation.



Model methods

As a class can have functions, so does a model as it is a Python class after all. We can create kind of a helper methods/functions inside the model. The model class provides a helpful __str__() function which is used to rename an object from the database. We also have other predefined helper functions like get_absolute_url that generates the URL and returns it for further redirection or rendering.

Also, you can define the custom functions that can be used as to help the attributes inside the model class.



Django ORM

Django has an Object Relational Mapper is the core concept in Django or the component in Django that allows us to interact with the database without the programmer writing SQL/DB queries. It is like a Pythonic way to write and execute sql queries, it basically abstracts away the layer to manually write SQL queries.

We’ll explore the details of how the ORM works under the hood but it’s really interesting and fascinating for a Beginner to make web applications without learning SQL(not recommended though personally). For now, its just magical to see Django handling the DB operations for you. You can get the references for learning about the Queryset in ORM from the docs



Example Model

Let us set up a model from what we have learned so far.

We’ll create a model for a Blog Post again but with more robust fields and structure.

#from django.db import models
from django.contrib.auth.models import User

class Article(models.Model):

    options = (
    ('draft', 'Draft'),
    ('published', 'Published'),
    )

    title = models.CharField(max_length=255, unique=True)
    slug = models.SlugField(max_length=255, unique_for_date="publish")
    post = models.TextField()
    author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="Posts")
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    status = models.CharField(max_length=16, choices=option, default="draft")

    def __str__()
        return self.title

    class Meta:
        ordering = ('-publish',)

We can see in the above model that we have defined the Meta class which is optional and is generally written to modify how to entries inside the table appear or order with other functionalities as well. We have also added the choices option in the status field which has two choices Draft and Publish one which is seen by the django interface and the other to the end-users. We have also added certain fields like slug that will create the URL for the blog post, also certain options like unique has been set to restrict duplicate entries being posted to the database. The related_name in the ForeignKey refers to the name given to the relation from the Article model to the User model in this case.

So, we can see that Django allows us to structure the schema of a database. Though nothing is seen as an end result, when we configure and migrate the model to our database we will see the results of the hard work spent in creating and designing the model.



Database Specific fields

By this time, you will have gotten a feel of what a database might be. Most of the projects are designed around SQL databases but No-SQL databases and others are also used in cases which suite them the most. We have tools to manage this database in SQL we call it the Database Management System (DBMS). It’s just a tool to manage data, but there is not just a single Database management tool out there, there are gazillions and bazillions of them. Most popular include MySQL, PostgreSQL, SQLite, Oracle, Microsoft Access, Maria DB, and tons of others.

Well, these different DBMS tools are almost similar with a few hiccups here and there. So, different Database tools might have different fields they provide. For Example, in Database PostgreSQL provides the ListField which SQLite doesn’t that can be the decision to be taken before creating any project. There might be some fields that some DBMS provide and other doesn’t.



Conclusion

We understood the basics of creating a model. We didn’t touch on the database yet but the next part is all about configuration and migration so we’ll get hands-on with the databases. We covered how to structure our database, how to write fields in the model, add constraints and logic to them and explore the terminologies in Django like ORM, Database Types, etc.

Thank you for reading the article, if you have any feedback kindly let me know, and until then Happy Coding 🙂


Source link

Progressive Enhancement in Django vs Remix

In this post, I want to tell you a quick story about one of the reasons I love Remix: super simple progressive enhancement.

A couple years ago, my team at work was tasked with creating a new application that would be used internally by our sales reps. The tool needed to allow reps to quickly search through our available products and build quotes to send to customers. For various reasons, we decided to build the app with Django.

Django is awesome. One thing I love about Django (and similar frameworks like Rails) is that you render your HTML server-side. The way you do this in Django is with their Django template language, which is an extension of HTML that allows you to reuse HTML files, and embed if statements, for loops and other custom logic. Rendering HTML server-side means you can talk directly to your database and you don’t have to create “API routes” to retrieve data from the browser with JavaScript.

In fact, you don’t have to include any JavaScript at all in your app if you don’t want to. In Django, you use HTML forms for user input, which is enough to create a functional app. This is what the first version of our quoting app at work did. There was no JavaScript; it was just server-rendered HTML with HTML forms for data mutations.

However, the sales team started asking for the fancier user experiences that are expected from modern applications. In other words, they were asking for some progressive enhancement. These modern user experiences simply can’t be done without JavaScript on the page, and this is where Django’s SSR model kind of left us hanging.

JavaScript kind of feels like an afterthought in Django. Django’s solution to JavaScript is to just do what you do on any web page: write some JavaScript in a file and include it with a <script /> tag in your HTML. The nice thing about this is that you have full control over which JavaScript files are loaded on any given page, so your network tab stays clean.

The problem with this approach is that you end up writing a lot of your server-side logic again in your JavaScript. For example, in a To-Do app, you might have a list of to-dos and a detail view that changes as you click on each one. If you want the ability to switch out the detail view client-side without making a full document request, you’ll have to write some JavaScript to 1) make a request to your server to get the to-do data and 2) manually replace the old detail view in the DOM, thereby duplicating some of the render logic that was in your Django template. This also means you have to add an API route for the JavaScript to talk to. This one example is not a ton of extra work, but it can add up quickly and get messy if you need a lot of interactivity.

We eventually needed enough interactivity in our quoting app that it was pretty difficult to maintain. We decided it would make our lives easier as developers to convert the entire front end to a React SPA and just use Django for the API routes and talking to the database. This solved our maintenance problems, and handling data was made easy with React Query, but I still felt like we had lost something.

For one, we were now sending a lot more JavaScript across the network because all of our app logic was now client-side. For two, we now had request waterfalls and spinners all over the place, instead of a single document load with all the data already there.

It was around the time I was thinking about these problems that I heard about Remix. I bought a supporter license and dove in, and I immediately knew it was the solution I was looking for.

Remix gives you all the benefits of server-side rendering while also making the transition to interactivity on the client completely seamless. All it takes is one <Script /> element in your root route and boom, your app is now running React in the browser, doing client-side route transitions. There’s no need to write any new logic at all. No extra JavaScript, no API routes, nothing. This is due to a couple things. First, since React can render HTML on the server and run in the browser, you don’t have to re-create your server-rendering logic on the client. So instead of using a template language on the server and JavaScript in the browser, I can just write React code once and use it in both places. Second, Remix takes care of creating and calling API routes for you. Your loader functions are used during the initial server render, and they are automatically made available as endpoints and called from the client on page or layout transitions.

Remix also lets you control which pages are interactive. If one page needs JavaScript but another doesn’t, you can include JavaScript only on the page that needs it. This allows me to retain a lot of that control over the network tab that I had in Django.

If you want to get fancy with forms and do form submissions client-side without a document refresh, you just have to switch from <form> to Remix’s <Form>. Remix will then prevent the default refresh behavior, call an endpoint that runs your action for that route, and call all the loaders for that route so the data on the page stays up to date. It’s the same behavior the browser gives you, but without the page refresh!

And therein lies the reason I love Remix’s approach to progressive enhancement so much. Remix doesn’t stray too far from the default browser behavior, which not only means you can fall back on default browser behavior if your user has a spotty connection and JavaScript fails to load, but you also learn to think in terms of how the browser behaves, which is transferrable knowledge you can use outside of Remix.

There are so many things I love about Remix, but the way it makes progressively enhancing apps with JavaScript so easy is one of my favorite things about it. Thanks for reading. 🙂

Photo by Andy Holmes on Unsplash


Source link

Connecting High School Students to Internships – Interniac

Given how competitive University admissions are and how often the average University student changes majors due to career confusion, getting a high school internship is more valuable than ever before. However, pre-university work experience is difficult to come by and oftentimes opportunities are given to students who have strong networks (either through a parent or their school). Today, there is no platform through which high school students all over the country can find an internship on their own. We aim to build a platform that supports high schoolers attending public schools and empowers businesses in hiring bright students. Interniac fills the gap in our education system by simplifying the process for employers to start internship programs and source candidates who are eager to gain valuable out-of-the-classroom work experience.

Our mission is to bring you opportunities, whether that be an internship or a chance to speak to professionals in the field you are interested in. We strive to help you build your future. Join our platform to learn more about what opportunities Interniac can offer you!

Please check out this OPENSOURCE project here and don’t forget to leave a star!
https://www.github.com/interniac/Interniac-website


Source link

10 Best Forum to become a good Developer in 2022

This is the list of some top 5 growing programming related forums/communities you must join. These forums may help you to get your answers for bug fixes and related topics. Also, joining this forum may help you to be a good developer.

  1. Webmatrices Forum
    A lot of posts of this forum ranks on Google. Also, this forum is nicely popular among new developers. It has the highest Daily Pageviews per Visitor: 6.1 and daily time on site: 5:52. It also has a decent amount of content in it. Users mostly talk about web/app development, game development and blogging/SEO related stuff here. This forum is also growing really fast.
    Suggest you to join this forum if you wanna learn about web development frameworks (Django, vue), API security, web scraping, automation, gameDevelopment and blogging/SEO.
    Visit here: https://webmatrices.com/
    Also, this forum has no ads.

  2. Codeproject
    This forum is somehow popular on the web. According to Alexa rank, it has 1.53 Daily Pageviews per Visitor and 1:50 daily time on site. It has slightly lesser ranks than Webmatrices. The number of content, questions and answers is also pretty good. People generally talk about Python, C++ and Ai related stuff here.
    Visit here: https://www.codeproject.com/

  3. Codeguru
    This website is genuinely awesome for learning OS-related stuff. It has 1.3 Daily Pageviews per Visitor and 1:26 daily time on site. People discuss C programming, Onion architecture, .NET, vb.net and other OS-related stuff. Joining this forum would be great if you wanna about OS. Although there’s a decrement rate in the Alexa rank of this forum website, I guess the rate will be changed soon.
    Visit here: https://forums.codeguru.com/

  4. DaniWeb
    This website is also somehow related to hardware and OS related stuff. Daily Pageviews per Visitor and daily time on site are 1.3 and 1:34 respectively. Members usually discuss VB.NET, Computer Hardware, Python and os related stuff.
    I suggest you join this forum if you really wanna dive more into OS, hardware development and C programming.
    Visit here: https://www.daniweb.com/

  5. thecodingforums
    This forum is the smallest of all mentioned here, but growing really nice. 1.4 Daily Pageviews per Visitor and 0:57 Daily Time on Site is the Alexa report of this site. People here talk about Python GUI, Tkinter, HTML, CSS and Java. I suggest you join this forum if you’re really new to the programming world.
    Visit here: https://www.thecodingforums.com/

As I mentioned, these are growing forums, you are the one who gonna be another growth factor of these forums.

By the way, this is the repost of my last article.


Source link

My Django-Svelte setup for fullstack development



My Django-Svelte workflow for fullstack development



Motivation

I recently discovered Svelte and became my first choice for personal projects and MVP/POCs.

As a backend developer, I struggled a lot with frameworks like React or Vue, looking for a productive workflow. Svelte is dead simple compared to them, in my opinion. And yet very powerful.

However, coming from Django, I still struggled on stuff like security or form validation: if I want a SPA, do I really need to use only Django Rest Framework and implement everything through REST API?
Take authentication for example: Django has built-in views for doing it in a secure way. Do I really need to re-implement it every time client-side using JWT? Looks like a waste of time, for my productivity at least.

I really like Django approach “batteries included”, since it ships with best practices and it makes me a lot more focused on the goal I want to achieve.
On the other hand, I still want the flexibility and reactivity provided by a SPA framework.

So, after multiple projects, I’d like to share in this blog post my personal take aways and show how I scaffold my projects, in order to get:

  • a Django website, using the powerful template system for authentication, registration and password recovery (using Django built in views)
  • a Svelte app served by Django, with hot reloading during development
  • some Rest API to provide data to the SPA app using the awesome Django REST Framework

This way helps me a lot, because it keeps the best of the three worlds without compromising productivity.



About this post

Please consider the following as my personal vademecum for setting up a Django+Svelte project quickly with basic usefules dependencies (such as whitenoise, black…) and authentication (which I haven’t found much covered online).

It is a concentrated boilerplate of my favourites tweaks on Django that made me proficient. Feel free to ignore those who don’t interests you. Any feedback is very welcome.

I’m using Svelte because is my favourite, but the approach should work for Vue and React, with obvious adjustments.

A medium Django/Python and Svelte knowledge is required.



The app



Prerequisites

My tools for the job are:



Setup

My setup is very similar to the one in the DRF quickstart, but I prefer poetry to pip

mkdir django-svelte-sample-app
cd django-svelte-sample-app



Django setup

For poetry init, go for the defaults and add the basic dependencies for our Django project after

poetry init
poetry add django whitenoise
poetry add --dev black --allow-prereleases

Set Django up (note the final dot)

poetry run django-admin startproject myapp .



Svelte setup

npx degit sveltejs/template frontend
cd frontend
npm install
cd ..



Setup

You should have the following structure:

$ find .
.
./frontend
./frontend/README.md
./frontend/rollup.config.js
./frontend/public
./frontend/public/index.html
./frontend/public/global.css
./frontend/public/favicon.png
./frontend/.gitignore
./frontend/package-lock.json
./frontend/package.json
./frontend/scripts
./frontend/scripts/setupTypeScript.js
./frontend/src
./frontend/src/App.svelte
./frontend/src/main.js
./pyproject.toml
./myapp
./myapp/asgi.py
./myapp/__init__.py
./myapp/settings.py
./myapp/urls.py
./myapp/wsgi.py
./manage.py
./poetry.lock
./.venv/....
./frontend/node_modules/...



Code: Django – settings.py

We will configure some settings for Django in order to:

  • enable Django Debug using Environment Variables
  • configure logging
  • read templates from a root folder (instead of subapps templates)
  • managing static files with Whitenoise

We will modify the myapp/settings.py file



Introducing DJANGO_DEBUG

This is very useful when working with Docker or Heroku and you want to dinamically turn on/off the Django debug mode.

Replace

DEBUG=True

with

import os
DEBUG = "DJANGO_DEBUG" in os.environ and os.environ["DJANGO_DEBUG"] == "ON"



Configure logging

I usually configure logging as the following:

logging_level = (
    "INFO" if "LOGGING_LEVEL" not in os.environ else os.environ["LOGGING_LEVEL"]
)

LOGGING = 
    "version": 1,
    "disable_existing_loggers": False,
    "formatters": 
        "console": 
            "format": "[%(asctime)s][%(levelname)8s][%(name)16.16s]@[%(lineno)5s]$ %(message)s"
        ,
    ,
    "handlers": 
        "console": 
            "class": "logging.StreamHandler",
            "formatter": "console",
        ,
    ,
    "root": 
        "handlers": ["console"],
        "level": "WARNING",
        "propagate": False,
    ,
    "loggers": 
        "django.server": 
            "level": "WARNING",
            "handlers": ["console"],
            "propagate": False,
        ,
        "myapp": 
            "level": logging_level,
            "handlers": ["console"],
            "propagate": False,
        ,
    ,

You can now easily change the log level using the LOGGING_LEVEL env variable. Feel free to change the format as you prefer!



Django Template folder

I generally prefer to have all my .html templates inside a root level templates folder instead of every app having appname/templates/appname folder.

Modify the TEMPLATES variable from:

TEMPLATES = [
    
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [],
        "APP_DIRS": True,
        "OPTIONS": 
            "context_processors": [
                "django.template.context_processors.debug",
                "django.template.context_processors.request",
                "django.contrib.auth.context_processors.auth",
                "django.contrib.messages.context_processors.messages",
            ],
        ,
    ,
]

to

TEMPLATES = [
    
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": ["myapp/templates"], # <-- here
        ...
    ,
]

and create the folder:

mkdir -p myapp/templates



Django static files

As mentioned, I really love Whitenoise for serving static files directly from Django. This helps me a lot during development and deploying because I can stay within Django.

We now create a staticfiles folder inside myapp, where files will be collected when we go to production, and the folder that will contain the compiled Svelte files, that will be served as Django static files (we will see it later)

mkdir -p myapp/static/frontend

We need to configure out static configurations accordingly:

STATIC_ROOT = os.path.join(BASE_DIR, "myapp", "staticfiles")
STATIC_URL = "/static/"
STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage"

STATICFILES_DIRS = (os.path.join(BASE_DIR, "myapp", "static"),)

And do not forget to add Whitenoise to the list of middlewares:

MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "whitenoise.middleware.WhiteNoiseMiddleware", # <-- here
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.common.CommonMiddleware",
    ...
]



Finish Django configuration

Let’s complete Django configuration creating applying the migrations and starting up the server, just to be sure no warnings came up

If you want to just check that everything is ok, you can run:

DJANGO_DEBUG=ON poetry run python manage.py makemigrations
DJANGO_DEBUG=ON poetry run python manage.py migrate
DJANGO_DEBUG=ON poetry run python manage.py runserver

You should see

Watching for file changes with StatReloader
[2021-12-09 18:31:03,519][    INFO][django.utils.aut]@[  643]$ Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).
December 09, 2021 - 18:31:03
Django version 4.0, using settings 'myapp.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

So far, so good. We just instructed Django to do some useful stuff through standard configuration. Let’s add the Svelte part in order to see something.



Code: Svelte

For now, we will just expose the Svelte default app from Django.

The idea here is: we will serve the files from Django static/frontend dir and we will develop from Django (ie. localhost:8000) instead of localhost:5000 (default rollup dev server).

All we have to do is configure rollup to emit the build files in the static django folder.
Go to frontend/rollup.config.js and change the export default like this:

export default 
    input: 'src/main.js',
    output: 
        sourcemap: true,
        format: 'iife',
        name: 'app',
        file: '../myapp/static/frontend/bundle.js' // <-- here
    ,
    plugins: [
        ...
        !production && livereload('../myapp/static/frontend'), // <-- here
        ...
    ],
    ...

Move the frontend/public/ files to django

mv frontend/public/favicon.png myapp/static/frontend/
mv frontend/public/global.css myapp/static/frontend/

Now in a terminal starts rollup dev server

cd frontend
npm run dev

And you will see the bundle files created under the Django folder

$ ls myapp/static/frontend
bundle.css     bundle.js      bundle.js.map  favicon.png    global.css     index.html

We will leave the rollup dev server up so that we will have the hot reload while working on the Django side, so leave the server up and change terminal.

In order to serve it from Django, we need to render the template using a standard view



Code: Django – the SPA view

We now create a dedicated Django app that will just render the Svelte app

cd myapp
poetry run django-admin startapp spa
cd ..
mkdir -p myapp/templates/spa
mv frontend/public/index.html myapp/templates/spa/

Replace the content of myapp/spa/views.py with the following:

from django.views.generic import TemplateView

class SpaView(TemplateView):
    template_name = "spa/index.html"

Modify the myapp/templates/spa/index.html using static resources from the frontend

% load static %

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset='utf-8'>
    <meta name='viewport' content='width=device-width,initial-scale=1'>

    <title>Svelte app</title>

    <link rel='icon' type='image/png' href="% static 'frontend/favicon.png' %"> <!-- <-- here -->
    <link rel='stylesheet' href="% static 'frontend/global.css' %"> <!-- <-- here -->
    <link rel='stylesheet' href="% static 'frontend/bundle.css' %"> <!-- <-- here -->

    <script defer src="% static 'frontend/bundle.js' %"></script> <!-- <-- here -->
</head>

<body>
</body>
</html>

Add the view in the myapps/urls.py

# myapps/urls.py
from django.contrib import admin
from django.urls import path

from myapp.spa.views import SpaView  # <-- here

urlpatterns = [
    path("admin/", admin.site.urls),
    path("", SpaView.as_view(), name="spa"),  # <-- here
]

and finally, in order to add it in the installed apps, we need to:

  • modify myapp/spa/apps.py
class SpaConfig(AppConfig):
    default_auto_field = "django.db.models.BigAutoField"
    name = "myapp.spa" # <-- here
  • add myapp.spa in the INSTALLED_APPS in myapp/settings.py
INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    ...
    "django.contrib.staticfiles",
    "myapp.spa", # <-- here
]



Test it

From the root folder of the project (ie the one with the frontend and myapp folders inside), run in two different terminal windows:

# 1st shell - svelte
cd frontend
npm run dev
# 2nd shell - django
DJANGO_DEBUG=ON poetry run python manage.py runserver

Go to localhost:8000 and you will see the Svelte app served directly from Django.

Try changing frontend/src/App.svelte or frontend/src/main.js, hit Ctrl+R and you will see it hot reloaded (from Django. Remember to disable cache or force the browser to refresh the page if you don’t see any change).

Don’t forget that you need the “npm run dev” in background in order to keep sync the bundle.* files under Django static folder.



Secure our SPA the Django way

Now we can leverage the standard Django features, such as authentication.

First, secure our View extending the LoginRequiredMixin. In myapp/spa/views.py

from django.views.generic import TemplateView
from django.contrib.auth.mixins import LoginRequiredMixin


class SpaView(LoginRequiredMixin, TemplateView):
    template_name = "spa/index.html"

To enable auth, add in your myapp/settings.py

from django.urls import reverse_lazy

LOGIN_URL = reverse_lazy("login")
LOGIN_REDIRECT_URL = reverse_lazy("spa")
LOGOUT_REDIRECT_URL = reverse_lazy("spa")

and in myapps/urls.py

from django.contrib import admin
from django.urls import path, include # <-- here

from myapp.spa.views import SpaView

urlpatterns = [
    path("admin/", admin.site.urls),
    path("accounts/", include("django.contrib.auth.urls")), # <-- here
    path("", SpaView.as_view(), name="spa"),
]

Create the login form template:

mkdir -p myapp/templates/registration
touch myapp/templates/registration/login.html

Add the following to myapp/templates/registration/login.html (taken from the django documentation)

<html>

<head></head>

<body>

    % if form.errors %
    <p>Your username and password didn't match. Please try again.</p>
    % endif %

    % if next %
    % if user.is_authenticated %
    <p>Your account doesn't have access to this page. To proceed,
        please login with an account that has access.</p>
    % else %
    <p>Please login to see this page.</p>
    % endif %
    % endif %

    <form method="post" action="% url 'login' %">
        % csrf_token %
        <table>
            <tr>
                <td> form.username.label_tag </td>
                <td> form.username </td>
            </tr>
            <tr>
                <td> form.password.label_tag </td>
                <td> form.password </td>
            </tr>
        </table>

        <input type="submit" value="login">
        <input type="hidden" name="next" value=" next ">
    </form>

    # Assumes you set up the password_reset view in your URLconf #
    <p><a href="% url 'password_reset' %">Lost password?</a></p>
</body>

</html>

Create a super user running in a terminal

poetry run python manage.py createsuperuser

Now if you try to hit localhost:8000, you will be redirected to http://localhost:8000/accounts/login/?next=/.

Try to login with the provided credentials and you will see the Svelte app again.

Hit localhost:8000/accounts/logout to logout.



Rest API

Now we will add a very simple REST API using Django Rest Framework and consume it from the Svelte App.

Note that our Svelte SPA app will leverage DRF SessionAuthentication, since it will invoke the API in the same context of the Django app. This is the most secure way, in my opinion

First, install DRF

poetry add djangorestframework

In addition, since Django 4.0 has just been released, we need to install pytz, since DRF still uses it

poetry add pytz

and add it in myapp/settings.py INSTALLED_APPS

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    'rest_framework', # <-- here
    "myapp.spa",
]

Create a new Django app for the API

cd myapp
poetry run django-admin startapp api
cd ..

Add the mock api in myapp/api/views.py

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import authentication, permissions
from rest_framework.renderers import JSONRenderer


class GreetingApi(APIView):
    authentication_classes = [authentication.SessionAuthentication]
    permission_classes = [permissions.IsAuthenticated]

    renderer_classes = [JSONRenderer]

    def get(self, request, format=None):
        return Response("message": "Hello world")

Note that:

  • we are using the default Django Session Authentication (via login form)
  • the API is available only for authenticated users

Now adjust frontend/src/App.svelte

<script>
    import  onMount  from "svelte";

    export let name;

    let apimessage = "Waiting for server...";

    onMount(async () => 
        let resp = await fetch("/api/greet").then((res) => res.json());
        console.log(resp);
        apimessage = JSON.stringify(resp);
    );
</script>

<main>
    <h1>Hello name!</h1>
    <p>
        Visit the <a href="https://svelte.dev/tutorial">Svelte tutorial</a> to learn
        how to build Svelte apps.
    </p>

    <h3>Data from server</h3>
    apimessage
</main>

Add the API to myapp/urls.py

from django.contrib import admin
from django.urls import path, include

from myapp.spa.views import SpaView
from myapp.api.views import GreetingApi  # <-- here

urlpatterns = [
    path("admin/", admin.site.urls),
    path("accounts/", include("django.contrib.auth.urls")),
    path("api/greet", GreetingApi.as_view()),  # <-- here
    path("", SpaView.as_view(), name="spa"),
]

Hit localhost:8000, login and enjoy your Django based SPA using Server Side Authentication and Rest API



Building for Production

In order to make our app ready to Production, we need:

  1. Gunicorn installed
poetry add gunicorn
  1. collect all static files
poetry run python manage.py collectstatic
  1. configure the allowed hosts
#myapp/settings.py
# change ALLOWED_HOSTS = [] to
ALLOWED_HOSTS = ["localhost"]

Now you are ready to run

poetry run gunicorn myapp.wsgi

Go to localhost:8000 and enjoy your gunicorn served app



Conclusions

In this quite long walkthrough, we saw different things:

  1. set up a Django app with my personal useful tweaks
  2. set up an integrated Svelte app served by Django
  3. configure Django built-in authentication to secure our SPA
  4. providing some Rest API for the SPA to consume
  5. packing everything up for Production

You can find all the code here on github.

I hope this post can help you make your life as developer easier. I’m going to add other posts integrating Docker/Docker compose and some utility scripts for local development.

Feel free to comment, I’d be glad to receive any feedback your have.


Source link

Top 15 Django Hosting Services: Pros and Cons

The original article was written by SoftFormance https://www.softformance.com/blog/top-15-django-hostings/

Choosing a Django hosting service is one of many decisions you’ll need to make when working on a project, and it’s a step that cannot be overlooked! With so many options on the market available, it surely is an overwhelming task.

At first, all of these hosting services look quite similar in their features. However, due to huge differences, choosing the wrong one will doom your project from the very beginning. For example, a hosting service with limited scalability, bandwidth, or storage isn’t the right choice for a fast-growing project that is constantly updating and changing.

But don’t worry, we got you covered and made a list of 15 Django hosting services, with their main pros and cons. We also highlighted the most important factors to consider and what to pay attention to when choosing a hosting service. So, let’s dive right in!



What to consider when choosing a hosting service for your project?

Multi-platform software vs PaaS. The multi-platform model gives you an operational system with complete freedom to build your site in any language you like. Meanwhile, the PaaS model provides you with virtual space, where you can install a limited number of languages (Python, Django, or others, provided by the platform).
Price. **Whether you are a huge company or a rising startup, money for hosting services always takes a significant part of the budget. Thus, choosing a service that has a balance between price and quality is important.
**Scalability. **Being able to adapt your platform depending on the changing needs of your business is the key to success. Scalable hosting services allow you to add bandwidth, storage, and other resources at once.
Speed. Only with a 1-second delay, customer satisfaction rate drops by 16%, while a 1-3 seconds delay on a page load leads up to a 32% bounce rate. As such, consider the speed of website load, server response, and file download/upload to a server.
**Control panel.
It allows you to monitor and adjust your website and its features. Usually, control panels have many tools that may vary slightly from one hosting service to another. Pay attention to it and choose the one that matches the best with your needs.
Without further ado, let’s talk about services that will make your project a success.



Python & Django-specific hosting providers

Most of the hosting services are oriented on a lot of programming languages. However, let’s start with a few providers that are only Django-specific.

django CMS

Django CMS is easy-to-use, developer-friendly, Python CMS founded in 2007. NASA, Instagram, and National Geographic are only a few examples of companies that used it.

Pros

  • User-friendliness. Django CMS is oriented not only at developers but also at marketing managers and content editors. Hence, it has a short learning curve and quite an intuitive drag and drop interface.
  • Scalability and customization. It is flexible, easy to extend, and possible to add other integrations in the later stages of the project.
  • Broad Django CMS community available through their Slack Channel and Forum.
    Cons

The basic user interface but it’s easily extendable with lots of plugins available.
Plans & Pricing

Django CMS is a free and open-source platform.

Wagtail CMS

This CMS was originally built for the Royal College of Art, but today is used by lots of developers and companies all over the world.

*Pros *

  • Lightweight and straightforward interface.
  • Flexibility in development. It provides developers with a platform and set of tools, giving them complete freedom in how to use them.
  • Integration with existing Django applications. It is easily integrated with other Django apps in your tech stack.
  • Multi-site support. You can run several sites using the same admin.

Cons

  • In order to extend, you need significant coding knowledge and skills.
  • Not a fully developed CMS. Even basic components require heave coding.
  • Plans & Pricing

Wagtail CMS is a free and open-source platform.



Mezzanine

Mezzanine is a CMS created by Stephen McDonald in 2010. Similar to WordPress, it has most of its functionality by default, which makes it a more integrated and productive platform.

Pros

  • Beginner-friendly. For inexperienced users, Mezzanine is ready to use out of the box. It provides a built-in search engine and API, numerous integrations, a blog, and lots of themes and templates.
  • Front-end editing. Meaning that users can edit blog posts, themes, and widgets as long as they are logged with an Admin account.
  • Integrations with third-party applications, such as Disqus, Gravatar, Google Analytics, Twitter, and others.
    Cons

  • No feature of scheduled publishing. With Mezzanine, you cannot schedule publications to be posted at a specific time.
    Plans & Pricing

Mezzanine is a free and open-source platform.



PythonAnywhere

If you search for Django hosting, this is one of the first platforms that you’ll come across. Focused exclusively on Python and running on AWS servers, this PaaS hosting service allows you to install your Django project with one click.

Pros

  • One-click installation for Django projects.
  • Quick and easy to set up even for inexperienced users.
  • Accessible and simple options for scaling.
  • Free SSL support no matter what plan you are choosing.
    Cons

  • Support service is accessible only via email.

  • No WebSocket support, meaning it can’t host real-time applications.
    Plans & Pricing

PythonAnywhere has a free plan with limited options, which is perfect to test the service and get you started as well as four paid plans. The prices vary from 5 to 100$, and there is a custom option where you can choose all of the features you need (5-500$ per month).

djangoeurope

Which hosting service can be better than the one founded by one of the Django developers himself? It was set up in 2009 by a small team of experts and grew into one of the most developer-friendly Django-specific hosting services.

djangoeurope doesn’t have its own data centers and uses ones of other hosting services, depending on location (Hetzner’s in Germany and Finland, hosttech’s in Switzerland, and so on).

*Pros *

  • High level of customization. It has a fully customizable web server, and you gain complete control over the configuration of your app.
  • One-click Django installation. You will have your website up and running within minutes, just by entering your project’s name, website name, and address login.
  • An unlimited number of sites. djangoeurope allows hosting an unlimited number of sites and domains.
  • Backups. The service provides daily and weekly backups that are available from 7 days to 3 months.
    Cons

  • Scalability. The service offers quite limited bandwidth (each server has a bandwidth of 1 Gbps that cannot be modified).
    Plans & Pricing

The plans vary from 5 to 60 euros per month, and there is a policy of a 30-days money-back guarantee. You can also pay in advance for the whole year and get a 10% discount.



Wide-ranging hosting providers

Let’s move on to the hosting services of broader use. But don’t worry, all of them are perfectly fit to host Django projects.

Amazon Web Services

Today, more than 33% of all websites around the globe are built upon Amazon Web Services. This makes AWS one of the most widespread hosting services used by countless businesses and organizations. Let’s find out the secret to the success of this cloud hosting service.

Pros

  • Security and compliance. AWS ensures complete redundancy, backups, and server cloning for their clients.
  • Scalability. You purchase the necessary amount of storage, with an opportunity to increase or reduce it when needed.
  • Excellent support. Several support plans are available, according to your needs.
  • High speed and agility. AWS allows setting up an application within minutes, saving your time and money, and boosting efficiency and agility.
  • Pay as you go method. You are paying only for the services and tools you are using.
    *Cons
    *
  • Not beginner-friendly. The abundance of options and choices is overwhelming and difficult to understand for a newbie.
  • Country specific. While AWS provides an extensive range of options, all of them are available only in the USA, while if you are located in another country, you’ll need to check for the availability of each option specifically.
  • Complicated pricing. Too many options and different prices for each one make it difficult to determine the exact price beforehand.
    Plans & Pricing

At first, AWS pricing may seem a little too complicated when you look at it. The service offers free trials, but with a limited number of options. If you need a lot of storage or some add-ons, here comes added costs. To determine the exact cost you will need to pay, use AWS Pricing Calculator.

Azure (Microsoft)

Azure is another cloud giant in the area of hosting services, but we prefer other services to it. Our tech stack is Python/Django, which is open-source and completely contradictory to the core values of Microsoft, which is a proprietary company. As such, we go for such open-source OCs as Linux (in particular, Ubuntu).

Pros

  • Scalability. The service allows you to purchase, use, and remove data packages exactly when needed.
  • Security. Azure’s security system is based on the DADSC approach, which is Detect, Assess, Diagnose, Stabilise, and Close and received multiple compliance certifications
  • Availability. The service has more than 40 data centers all over the world, making it accessible for international businesses.
    Cons

  • Not beginner-friendly. Same as with AWS, it will take lots of time and effort to understand all of its features for a newbie.

  • Inefficient customer support. In case of an emergency or problem that requires instant solution, it’s hard to contact the customer support asap.

  • Data loss. Since the service is a single solution, it means that all of your data will be hosted in one space. If you won’t be able to access it for some reason or Azure itself will lose it, you will risk losing it for good.
    Plans & Pricing

Azure’s pricing system is rather complicated and includes many different factors and pitfalls, lacking precise prices and costs. On the other hand, it uses the pay-as-you-go method, so you don’t overpay for features and add-ons you don’t use.

DigitalOcean

Back in 2012, the founders of DigitalOcean, Ben and Moisey Uretsky stumbled upon the Craiglist job listing of Mitch Wainer, co-founder of the company to be. Several months later, they launched a beta version of the site.

Today, DigitalOcean is a popular cloud provider among developers across North America, Europe, and East Asia.

We prefer DigitalOcean over other hosting services and use it for the majority of our clients who want to automate their business or start a new software product.

Pros

  • Beginner-friendly. DigitalOcean has a simple API interface that allows both newbies and seasoned developers to use it to their best advantage.
  • Scalability. You can both add more space or downsize easily, depending on your needs.
  • Affordability. Compared with similar hosting services, DigitalOcean offers one of the best prices on the market.
    High speed. A 40 Gbps network allows you to access one of the best speed levels on the market.
  • Broad outreach. DigitalOcean has 13 data centers on three continents.
    *Cons *

  • Limited range of products in comparison with other hosting services.
    Plans & Pricing

Prices start from 5$ per month. Depending on your needs, there are different options available, from 5 to 960$. You can also get a two-month free trial and try out free credits up to 100$ every month.



Google Cloud Platform

Over the last three years, Google Cloud’s revenue grew from 4 to 13 billion dollars, making up more than 7% of the company’s total revenues.

Pros

  • Scalability. There are wide options regarding data storage, updates, and functionality.
  • Global outreach. Wherever you are, GCP gets you covered and allows deploying from all over the world.
    Cons

  • Lack of innovation. In comparison with other hosting services, it is not as innovative and wide in its features and productivity as the competitors.

  • Focus on smaller projects. Large projects are out of GCP’s focus in comparison with its competitors, such as Microsoft.
    Plans & Pricing

The platform offers 300$ in free credits and 20+ free products, has pay as you go method and 24/7 free billing support.



Hetzner

Hetzner is a Germany-based company that has data centers in Germany and Finland. It has been on the market since 1997 and provided services for Userlike, Leoni, Whereby, Talkwalker, and many more companies.

We also use Hetzner for demo servers and other inner goals due to its affordability.

Hetzner is also an environmentally sound organization. It uses exclusively renewable sources to power the servers in the data centers (wind and hydropower) and concentrates on choosing energy-efficient hardware.

Pros

  • Affordable prices. Its prices are one of the lowest on the market and affordable for both large and small-scale businesses.
    24×7 support. The support is free and available at any time. Documentation and email support are free for everyone while phone support is only free for users with Level 4 pricing plans.
  • Partnership with Dell, Intel, and other vendors, which is a guarantee of reliable software and hardware.
  • Free domain and SSL.
    Cons

  • No data centers in the United States.

  • Inconvenient and difficult to use control panel.

  • Most of the documentation is in German.

  • No uptime guarantee.
    Plans & Pricing

Hetzner offers various levels of subscriptions, with prices starting at 1.90 euros per month for level one. There are also plans for 4.90 and 9.90 euros per month, and a premium level for 19.90 euros monthly. You can learn more about the details of each level here.



Heroku

Founded in 2007, this PaaS platform supported only Ruby programming language at first. Today, the number of supported languages expanded, including Python, which makes Heroku a polyglot platform. It hosts more than 105 thousand social and mobile cloud applications.

Pros

-Beginner-friendly. Its initial deployment and environment configuration are easy and clear, even for a newbie.

  • Seamless integration with other SaaS products and services.
  • Exceptional support, ready to assist with all kinds of issues.
  • Heroku uses Amazon’s secure data centers to host and manage its physical infrastructure.
    Cons

  • Quite pricey, especially in comparison with other hosting services.

  • Some plans include sleeping mode, which automatically puts your application into sleeping mode after some period of inactivity. Unless you have enough coding skills to work around built-in functionality, it may be inconvenient.
    Plans & Pricing

Heroku offers a free plan with a limited number of choices as well as paid ones. For the Standard plan, prices vary between 25 and 50$, and for the Performance plan between 250 and 500$, depending on the features you need.



A2 Hosting

A2 Hosting was founded back in 2001 and provides services for large and small-scale companies for two decades now. Having data centers in Amsterdam, Singapore, and Michigan, the platform has global coverage and can offer services to companies all over the world.

Pros

  • Great hosting performance speed.
  • Data centers around the globe.
  • Easy to scale.
  • Unlimited disk space and bandwidth.
  • 99.9% uptime guarantee.
    Cons

  • The cheaper plans are quite limited in their features in comparison with more expensive ones.

  • Plans & Pricing

The prices vary between 8 and 123$ per month, with all plans including unlimited storage and data transfer, as well as free SSD.



Bluehost

Founded by one of the oldest and largest global hosting corporations, Bluehost is another platform to consider when looking for a hosting service. FalconStor Software, HB Communications, Quest are just a few companies among many others who used Bluehost.

Pros

User-friendly hosting dashboard and control panel.
Simple and straightforward website transfer and setup.
Money-back guarantee.
24×7 support via chat, email, and phone.
Cons

  • No automated backup. You have to set up your own backup via the control panel or additionally pay for the Backup Pro feature.
  • Slower speed in comparison with other hosting services.
    No unlimited storage.
    Plans & Pricing

The platform offers three plans for 19.99, 29.99, and 59.99$ per month, which vary by the amount of SSD storage, bandwidth, cores, and IP addresses.



TMDHosting

TMDHosting has data centers in 7 locations around the world and uses cutting-edge cloud technology to provide its customers with the fastest load times.

Pros

  • Convenient and easy-to-use interface, including control panel, support tickets, billing, and other features.
  • Exceptional server performance: high speed and quick server response time.
  • Regular updates and daily backup.
  • 24×7 support time, response time is less than 15 minutes.
    *Cons
    *
  • There are not a lot of features and characteristics for more complex projects.
    Plans & Pricing

The prices start from 2.95$ per month for the Starter Plan, 5.95$ for the Business Plan, and 12.95$ for the Professional Plan.



HostUpon

Based in Toronto, HostUpon accounts for more than 10 thousand customers and 50 thousand websites and offers a tailored solution for clients all over the world.

*Pros
*

  • Unlimited disk space and bandwidth.
  • 5 data centers across the world.
  • 99.9% uptime guarantee.
  • Full control with cPanel and WHM Control Panels.
  • Free migration from your current provider.
  • 24×7 support available via phone, live chat, and support ticket.
    Cons

  • Too many features and details in the basic plans.

  • Lower-price plans don’t offer SSL certificates and backups.
    Plans & Pricing

The prices of VPS hosting start with 49.95$ per month, offering 20GB disk space, 100GB bandwidth, and 512MB memory. All of the other plans include unlimited bandwidth and more disk space and memory. The most popular plan costs 69.95$ per month and includes 50GB disk space, unlimited bandwidth, and 1 GB memory.

Comparison Table
Up to this point, you are probably overwhelmed with all the facts, numbers, and statistics. So, we simplified it a bit for you. Take a look at the table with all the core features and characteristics of each of the listed hosting services:

Type of cloud computing service Price Scalability Speed Control Panel
Django CMS Free Easily scalable

Wagtail CMS Free

Mezzanine Free

PythonAnywhere PaaS 5-500$ Accessible and simple scaling options Slower in several times in comparison with other providers No control panel
djangoeurope Multi-platform 5-60€ Limited bandwidth Django-based control panel
Amazon Web Services Multi-platform Pricing Calculator Accessible and simple scaling High speed and agility

Azure (Microsoft) PaaS Pricing Calculator

DigitalOcean Multi-platform 5-960$ Highly scalable 40 Gbps network; one of the best speeds on the market cPanel, WHM Control Panels
Google Cloud Platform Multi-platform 300$ free credits, 20+ free products Highly scalable cPanel/WHM Control Panels
Hetzner Multi-platform 1.90-19.90$ Inconvenient, difficult to use
Heroku PaaS 25-500$

A2 Hosting 8-123$ Easy to scale 285ms

Bluehost Multi-platform 19.99-59.99$ Not highly scalable 688ms User-friendly control panel
TMD Hosting Multi-platform 2.95-12.95$ Up to 10TB bandwidth 648ms cPanel, WHM Control Panels
HostUpon Multi-platform 49.95-149.95$ Unlimited disk space and bandwidth 846ms cPanel, WHM Control Panels
Sum Up
The right hosting provider is a significant part of building a successful project. There are lots of factors to consider, from your experience to the budget of your project. You should always pay attention to scalability, speed, prices, control panel, among other characteristics when checking out the hosting service.

We prefer to use DigitalOcean for the majority of our clients due to its extended features, user-friendly control panel, excellent functionality, and affordable prices.

Also, we use Amazon Web Services for fast-growing and developing projects with bigger budgets.

If you are looking to launch a Django-based software but don’t know where to start, waste no time and contact us! We’d be happy to help you to figure out all the details and calculate the costs for the development, support, and hosting of your project.

Still unsure? Check out some of our latest work.


Source link