When I started learning Django, finding a tutorial that had everything I needed was pretty hard So hopefully this tutorial will help you get started!
What you will learn
- Create a virtualenv
test
- Create a sample project called
HelloDjango
- Create a demo Django app called
accounts
- Finally configure the
settings.py
Let’s dive right in
Prerequisites
Make sure you have the following installed on your computer to follow-through.
- You got Linux Os installed (ubuntu, Debian)
- Python 3+
- Django 2.0
- Virtualenv
Django Introduction
According to djangoProject,Django is a python web framework for developers looking for a faster way to build web applications and with less code.Essentially, django is for perfectionists with deadlines
Why Consider Django?
Please refer to the django Documentation for more info.I will give a personal opinion why it is really cool.
- Inbuilt Security features such as Cross site request forgery (CSRF) protection.
- Great Documentation.
- Faster because It has many inbuilt features such as Admin site, Authentication
Linux Installation
I recommend Ubuntu or Debian .For this specific tutorial, I had mint installed because its light and it’s just a personal preference.
Python Installation
Django is a python framework so first ensure you have python installed.The default installed in my Os is 2.7.Check the version of python installed by typing the following command into your shell:
$ python --version
$ python -V (Mind the capital)
$ python2 -V
The above outputs
Python 2.7.12
To check the version of Python3
$ python3 -V
The above outputs
Python 3.5.2
In this tutorial ,we are using python 3.5 and higher.Type the command below to check which version 3 is installed
$ python3 --version
You should see something close to this:
Python 3.5.2 (default, Nov 23 2017, 16:37:01)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
You can type CTRL+D to exit the interactive shell for now.
Installing Python
If you do not have python installed,use this command:
$ sudo apt-get install python3.5
to install the latest version 3.6 check this tutorial
Setting up Virtual Environment
We could just create a Django application on our computer, but to control the packages unique for our application we will use Virtual Enviroment.Virtual Environment is useful when you want to create isolated environments, each running their own versions of packages.We can even create virtual environments with various python versions ! sounds cool.For this tutorial I am going to use virtualenv.
Virtualenv
We can install virtualenv using python’s package manager pip.use the command:
$ sudo pip install virtualenv
Pip is a useful python package tool that installs, updates, and remove Python packages/libraries used by Django and your other Python apps.Pip come installed with python 2.7+downloaded from python website.You just have to upgrade it using the command:
$ pip install -U pip
You should get something like this if virtualenv
is already installed as in my case:
cindy@cindy-Veriton-M290 ~/Desktop $ pip install virtualenv
Requirement already satisfied: virtualenv in /home/cindy/.local/lib/python2.7/site-packages
Create and name virtualenv
Once you have successfully installed virtualenv,next we create the virtualenv test in shell.I like creating my project in documents Folder.So right-click and choose open a terminal here option.Once you open the terminal,type:
$ virtualenv -p python3 test
test
is just a name,you could give it any name.The -p points to the python version you want to use ,in the above case python 3
Activate Virtualenv
Now that we have created our virtualenv test,we need to use it to install django and other packages we will need.In order to use our virtualenv,we mustactivate it. change directory to your virtual environment using:
$ cd test
Then once you are inside the virtualenv directory,activate it as shown below:
$ source bin/activate
By now you should see your virtualenv in brackets
(test)
Below is a sample from my console:
(test) cindy@cindy-Veriton-M290 ~/test $
How to check packages installed in the virtualenv you just created
run:
$ pip freeze
Django Installation
our virtualenv
is running,let's install django .The version of django at the time of writing this article is 2.0.2.
$ pip install django
Run:
$ pip freeze
your console should list the installed packages
(test) cindy@cindy-Veriton-M290 ~/test $ pip freeze
Django==2.0.2
pytz==2018.3
To specify django version,use:
$ pip install django==.For example to install django 1.11:
$ pip install django==1.11
Creating Django Project
Django is successfully installed so lets create our project Structure! Type this in your console:
django-admin startproject HelloDjango
This command creates a template for our project.
HelloDjango/
manage.py
HelloDjango/
__init__.py
settings.py
urls.py
wsgi.py
The outer HelloDjango
is the container holding our project.Its okay to change the name to something else say ‘src'.
The inner HelloDjango
contains your site's configurations.I Highly recommend you leave it as it is, at least for now.
Change to project directory
cd HelloDjango
The project directory is the outer HelloDjango containing manage.py file.If you changed its name to src,then change directory to src.
cd src
Make Migrations
We need to create a database and Django comes with sqlite .You are free to use any other databases of your choice.But for this tutorial we will use the sqlite. Change directory to the project root and make migrations by typing the command:
$ python manage.py makemigrations
$ python manage.py migrate
Test development server
To test if your project is working well,go to your project root directory then type this : $ python manage.py runserver
You should see something like this:
Performing system checks...
System check identified no issues (0 silenced).
February 28, 2018 - 18:58:33
Django version 2.0.2, using settings 'achieng_website.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
When you go to http://127.0.0.1:8000/,If django was successfully installed you should get a success message"congratulations"
Configuring Settings.py
We will make some changes on our settings.py.This file help us manage our static files such as css,js, and images.First we going to change Templates DIR
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
...
],
},
},
]
Add staticfiles_Dirs
as well:
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
Change time zone
Finally,lets go back to our settings.py and change our timezone.I come from Nairobi so my time zone is Africa/Nairobi.Check yours on: wikipedia
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Africa/Nairobi'
Creating an App
python manage.py startapp accounts
Your project structure should be like this:
accounts/
__init__.py
admin.py
apps.py
migrations/
__init__.py
models.py
tests.py
views.py
The app creates modules such as models.py
,admin.py
,views.py
,apps.py
.
Django implements MVC Pattern
For the app you have just created to be used,add it to INSTALLED_APPS
in the settings.py
.
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'accounts',
)
This Post was originally posted onachiengBlog
Top comments (10)
Hello. Anybody experienced or encountered the error below? I need help. Thanks a lot!
$ python manage.py startapp TestApp
File "manage.py", line 14
) from exc
^
SyntaxError: invalid syntax
Yes this error usually occurs if you haven't activated the virtual environment.
Hello Benjie,
It has been a while, did you get help?
Why using Django? Because the ORM is awesome and migrations are fucking dope. At this stage that's what makes me addicted to Django (versus any other framework that handles everything else just as well).
I want to add the useful
pip freeze > requirements.txt
in order to keep the list of the package and thenpip install -r requirements.txt
in order to install them (on another environment for example)I've used Pipenv also for doing django tutorials and love it. If you familiar with Ruby, It's like a bundle.
You can add, remove, libraries very easily.
docs.pipenv.org/
If you get the next error message while trying to create the virtualenv in Ubuntu:
Running virtualenv with interpreter /usr/bin/python3
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/virtualenv.py", line 24, in
import distutils.spawn
ModuleNotFoundError: No module named 'distutils.spawn'
Just run: sudo apt-get install python3-distutils
This happens because Ubuntu's built-in Python is broken.
I am glad you think so ☺.No,I haven't used pipenv yet,and I am definitely trying it out.
Hi Cindy,
what after adding app? I followed your article and my django admin page is up but i have don't know what to do after creating app. How to access it? it is still showing me admin page.
Hi Hasan,
This tutorial was simply to help with setting up the Django structure.The app is where you should perform the task you wanted to.For example as the name suggests accounts app would be handling registration,password resets etc.
I have a tutorial called laughing blog and it can give you better perspective achiengcindy.com/blog/2018/06/23/l...