Hello Word in Django : How to start with Django

In this article I will teach you how to make and run a python-django app in less than 5 minutes.

Prerequisite: Python (preferably python 3) is already installed.


Step to create and run the django app:

Install virtual environment. You may proceed without virtual environment too, but in long run it is going to be very helpful. $ pip install virtualenv

Create a virtual environment.
$ virtualenv -p /usr/bin/python3 helloworld_VE

Activate the virtual environment.
$ source helloworld_VE/bin/activate

Install the latest django framework in virtual environment.
$ pip install django

Create your project. 
$ django-admin startproject myproject

Go inside newly created project directory. 
$ cd myproject

You will see a file manage.py  and a directory with same name as of your project.

create an app here. Every project consist of one or more apps. These are plug-able modules which can be reused in other project if written properly. 
$ python manage.py startapp helloworld

Go inside helloworld  directory. create a new file urls.py .


Add below lines to this file and save it.

from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
]



Open views file and save below code in it. 

from django.shortcuts import render
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello World. First Django Project. ThePythonDjango.Com")


Include the app i.e. helloworld urls in main project urls file. Open myproject/urls.py file and make add below line in urlpatterns. url(r'^helloworld/',include('helloworld.urls')),


Also import include module.
from django.conf.urls import include


Now finally add helloworld  in installed apps in myproject/settings.py file .


Now run command. 
$ python manage.py runserver .


This will run the python http server on localhost and 8000 port. If you want to run it on different port, use port number in command. $ python manage.py runserver 8888 . To run it on different IP address, pass the IP address as well. Use this command to make your project available for everyone on the network.$ python manage.py runserver 0.0.0.0:8000

So this was basic tutorial to set up django app in less than 5 minute. You can refer below github code and  video for same.   

Code on Github:
Github URL : https://github.com/anuragrana/hellow-world-django.git   

Video:



Hosting django app on server:

Read how you can host your django app on pythonanywhere server for free. A complete step by step guide with all screenshots and video.

Reference:

How to install virtual environment? Django official tutorials.


Displaying custom 404 error (page not found) page in Django 2.0

It happens very frequently that a visitor on your website typed a wrong URL or the page user is looking for no longer exists.

What do you do to handle such cases?

You have three options.

  • Redirect the visitor to home page, silently.
  • Show a boring 404 error page and then ask them to click on a link to go to home page.
  • Create your own funny/awesome/informative custom 404 error page.
In this article we will discuss the third option i.e. How to show your own error page in Django 2.0 project when a URL is not found.

Code is available on Github.


How to create your own custom 404 error page in Django:

A custom 404 error page can serve multiple other purposes apart from just telling the user that the link you visited is not correct.

You can ask user to subscribe or sign-up. Or you may show some funny stuff. 


django 404 not found

  

Steps to show custom 404 error page in Django:


Project Setup:
Create a virtual environment using python3 and activate it.

- Once virtual environment is activated, install the Django 2.0 in it using pip.

pip install Django==2.0.3


- Now go to the directory where you want to create project. - Run the below command to create a new project.

django-admin startproject error_404


- This will create a new folder error_404  in your current working directory. Inside project directory there will be manage.py  file.

- Now we will use manage.py  file to run django commands.

- Create a new app inside project. Use the below command to create new app.

python manage.py startapp myapp


- This will add a new app in your project. Tree structure of your project at this point will look like as below:

(django2) rana@Nitro:error_404$ tree
.
??? error_404
?   ??? __init__.py
?   ??? settings.py
?   ??? urls.py
?   ??? wsgi.py
??? manage.py
??? myapp
    ??? admin.py
    ??? apps.py
    ??? __init__.py
    ??? migrations
    ?   ??? __init__.py
    ??? models.py
    ??? tests.py
    ??? views.py

4 directories, 14 files


- Don't forget to add your newly created app to the list of installed apps in project settings.py  file.


error_404/settings.py:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myapp',
]
 

- Right now if you start your python server using command python manage.py runserver , you will see below output in your terminal.

(django2) rana@Nitro:error_404$ python manage.py runserver
Performing system checks...

System check identified no issues (0 silenced).

You have 14 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.

March 19, 2018 - 17:21:19
Django version 2.0.3, using settings 'error_404.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.


- And you can see your project is working just fine by going to localhost:8000 in your browser. If you seen below screen means all is good. 


django 404 not found


Showing 404 error page:

- If you try to go to some URL which doesn't exists yet like localhost:8000/abc, then it will show the default 404 page not found error page of Django. 


custom 404 error page in django


- When you will deploy the code on server, you will set DEBUG = False  and ALLOWED_HOST = ["your_domain"]  hence your incorrect URL will return response as shown below.


django 404 when debug is false


On your localhost you need to edit your project/settings.py file to show this error.


error_404/settings.py:

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False

ALLOWED_HOSTS = ["*"]


Setting "*" in allowed hosts will let you run your project with any host when debug is false. Don't do this in production.

Now go inside your app and create urls.py file.


myapp/urls.py:

from django.urls import path

from . import views

urlpatterns = [
    path('', views.index, name='index'),
]
 


Custom 404 error page:

Now create a new view inside your views.py file. Mind the second parameter exception  in error view.


myapp/views.py:

from django.shortcuts import render
from django.http import HttpResponse


def error_404_view(request, exception):
    data = {"name": "ThePythonDjango.com"}
    return render(request,'myapp/error_404.html', data)


def index(request):
    return HttpResponse("Hello, world. You're at the Home page of Django sample project error 404.")


Create an HTML file which will show appropriate message or form or funny stuff in myapp/templates/myapp directory.


error_404.html:

<html>
  <head>
  </head>
  <body>
    <h1> This is a custom 404 error page which will 
         be shown instead of default 404 error page of Django everytime
         incorrect urls is entered in browser.
    </h1>
  </body>
</html>


Now go to urls.py  file of your project and update it. file error_404/urls.py will look like as below:

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('myapp.urls')),
]
 
handler404 = 'myapp.views.error_404_view'


Now if you go to your browser and open any non-existent URL, you will be shown custom 404 error page.


displaying custom 404 error page not found page in django

We need to set DEBUG = False and ALLOWED_HOST = ["*"] or whatever your host is in order to see custom 404 error page.


Code:

Code is available on Github. Please go through README file to setup the project on your machine.  

References:

  1. https://docs.djangoproject.com/en/2.0/ref/views/#error-views


Featured Image Source:  https://www.pinterest.com/pin/101612535313085400/   


Comment in case of any query.


Elastic Search with Kibana and Django

In this article we will see how to implement fast text search using elastic search instead of using MySQL or PostgreSQL.


System configurations:

- Ubuntu 16.04
- Python 3.5, Django 1.10
- Elastic Search v6.0.0
- Kibana v6.0.0


Elastic Search:

As per Wikipedia:

Elasticsearch is a search engine based on Lucene. It provides a distributed, multitenant-capable full-text search engine with an HTTP web interface and schema-free JSON documents.


ElasticSearch indexes documents for your data instead of using data tables like a regular relational database does.

There are two client libraries to interact with ElasticSearch with Python.
1. elasticsearch-py
2. elasticsearch-dsl


Installing Elastic Search:

Since ElasticSearch runs on Java you must ensure you have an updated JVM version. Check what version you have with java -version in the terminal.

1 - Make a directory. mkdir elasticsearch

2 - Download the tar file. wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-6.0.0.tar.gz

3 - Untar the compressed file. tar -xzf elasticsearch-6.0.0.tar.gz

4 - Start the elastic search. ./elasticsearch-6.0.0/bin/elasticsearch. Elastic search will print lots of output on terminal.

elastic search with kibana and django


To confirm if its working, go to your browser and hit http://localhost:9200/ .  You will get the response something like below.

elastic search with kibana and django

Elastic search is up and running. Lets setup the Kibana.


Kibana:

Kibana is an open source analytics and visualization platform designed to work with Elasticsearch. Its simple, browser-based interface enables you to quickly create and share dynamic dashboards that display changes to Elasticsearch queries in real time.


Installing Kibana:

Official documentation of Kibana explains in detail about the steps to install it. We are going to present you the short version of same.

We will be installing using the .deb file.

1 - Download the kibana v6.0.0 deb file. wget https://artifacts.elastic.co/downloads/kibana/kibana-6.0.0-amd64.deb

2 - Compare the SHA produced by sha1sum or shasum with the published SHA. sha1sum kibana-6.0.0-amd64.deb

3 - Install kibana. sudo dpkg -i kibana-6.0.0-amd64.deb

Use below commands to start or stop kibana.

sudo systemctl start kibana.service 
sudo systemctl stop kibana.service


Use below commands to start kibana automatically when system boots up

sudo /bin/systemctl daemon-reload
sudo /bin/systemctl enable kibana.service


Now open the Kibana in browser. Go to http://localhost:5601 . If your elastic search was running and everything is fine then you will see all green on the kibana status page otherwise you may see some red flags.

elastic search with kibana and django


So now kibana and elastic search are up, connected and running. In next part of this article, we will setup a Django project and will link it to elastic search.


References:

https://www.automationlaboratories.com/linux/installation-elk-stack-linux-server/



SUBSCRIBE
Please subscribe to get the latest articles in your mailbox.



Recent Posts:






© pythoncircle.com 2018-2019
Contact Us: code108labs [at] gmail.com
Address: 3747 Smithfield Avenue, Houston, Texas