preface
Django juejin (Django juejin. Cn) uses a hello World widget to get familiar with the basics of Django development. With that in mind, we’ll write a slightly more complex to-do app. Use this example to familiarize yourself with Django.
My computer environment is Win10 system, text editor is VS Code, browser is Microsoft Edge.
This article assumes that you have a basic knowledge of python3 syntax and a little HTML syntax.
Final effect display
The effect after the above is the final finish, a simple to-do list software, at the top is the title, followed by a can input item contents of the input box (form), finally will show you all outstanding items, and comes with a delete button, point to remove this item, both said this task has been completed.
Install django
Run the following command using CMD or Powershell, a command line tool with administrator privileges
PIP install django = = 2.2Copy the code
Create your Django project
Proceed with the following command from the command line, first switch the working directory to the desktop (assuming you put the project on the desktop, or wherever you like), and then create the project, this time named TodoApp
cd C:\Users\Derek\Desktop
django-admin startproject todoapp
Copy the code
Note the path to the desktop, where you’ll need to replace Derek with your Windows username.
Test whether the server works properly
We need to start the service at the same level as the manage.py file, and since our working directory was on the desktop, we now need to switch inside the project folder todoApp and run the following command.
cd todoapp
python.exe .\manage.py runserver
Copy the code
If you see something similar to the following, you’ve succeeded.
Create an
You can temporarily close the browser window and follow the instructions in the terminal output window by pressing Ctrl+C to stop the server. A Django project can contain multiple application modules, much like a supermarket divided into fruit sections, drinks sections, and snacks sections. So now we need to create our first application for our project and call it Main, the main application.
python .\manage.py startapp main
Copy the code
Directory of
Now that we have the directory structure we need for this development, we can use VS Code to open our project folder, the TodoApp folder on the desktop.
The specific directory structure is shown below, you can compare it with me.
Add our new app Main to settings.py
Go to settings.py in the main project folder todoApp and add the app main to the INSTALLED_APPS area.
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'main',
]
Copy the code
The purpose is to let Django know that we have a new application called Main.
Configuring URL Parsing
We know that the way web applications work is that the user enters a URL into the browser, the URL, and then goes to the corresponding page and displays it, and this process is CALLED URL parsing or URL routing, where one URL corresponds to one function page, The entry point for our entire project is the urls.py file in the project folder TodoApp. You can see that there is a variable called UrlPatterns that stores the mapping between urls and functions. We now need to transfer control of URL parsing from the main project entry to our app called Main. Specific practices are as follows:
As a first step, in the urls.py file under the project folder Todoapp, write the following code
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path(' ',include('main.urls')),]Copy the code
Second, create a urls.py file in your app’s main folder and add the following code
from django.urls import path
from . import views
urlpatterns = [
path(' ',views.index, name='index'),]Copy the code
To clarify, in the first step above, in addition to the default import, we imported an additional include function, and then added a new URL matching rule under the default admin
Path (”,include(‘main.urls’)), the first argument is an empty single quotation mark representing the URL http://127.0.0.1/. The quotation mark is an empty string because the host address does not contain any keywords. The second parameter is include(‘main.urls’), which means that when the user types 127.0.0.1/ the address, he gives resolution control to the urls file below main, and then to the urls file below main, which also has an urlpatterns variable, Path (”,views.index, name=’index’); the first parameter is null; the second parameter is views.index. URL 127.0.0.1/ corresponds to the function named index in the views file. The third parameter indicates that the URL resolution rule is named ‘index’.
Create the first function index
Because the last URL matching rule finally falls on the function index of views, but our index function does not exist yet, so now we need to create a function index.
Open the views file to main/views.py and override the original code with the following code.
from django.shortcuts import render
def index(request) :
return render(request,'index.html')
Copy the code
We first import the render function, which returns an HTML page document to the user’s browser. The HTML document can be static, or it can be a dynamic page containing variables, usually called a template. Then create a function called index. The request parameter represents the user’s request object, which is fixed and written each time, and finally returns the index.html document to the end user and displays it in the browser.
Create your first HTML template
The index function above returns the index.html template to the user, so now you need to write the contents of the HTML template. Start by creating a new folder called templates under your main folder, create a new file called index.html, and fill in the following.
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<title>Home Page</title>
</head>
<body>
<h1>todo</h1>
</body>
</html>
Copy the code
Basically a very simple HTML file, including some basic tags, if you do not understand can go to the web search tutorial, or relatively simple.
So the final actual page should only show the word “to-do”.
Now let’s test by typing the command to start the server from the command line.
python manage.py runserver
Copy the code
Seeing those four big words is a sign of success.
Summary of development process
The first step is to configure url routing, the second step is to write view functions, and the third step is to write HTML template files.
A few files involved: urls.py — views.py — xxx.html
The result is a simple Web application.
Build a database model
To write a Web application in Django, you don’t need to write a raw SQL statement. Instead, you use ORM (Object relational mapping) to call a database. Basically, you map a table in a relational database such as SQllite to a Class in Python. This makes programming very easy and convenient.
Find models.py under main and update the following code.
from django.db import models
class TodoModel(models.Model) :
name = models.CharField(max_length = 200)
def __str__(self) :
return self.name
Copy the code
Model class. TodoModel represents a table in the database, and each of the following attributes represents a field in the database table. For example, our first field is name. The type is a string represented as CharField and has a maximum length of 200. The final __str__ section has the effect that when you output an object, it displays the name of the object instead of object.
Migrating a Database
The above only defines the model, but does not actually create tables in the database, execute the following command to migrate the database.
python .\manage.py makemigrations
python .\manage.py migrate
Copy the code
Logging In to the Admin Background
Django has a ready-made background page for administrators to add data to a database. Let’s create an administrator account:
python manager.py createsuperuser
Copy the code
You will then be prompted for your username and password and email address, which will be used later.
Open the admin.py file in the main app and update the following code:
from django.contrib import admin
from .models import TodoModel
admin.site.register(TodoModel)
Copy the code
The above code registers the database model we defined earlier into the background interface.
Since there was a code path(‘admin/’, admin.site.urls) in urls.py under the previous project folder todoapp, we can open the admin interface with the path admin. The complete address to http://127.0.0.1:8000/admin
Enter the user name and password we created just now to log in.
As shown, our Todo model appears on the screen. Next, click the Add button to add two to-do items, “Learn Django” and “Learn HTML.”
Displays the database’s to-do items on a web page
Now we need to update the views.py file. Before, we just had the index function return the index.html template file directly, but this time we will query all the todos from the database, and then pass the data to the HTML template and display it.
Update the index function in views.py:
from django.shortcuts import render,redirect
from .models import TodoModel
def index(request) :
list = TodoModel.objects.all(a)return render(request,'index.html', {'list':list})
Copy the code
Todomodel.objects.all () is used to query all data in the database and assign a value to the list variable. In addition to returning an HTML file, todomodel.objects.all () is used to inject all data from the list into the index template.
Next, update the index.html file:
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<title>Home Page</title>
</head>
<body>
<div>
<div>
<a href="{% url 'index' %}">Todo List</a>
</div>
<div>
{% for item in list %}
<div>
<span>{{ item }}</span>
</div>
{% endfor %}
</div>
</div>
</body>
</html>
Copy the code
There is a new syntax to note: {% for item in list %}{% endfor %}, which means to use loops in the HTML template, because we don’t know how many items are stored in the database, {{item}}, which means to display the value of the variable.
{% url ‘index’ %} represents a URL with the name index, corresponding to the path(“,views.index, name=’index’) we wrote in urls.py earlier.
Start the server again and the page should appear as follows.
Add a form to allow users to add their own to-do lists
Now our program can only add data to the database in the background as the administrator, but we need the end user to also enter the content of the to-do items on the front page, which needs to use the form, the form is a common input box on the web page, convenient for users to submit data to the website background.
First, continue to update index.html
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<title>Home Page</title>
</head>
<body>
<div>
<div>
<a href="{% url 'index' %}">Todo List</a>
</div>
<div>
<form action="{% url 'index' %}" method="post">
{% csrf_token %}
<input type="text" name="name">
<input type="submit" value="Add">
</form>
{% for item in list %}
<div>
<span>{{ item }}</span>
</div>
{% endfor %}
</div>
</div>
</body>
</html>
Copy the code
We added the HTML form form this time. If you are not familiar with this syntax, you can search the HTML form online.
Action =”{% URL ‘index’ %}” means that after the form is submitted, the data will be sent to the index route, which is the home page.
Method =”post” indicates that the HTTP post method is used. Since data needs to be submitted, post is used instead of GET.
{% csrF_token %} adds a security aspect that is mandatory in Django.
As shown in the image above, there is now an input box on the page. The next step is to update views.py so that the application can handle the data submitted from the front end.
from django.shortcuts import render,redirect
from .models import TodoModel
def index(request) :
if request.method == 'POST':
new = TodoModel(name=request.POST['name'])
new.save()
return redirect('/')
list = TodoModel.objects.all(a)return render(request,'index.html', {'list':list})
Copy the code
This time we add an if judgment, if post request, then we add data to the database, notice that the new data is equal to instantiating an object of the TodoModel class, assigning the value of the name attribute in the form to the name attribute, and then saving it to the database. Finally, you need to redirect the page back to the main page index.
If it is a normal GET request, the index home page is displayed as before and the list data is injected.
At this point, we can try to enter the contents of the to-do item on the page and click the Add button to submit it to the database.
Add delete button
Once the new entry is complete, we go ahead and make a Delete delete button so that users can delete unwanted to-do items, first updating index.html
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<title>Home Page</title>
</head>
<body>
<div>
<div>
<a href="{% url 'index' %}">Todo List</a>
</div>
<div>
<form action="{% url 'index' %}" method="post">
{% csrf_token %}
<input type="text" name="name">
<input type="submit" value="Add">
</form>
{% for item in list %}
<div>
<span>{{ item }}</span> <span><a href="{% url 'delete' item.id %}">Delete</a></span>
</div>
{% endfor %}
</div>
</div>
</body>
</html>
Copy the code
This time, we added an A tag, or hyperlink, that points to a DELETE route (it doesn’t yet exist), and passed in an item.id primary key, the id attribute django automatically added for us, which represents the database primary key, an integer that starts at 1.
Let’s now add the delete route:
from django.urls import path
from . import views
urlpatterns = [
path(' ',views.index, name='index'),
path('delete/<str:pk>/',views.delete,name='delete'),]Copy the code
We added a new URL route called delete, which uses the dynamic URL parameter pk, STR string, Actually the effect as http://127.0.0.1/delete/1, http://127.0.0.1/delete/2, http://127.0.0.1/delete/3, and so on.
Then add a new delete view function:
views.py
from django.shortcuts import render,redirect
from .models import TodoModel
def index(request) :
if request.method == 'POST':
new = TodoModel(name=request.POST['name'])
new.save()
return redirect('/')
list = TodoModel.objects.all(a)return render(request,'index.html', {'list':list})
def delete(request,pk) :
target = TodoModel.objects.get(id=pk)
target.delete()
return redirect('/')
Copy the code
Add the style
CSS stands for cascading style sheets (CSS), which is used to modify the style of a web page. First we need to create a new folder named static under mian, and then create a new style. CSS file under mian. Paste in the following code:
body {
background-color:cornflowerblue;
}
.container {
text-align: center;
background-color: blanchedalmond;
border: darkmagenta;
border-style: solid;
border-radius: 5%;
width: 600px;
height: 800px;
margin: auto;
}
.home-button {
text-decoration: none;
font-size: 50px;
}
.name-input {
width: 60%;
height: 25px;
margin-top: 20px;
margin-bottom: 20px;
}
.submit {
background-color: darkmagenta;
font-size: 20px;
width: 70px;
}
.todo-box {
border-style: solid;
border-width: thin;
border-color: darkmagenta;
background-color: blanchedalmond;
margin-left: 30px;
margin-right: 30px;
margin-top: 10px;
margin-bottom: 10px;
}
.delete-button {
text-decoration: none;
}
.box-right {
float: right;
margin-right: 10px;
}
Copy the code
Then update our index.html to add some classes to the tag:
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<title>Home Page</title>
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'style.css' %}">
</head>
<body>
<div class="container">
<div>
<a class="home-button" href="{% url 'index' %}">Todo List</a>
</div>
<div>
<form action="{% url 'index' %}" method="post">
{% csrf_token %}
<input class="name-input" type="text" name="name">
<input class="submit" type="submit" value="Add">
</form>
{% for item in list %}
<div class="todo-box">
<span>{{ item }}</span> <span class="box-right"><a class="delete-button" href="{% url 'delete' item.id %}">Delete</a></span>
</div>
{% endfor %}
</div>
</div>
</body>
</html>
Copy the code
That’s it. Now close the browser and open it again and you should see the changes.
Code control
Because there are many steps, HERE I put the source code of the project into Gitee for everyone to compare, thank you.
https://gitee.com/derekll/todoapp
Copy the code