WebSite Making

We are going to write a Django project so that we can learn the basic concepts and operations. Our website is a basic poll application, which consist of two parts:

  • A pyblic site that lets people view polls and vote in them
  • An admin site that lets you add, change, and delete polls.

Create a project

The first thing we need to do is to create a Django project, which is a collection of settings for an instance of Django, including database configuration, Django-specific options and application-specific settings.

From the command line, cd into the directory where you would like to store your project, then run the following command:

django-admin startproject MyWebsite

This will result in a directory in your current directory and the directory structure is like:

creen Shot 2019-03-07 at 9.29.13 P

  1. The outter MyWebsite/ root directory is just a container for our project. It is name doesn’t matter to Django; so you can rename it whenever you want.
  2. The inner MyWebsite/ directory is the actural Python package for our project.
    • MyWebsite/.settings.py is for configuration for this Django project.
    • MyWebsite/urls.py is for URL declarations for Django project.
    • MyWebsite/wsgi.py is an entery-point for WSGI-compatible web servers to serve the project.
  3. manage.py is a command-line utility that lets you interact with the Django project.

Development server

Once we created the project, we can verify whether it works by running the following command:

python manage.py runserver

The following output will be on the terminal:

1
2
3
4
5
6
7
8
Performing system checks...
System check identified no issues (0 silenced).
You have unapplied migrations; your app may not work properly until they are applied.
Run 'python manage.py migrate' to apply them.
February 28, 2019 - 15:50:53
Django version 2.1, using settings 'mysite.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

Then we can visit http://127.0.0.1:8000/ with browser.

By default, the runserver command starts the development server on the internal IP at port 8000. If you want to use another port, you can pass it as a command-line argument.

python manage.py runserver 8080

If you want to change the server’s IP, pass it along with the prot.

python manage.py runserver 0:8080

Create the Polls app

Now that we can create the apps under this project. To be clear, an app is a Web application that does something – e.g., a Weblog system, a database of public records or a simple poll app. A project is a collection of configuration and apps for a particular website. A project can contain multiple apps. An app can be in multiple projects.

To create our app, make sure we are in the same directory as manage.py and type the command:

ppython manage.py startapp polls

we will get a directory like this:

creen Shot 2019-03-12 at 1.41.00 P

Write a view

Open polls/views.py and put the following code in it:

1
2
3
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello World!")

To call the view, we need to map it to a URL. Therefore we need to create a urls.py and write the codes:

1
2
3
4
5
from django.urls import path
from . import views
urlpatterns = [
path('',views.index,name='index')
]

The next step is to point the root URLconf at the polls.urls module. Open MyWebsite/urls.py:

1
2
3
4
5
6
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('polls/', include('polls.urls')),
path('admin/', admin.site.urls),
]

Here, the include() function allows referencing other URLconfs. We should always use include() when you include other URL patterns. admin.site.urls is the only exception to this.

Finally, run the command python manage.py runserver and go to http://127.0.0.1:8000/polls/, we should see the text Hello World!, which is defined in the index view.

The path() function takes four arguments, two required: route and view, and two optional:kwargs and name.

  1. path() argument: route

    route is a string that contains a URL pattern. When processing a request, Django starts at the first pattern in urlpatterns and makes its way down the list, comparing the requested URL against each pattern until it finds one that matches.

    Patterns don’t search GET and POST parameters, or the domain name. For example, in a request to https://www.example.com/myapp/, the URLconf will look formyapp/. In a request to https://www.example.com/myapp/?page=3, the URLconf will also look for myapp/.

  2. path() argument: view

    When Django finds a matching pattern, it calls the specified view function with an HttpRequest object as the first argument and any “captured” values from the route as keyword arguments. We’ll give an example of this in a bit.

  3. path() argument: kwargs

    Arbitrary keyword arguments can be passed in a dictionary to the target view. We aren’t going to use this feature of Django in the tutorial.

  4. path() argument: name

    Naming your URL lets you refer to it unambiguously from elsewhere in Django, especially from within templates. This powerful feature allows you to make global changes to the URL patterns of your project while only touching a single file.

Database setup

By default, the configuration uses SQLite, which is included in Python and thus we won’t need to install anything else to support your database. Now, open Mywebsite/settings.py.We can see that in INSTALLED_APPS, there are several predefined applications as a convenience of common use.

creen Shot 2019-03-14 at 12.26.11 P

Note that these applications use at least one database table. Then we need to create tables for them before we use them by running the following command:

python manage.py migrate

The migrate command looks at the INSTALLED_APPS setting and creates any necessary database tables according to the database settings in your mysite/settings.py file .

Create models

A model is the single, definitive source of truth about your data. It contains the essential fields and behaviors of the data you’re storing.

In our poll application, we are going to create two tables: Question and Choice. Question model has two fields: question_text and pub_date. Choice has two fields too: choice_text and votes tally. And each Choice is associated with a Question. Open polls/models.py and put the following codes:

1
2
3
4
5
6
7
8
from django.db import models
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
class Choice(models.Model):
question = models.ForeignKey(Question,on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)

The code is straightforward. Each model is represented by a class that subclasses django.db.models.Model. Each model has a number of class variables, each of which represents a database field in the model.

Each field is represented by an instance of a Field class – e.g., CharField for character fields and DateTimeField for datetimes. This tells Django what type of data each field holds.

The name of each Field instance (e.g. question_text or pub_date) is the field’s name, in machine-friendly format. You’ll use this value in your Python code, and your database will use it as the column name.

Finally, note a relationship is defined, using ForeignKey. That tells Django each Choice is related to a single Question. Django supports all the common database relationships: many-to-one, many-to-many, and one-to-one.

Activate models

With the above codes, we can create a database schema (CREATE TABLE statements) for this app and create a Python database-access API for accessing Question and Choice objects. But first we need to tell our project that the polls app is installed. Therefore, we need to add models to INSTALLED_APPS setting. The PollsConfig class is in the polls/apps.py file, so its dotted path is 'polls.apps.PollsConfig'. Edit the mysite/settings.py file and add that dotted path to the INSTALLED_APPS setting. It’ll look like this:

creen Shot 2019-03-14 at 12.47.20 P

Now Django knows to include the polls app. Let’s run another command:

python manage.py makemigrations polls

By running makemigrations, you’re telling Django that you’ve made some changes to your models (in this case, you’ve made new ones) and that you’d like the changes to be stored as a migration.

Now we can run migrate again to create those model table:

python manage.py migrate

The migrate command takes all the migrations that haven’t been applied (Django tracks which ones are applied using a special table in your database called django_migrations) and runs them against your database - essentially, synchronizing the changes you made to your models with the schema in the database.

In summary, there three steps to make model changes:

Playing with the API

Now, let’s hop into the interactive Python shell and play around with the free API Django gives you. To invoke the Python shell, use this command:

1
python manage.py shell

Once we are in the shell, explore the database API.

Django Admin

Create an admin user

Firstly, we need to create a user who can login to the admin site. In order to create such user, we can use the command like this:

python manage.py createsuperuser

Then enter username, email address and password:

Username:admin

Email address: admin@example.com

Password:admin123

The Django admin site is activated by default. Let’s start server and explore it:

python manage.py runserver

Now, open a web browser and go to “/admin/“ on your local domain, e.g., http://127.0.0.1:8000/admin/

dmin0

Once you login to the website using username and password, we can see:

dmin0We should see a few types of editable content: groups and users. They are provided by django.contrib.auth, the authentication framework shipped by Django.

Make the poll app modifiable in the admin

But where’s our poll app? It’s not displayed on the admin index page.

Just one thing to do: we need to tell the admin that Question objects have an admin interface. To do this, open the polls/admin.py file, and edit it to look like this:

1
2
3
from django.contrib import admin
from .models import Question
admin.site.register(Question)

Now that we’ve registered Question, Django knows that it should be displayed on the admin index page:

dmin03

Day1 Basic Commands

  1. Create a new Django project

    1
    django-admin.py startproject project_name
  2. Create a new app

    1
    python manage.py startapp app_name

    Open the Django project directory, then execute the command. Usually a Django project can have multiple app.

  3. Run the app

    1
    2
    3
    4
    5
    6
    python manage.py runserver
    # use specified port
    python manage.py runserver 8001
    python manage.py runserver 9999
    # all available ip
    python manage.py runserver 0.0.0.0:8000
  4. Create a database table

    1
    2
    python manage.py makemigrations
    python manage.py migrate
  5. Clear the database

    1
    python manage.py flush
  6. Import/Export Data

    1
    2
    python manage.py dumpdata appname > appname.json
    python manage.py loaddata appname.json
  7. Create supermanager

    1
    python manage.py createsuperuser

Day2 View and URL

Here we are going to write a “Hello World!” application to illustrate the relationship between views and urls.

Firstly, use the command to create a project. Of course we can also pycharm to create a project named “MyWebsite”. We can see the project file structures:

creen Shot 2019-03-07 at 9.29.13 P

Then inside this project, we are going to create an app named “FirstDemo”:

1
python manage.py startapp FirstDemo

Then, we have the new structures:

creen Shot 2019-03-07 at 9.31.49 P

we can find that there is one added directory “FirstDemo”. After creating a new app, we are going to registering this app to the whole project by add this new app to settings.py:

creen Shot 2019-03-07 at 9.34.23 P

After this, we are going to define a view function. A view function specify what we are going to see when we open the website. Go to “FirstDemo” and open “views.py”:

creen Shot 2019-03-07 at 9.37.38 P

Here, we define a “HelloWorld” function, whose parameter is request and the first parameter can only be request. A request variable includes get and post infomation. This function use HttpResponse to return information to the webpage, like print in python.

After we define the function of our webpage, but how can be visit it? We are going to define the url that we need to visit the webpage. Open the MyWebsite/MyWebsite/urls.py,we are going to import the view function:

1
from FirstDemo import views as fd_views

then we define the url:

1
path('',fd_views.HelloWorld),

The overall modification is like:

creen Shot 2019-03-07 at 9.46.20 PM-201679

Finally we can run our project:

creen Shot 2019-03-07 at 9.47.39 P

Open the link, we can see:

creen Shot 2019-03-07 at 9.48.17 P

Day3 Advanced Views and Urls

Last time, we have learned how to display information in django. This time, we are about to implement a little complex function, i.e., addition, and display the addition result.

/add/?a=4&b=5 to visit webpage

Firstly, let’s create a new app named Addition:

1
python manage.py startapp Addition

We need to define the addition function in views.py

1
2
3
4
5
6
7
from django.shortcuts import render
from django.http import HttpResponse
def add(request):
a = request.GET['a']
b = request.GET['b']
c = int(a)+int(b)
return HttpResponse(str(c))

Here, request.GET return a dictionary, request.GET['a'] return a value. A better way is request.GET.get('a',0) where a default value 0 is return if a is not defined.

Then we need to modify urls.py:

creen Shot 2019-03-10 at 5.17.57 P

Finally, we can run our program:

1
python manage.py runserver 8110

Here, we set the port 8110. And we can use the following url to visit the webpage:

1
http://127.0.0.1:8110/add/

But we found that:creen Shot 2019-03-10 at 5.21.18 P

That is because we didn’t give initial value to a and b.

1
http://127.0.0.1:8110/add/?a=4&b=5

Using the above url, we can see 9 displayed.

/add/3/4 to visit page

Here we define another add function in views.py

1
2
3
def add2(request,a,b):
c = int(a)+int(b)
return HttpResponse(str(c))

Then, in urls.py:

creen Shot 2019-03-10 at 5.27.19 P

Finally we run the program and visit the webpage:

1
http://127.0.0.1:8110/add/3/4/

Reference

Deploying a Keras Deep Learning Model as a Web Application in Python

Bringing visualisation to the web with Python and Bokeh

Django tutorials