tag: django | Python Tutorial

Tag: django

Django admin

Django comes with an automatic admin interface.

We just created a (database) model in the previous article. Now we can create a backend management tool for it.

This is one of the most powerful features of Django.

Related course:
Python and Django Full Stack Web Developer Bootcamp
icon

Admin interface

You can open the admin interface with a web browser, but to open the admin interface, first we need to change a file. Open the file movies/admin.py
This is the file contents:

from django.contrib import admin

# Register your models here.

Lets add some code:

from django.contrib import admin
from .models import Movie

admin.site.register(Movie)

Start the Django server:

python manage.py runserver

Open the url: http://127.0.0.1:8000/admin/

Admin login

A login screen will popup. Let’s enter the matrix!

django admin

Django admin add user

Create a superuser.

python manage.py createsuperuser

Type a username and password. You should see this message:

Superuser created successfully.

Now open the webpage again and login.

The admin screen

If you see the screen below, good job!

django site admin

The model ‘Movie’ is there!

Django admin add

If you click on the model, a new screen shows up:

django add to model

We can add new movies here. If you click on the button, all the fields are there to add a new movie, exactly as we specified it in the model.

django insert into database

How cool is that?
All the CRUD operations work.

Note: CRUD is short for create, read, update and delete. Common database operations

We can now interact with the complete database system from this graphical interface.

Django hello world

Create hello world in django?

In this article we’ll create the hello world app.

If you do not have Django installed, see the previous tutorials.

Python and Django Full Stack Web Developer Bootcamp
icon

Make a new project

Execute these commands:

django-admin startproject first_django_project
cd first_django_project/
python manage.py startapp hello

Wait.. what did we just do?

  • We created a project named first_django_project
  • We created an app named hello
    Django projects can have multiple apps. Every app is like a website component, it has unique functionality.

Hello world code

We create the hello world code.
If you open the folder /first_django_project/hello you’ll see this:

django app

A lot of code! Which file do we need to change?

There’s one file named views.py

If you open the file you’ll see this:

from django.shortcuts import render

# Create your views here.

We’re gonna create our view in here.

Note: A view returns what the visitor sees: a webpage.

We’ll use HTML and a class to create the view.

If you are not familiar with these, I recommend this course:

Add these lines of code:
abstract-base-classes.md

from django.shortcuts import render

# Create your views here.

import textwrap

from django.http import HttpResponse
from django.views.generic.base import View

class HomePageView(View):

def dispatch(request, *args, **kwargs):
response_text = textwrap.dedent('''\
<html>
<head>
<title>Hello World!</title>
</head>
<body>
<h1>Hello world</h1>
<p>Hello, world! Hola Mundo!</p>
</body>
</html>
''')
return HttpResponse(response_text)

We create a class HomePageView with the method dispatch.
This methods return the webpage code (in HTML).

URL router

Python needs to return the view, if we visit the webpage.

If we visit a webpage, the web browser sends a HTTP request.
To link views with the HTTP request, we create a new route.

In the app directory, create the file hello/urls.py with this content:

  
from django.conf.urls import url
from hello.views import HomePageView

urlpatterns = [
url(r'^$', HomePageView.as_view(), name='home'),
]

In the project directory, change /first_django_project/urls.py:

  
from django.conf.urls import include, url

urlpatterns = [
url(r'', include('hello.urls')),
]

Change app settings

Then we edit first_django_project/settings.py. Apps can be added or removed in this file.
You’ll see a list definition:

  
INSTALLED_APPS = [ .. ]


Add our hello app to this list.

We’ll remove the line SessionAuthenticationMiddleware.
Finally we’ll disable the database. This is defined somewhere on line 72.

  
DATABASES = {
...
}


Remove those lines.

All set!

Run the command:


python manage.py runserver

Then open the URL to see the result:

django hello world

If you see the above result, you completed this lesson!

Django models

What is a django model?

A model is a class that matches a database table (or collection).
Models are defined in the apps models.py file, /app/models.py.

Say what? Let’s make an app with a database model!

Python and Django Full Stack Web Developer Bootcamp
icon

Models example

We start a new project, movie database.

django-admin startproject movie_site

Inside the directory movie_site we now see:

manage.py movie_site

Configure database

Open movie_site/settings.py, there are the lines:

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}

A database is already set up!

We’ll use the default database system: sqlite3.


Note: Django supports many databases including:

- SQLite (django.db.backends.sqlite3)
- MySQL (django.db.backends.mysql)
- MongoDB (django_mongodb_engine)
- Oracle (django.db.backends.oracle)* PostGreSQL (django.db.backends.postgresql_psycopg2)
- NoSQL DB

Create your database with this command:

python manage.py migrate

Now you’ll see lots of lines:


Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
Applying contenttypes.0001_initial… OK
Applying auth.0001_initial… OK
Applying admin.0001_initial… OK
Applying admin.0002_logentry_remove_auto_add… OK
Applying contenttypes.0002_remove_content_type_name… OK
Applying auth.0002_alter_permission_name_max_length… OK
Applying auth.0003_alter_user_email_max_length… OK
Applying auth.0004_alter_user_username_opts… OK
Applying auth.0005_alter_user_last_login_null… OK
Applying auth.0006_require_contenttypes_0002… OK
Applying auth.0007_alter_validators_add_error_messages… OK
Applying auth.0008_alter_user_username_max_length… OK
Applying sessions.0001_initial… OK

Good job!

Create an app

Django sites can have many apps. Each app is like a plugin.

Let’s make a movie details app.

python manage.py startapp movies

You have just created an app!
There’s a new folder: movies.

Note: Django doesn’t know it should use this app yet.
Apps are not added by default.. Let’s teach django.

Open movie_site/settings.py.
Scroll down to the line INSTALLED_APPS and add the line ‘movies’.

Create a movie model

We can create our model now. In the movies/models.py you can define all models.
Create a class for your movies model. The class will map to the database table.

If you don’t know classes and object orientated programming, take this couse:

We class will contain attributes of our movie object.

from django.db import models

# Create your models here.
from django.db import models
from django.utils import timezone

class Movie(models.Model):
author = models.ForeignKey('auth.User')
title = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(
default=timezone.now)

def publish(self):
self.published_date = timezone.now()
self.save()

def __str__(self):
return self.title

Run the command;

python manage.py makemigrations movies

This will output:

Migrations for ‘movies’:
movies/migrations/0001_initial.py
- Create model Movie

Also type this command:
python manage.py migrate movies

The magic continues:
Operations to perform:
Apply all migrations: movies
Running migrations:
Applying movies.0001_initial… OK

In English, that means it’s just created our database table!

Browse database

Open the database file (db.sqlite3) with sqlitebrowser.

django database model

Yeehaw! Our movie model is now our database.

Starting a django project

Start a new Django project?.

After installation of Django, we can create a new project.

Django can be used to create websites and web apps. You need to type in some terminal
commands to start a new Django project.

Python and Django Full Stack Web Developer Bootcamp
icon

Create Django project

Open the command prompt, then enter your projects directory.

mkdir projects
cd projects
mkdir django_example
cd django_example

Then we use django-admin tool.

django-admin startproject mywebsite
cd mywebsite
Note: If you list the files in the new directory, you’ll see manage.py and the skeleton project.

Django start server

Start the developent web server.

python manage.py runserver

It’ll output lots of things:

Performing system checks…

System check identified no issues (0 silenced).

You have 13 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.

July 19, 2017 - 20:54:09
Django version 1.11.3, using settings ‘mywebsite.settings’
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
Note: On the last line, you’ll see the address: http://127.0.0.1:8000/
Open that address in your webbrowser.

You’ll see the basic Django template:

django new project

 

If you see this screen, you have now successfully created a new Django project.

Installing Django

Install Django?

We recommend to install Python 3 and pip3.

To test your Python version, open the command prompt and type:

python –version

On some systems both versions of Python are installed, in that case use python3.

You may like: Python and Django Full Stack Web Developer Bootcamp
icon

Django works with both versions of Python, but Python 2 is legacy.

Installing Django

We use pip to install django:

pip3 install django

We then see:

pip3 install django
[sudo] password for user:
Collecting django
Downloading Django-1.11.3-py2.py3-none-any.whl (6.9MB)
100% |████████████████████████████████| 7.0MB 107kB/s
Requirement already satisfied: pytz in /usr/lib/python3.6/site-packages (from django)
Installing collected packages: django
Successfully installed django-1.11.3

Django version

You can check your version using Python.

On Liux and Mac OS X:

python3 -m django –version

On windows:

py -3 -m django –version

12