Python Django
Installation
1 | python -m pip install Django |
Writing your first Django app, part 1
Creating a project
Change Directory to the directory you would like to store your project first.
1 | django-admin startproject mysite |
This will create a mysite directory in your current directory.
Note: You’ll need to avoid naming projects after built-in Python or Django components. In particular, this means you should avoid using names like django (which will conflict with Django itself) or test (which conflicts with a built-in Python package).
Where should this code live?
If your background is in plain old PHP (with no use of modern frameworks), you’re probably used to putting code under the Web server’s document root (in a place such as /var/www). With Django, you don’t do that. It’s not a good idea to put any of this Python code within your Web server’s document root, because it risks the possibility that people may be able to view your code over the Web. That’s not good for security.
Put your code in some directory outside of the document root, such as /home/mycode
.
Let’s look at what startproject
created:
1 | mysite/ |
These files are:
- The outer
mysite/
root directory is a container for your project. Its name doesn’t matter to Django; you can rename it to anything you like. manage.py
: A command-line utility that lets you interact with this Django project in various ways. You can read all the details aboutmanage.py
in django-admin and manage.py.- The inner
mysite/
directory is the actual Python package for your project. Its name is the Python package name you’ll need to use to import anything inside it (e.g. mysite.urls). mysite/__init__.py
: An empty file that tells Python that this directory should be considered a Python package. If you’re a Python beginner, read more about packages in the official Python docs.mysite/settings.py
: Settings/configuration for this Django project. Django settings will tell you all about how settings work.mysite/urls.py
: The URL declarations for this Django project; a “table of contents” of your Django-powered site. You can read more about URLs in URL dispatcher.mysite/asgi.py
: An entry-point for ASGI-compatible web servers to serve your project. See How to deploy with ASGI for more details.mysite/wsgi.py
: An entry-point for WSGI-compatible web servers to serve your project. See How to deploy with WSGI for more details.
The development server
Let’s verify your Django project works. Change into the outer mysite directory, if you haven’t already, and run the following commands:
1 | python manage.py runserver |
Changing the port
By default, the runserver command starts the development server on the internal IP at port 8000.
If you want to change the server’s port, pass it as a command-line argument. For instance, this command starts the server on port 8080:
1 | python manage.py runserver 8080 |
If you want to change the server’s IP, pass it along with the port. For example, to listen on all available public IPs (which is useful if you are running Vagrant or want to show off your work on other computers on the network), use:
1 | python manage.py runserver 0:8000 |
Creating the Polls app
Now that your environment – a “project” – is set up, you’re set to start doing work.
Each application you write in Django consists of a Python package that follows a certain convention. Django comes with a utility that automatically generates the basic directory structure of an app, so you can focus on writing code rather than creating directories.
Projects vs. apps
What’s the difference between a project and an app? An app is a Web application that does something – e.g., a Weblog system, a database of public records or a small 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.
Your apps can live anywhere on your Python path. In this tutorial, we’ll create our poll app in the same directory as your manage.py file so that it can be imported as its own top-level module, rather than a submodule of mysite.
To create your app, make sure you’re in the same directory as manage.py and type this command:
To create your app, make sure you’re in the same directory as manage.py and type this command:
1 | python manage.py startapp polls |
That’ll create a directory polls, which is laid out like this:
1 | polls/ |
This directory structure will house the poll application.
Write your first view
Let’s write the first view. Open the file polls/views.py and put the following Python code in it:
1 | from django.http import HttpResponse |
This is the simplest view possible in Django. To call the view, we need to map it to a URL - and for this we need a URLconf.
To create a URLconf in the polls directory, create a file called urls.py. Your app directory should now look like:
1 | touch urls.py |
1 | polls/ |
In the polls/urls.py file include the following code:
1 | from django.urls import path |
The next step is to point the root URLconf at the polls.urls module. In mysite/urls.py, add an import for django.urls.include and insert an include() in the urlpatterns list, so you have:
1 | from django.contrib import admin |
The include() function allows referencing other URLconfs. Whenever Django encounters include(), it chops off whatever part of the URL matched up to that point and sends the remaining string to the included URLconf for further processing.
The idea behind include() is to make it easy to plug-and-play URLs. Since polls are in their own URLconf (polls/urls.py), they can be placed under “/polls/”, or under “/fun_polls/”, or under “/content/polls/”, or any other path root, and the app will still work.
When to use include()
You should always use include() when you include other URL patterns. admin.site.urls is the only exception to this.
You have now wired an index view into the URLconf. Verify it’s working with the following command:
1 | python manage.py runserver |
Go to http://localhost:8000/polls/ in your browser, and you should see the text “Hello, world. You’re at the polls index.”, which you defined in the index view.
The path() function is passed four arguments, two required: route and view, and two optional: kwargs, and name. At this point, it’s worth reviewing what these arguments are for.
- 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 for myapp/. In a request to https://www.example.com/myapp/?page=3, the URLconf will also look for myapp/.
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.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.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.
When you’re comfortable with the basic request and response flow, read part 2 of this tutorial to start working with the database.
Writing your first Django app, part 2
If you’re having trouble going through this tutorial, please head over to the Getting Help section of the FAQ.
Database setup
Now, open up mysite/settings.py. It’s a normal Python module with module-level variables representing Django settings.
By default, the configuration uses SQLite. If you’re new to databases, or you’re just interested in trying Django, this is the easiest choice. SQLite is included in Python, so you won’t need to install anything else to support your database. When starting your first real project, however, you may want to use a more scalable database like PostgreSQL, to avoid database-switching headaches down the road.
If you wish to use another database, install the appropriate database bindings and change the following keys in the DATABASES ‘default’ item to match your database connection settings:
- ENGINE – Either ‘django.db.backends.sqlite3’, ‘django.db.backends.postgresql’, ‘django.db.backends.mysql’, or ‘django.db.backends.oracle’. Other backends are also available.
- NAME – The name of your database. If you’re using SQLite, the database will be a file on your computer; in that case, NAME should be the full absolute path, including filename, of that file. The default value, os.path.join(BASE_DIR, ‘db.sqlite3’), will store the file in your project directory.
If you are not using SQLite as your database, additional settings such as USER, PASSWORD, and HOST must be added. For more details, see the reference documentation for DATABASES.
For databases other than SQLite
If you’re using a database besides SQLite, make sure you’ve created a database by this point. Do that with “**CREATE DATABASE database_name;**” within your database’s interactive prompt.
Also make sure that the database user provided in mysite/settings.py has “create database” privileges. This allows automatic creation of a test database which will be needed in a later tutorial.
If you’re using SQLite, you don’t need to create anything beforehand - the database file will be created automatically when it is needed.
While you’re editing mysite/settings.py, set TIME_ZONE to your time zone.
Also, note the INSTALLED_APPS setting at the top of the file. That holds the names of all Django applications that are activated in this Django instance. Apps can be used in multiple projects, and you can package and distribute them for use by others in their projects.
By default, INSTALLED_APPS contains the following apps, all of which come with Django:
- django.contrib.admin – The admin site. You’ll use it shortly.
- django.contrib.auth – An authentication system.
- django.contrib.contenttypes – A framework for content types.
- django.contrib.sessions – A session framework.
- django.contrib.messages – A messaging framework.
- django.contrib.staticfiles – A framework for managing static files.
These applications are included by default as a convenience for the common case.
Some of these applications make use of at least one database table, though, so we need to create the tables in the database before we can use them. To do that, run the following command:
1 | python manage.py migrate |
If you meet some error, review the Chapter Setting For MySQL.
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 and the database migrations shipped with the app (we’ll cover those later). You’ll see a message for each migration it applies. If you’re interested, run the command-line client for your database and type \dt (PostgreSQL), SHOW TABLES; (MariaDB, MySQL), .schema (SQLite), or SELECT TABLE_NAME FROM USER_TABLES; (Oracle) to display the tables Django created.
For the minimalists
Like we said above, the default applications are included for the common case, but not everybody needs them. If you don’t need any or all of them, feel free to comment-out or delete the appropriate line(s) from INSTALLED_APPS before running migrate. The migrate command will only run migrations for apps in INSTALLED_APPS.
Setting For MySQL
Prerequisite
Install the following software or plug-in
- MySQL Server
- mysqlclient
Install mysqlclient
through Conda (Recommend)
1 | conda install -c bioconda mysqlclient |
Set Up MySQL user and database
- Login your MySQL server as root. Create a user for your website. e.g, my website user is
mysite-admin
.
Noticemysql_native_password
is required for DjangoMySQL 1
CREATE USER 'mysite-admin'@'localhost' IDENTIFIED WITH mysql_native_password BY 'your_password1',
- Create a database for your website. e.g, my database is
mysite
.MySQL 1
CREATE DATABASE mysite
- Grant privileges. Your website user must has the privilege of CREATE database.
MySQL 1
2GRANT CREATE ON *.* TO 'mysite-admin'@'localhost'
GRANT ALL PRIVILEGES ON 'mysite'.* TO 'mysite-admin'@'localhost' - If you didn’t specify
mysql_native_password
as the authentication way in step 2, you can change it now. Notice, “caching_sha2_password” is a safer authentication but it does not work for Django.MySQL 1
2
3
4
5
6
7
8
9USE mysql;
select user,plugin from user where user='mysite-admin';
alter user 'your_username'@'your_host' identified with mysql_native_password;
select user,plugin from user where user='mysite-admin';
flush privileges - Modify your
settings.py
file. Replace the following part to your configuration.
Refer to the settings documentation.
Connection settings are used in this order:
1. OPTIONS.
2. NAME, USER, PASSWORD, HOST, PORT
3. MySQL option files.
In other words, if you set the name of the database in **OPTIONS**, this will take precedence over **NAME**, which would override anything in a MySQL option file.
Here’s a sample configuration which uses a MySQL option file:
1 | # settings.py |
In my experiment, I store MySQL option file (my.cnf) in other directory and let setting.py
to load it. Replace the following settings to yours.
1 | # Database |
6. In your manage.py
directory, test the database.
1 | python manage.py inspectdb |
One More Thing
Python Algorithms - Words: 2,640
Python Crawler - Words: 1,663
Python Data Science - Words: 4,551
Python Django - Words: 2,409
Python File Handling - Words: 1,533
Python Flask - Words: 874
Python LeetCode - Words: 9
Python Machine Learning - Words: 5,532
Python MongoDB - Words: 32
Python MySQL - Words: 1,655
Python OS - Words: 707
Python plotly - Words: 6,649
Python Quantitative Trading - Words: 353
Python Tutorial - Words: 25,451
Python Unit Testing - Words: 68