Let's start our Django application from the beginning. To start our first application we have to follow the below steps. Before going to start our project learn about django project layout.
- Create a directory with your project name & change your directory to the project. Lets consider our project as "Library Management"
- Now, create virtual environment for our project.
- Install Django package in environment.
- Start our project Library Management
- Run the below command to test our project setup.
- Now create an application "library" to show "hello world" as response in browser
- "db.sqlite3" is file database developed in python. It is best suitable for beginners. we can also use MySQL and Postgres databases. "library" is our application with its files in it.
- Now, open "library_management/urls.py" and replace the contents of file with below code.
- And open "library/views.py" file and replace file contents with below code
- Open your web-browser and access url "http://127.0.0.1:8000/hello-world/". You can find "Hello World" as response.
mkdir Library && cd Library
virtualenv env source env/bin/activatevirtual environment is now ready to use.
pip install django
django-admin startproject library_managementAfter executing the above commands a new folder "library_management" will be created. Inside that folder you can see another folder "library_management" and a file "manage.py". Inside "library_management/library_management" folder you can find below files
__init__.py settings.py urls.py wsgi.py
python manage.py runserverOpen your browser and hit the url http://127.0.0.1:8000/. You can see the below output.
If you do not see the above output, you might have missed something. so, delete everything that you did and start from the beginning again to save our time. As we are beginners we don't know much to resolve errors.
python manage.py startapp libraryAfter executing the above command in the directory you can observe that a folder with name "library" have created and a file "db.sqlite3" also. If you look inside of folder "library" you can find the following files.
admin.py apps.py __init__.py migrations models.py tests.py views.py
from django.conf.urls import url from django.contrib import admin from library import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^hello-world/$', views.hello_world), ]
from django.http import HttpResponse def hello_world(request): html_source_code = """ <html> <title> Hello World</title> <body> <h1> Hello World</h1> </body> </html> """ return HttpResponse(html_source_code)