Django
项目打开PyCharm
专业版,选择新建项目,左侧选择Django
,选择新建或已有虚拟环境,创建项目book_manager
。
app
进入虚拟环境,运行如下命令:
python manage.py startapp front
front
的views.py
from django.shortcuts import render
def index(request):
pass
def add_book(request):
pass
def book_detail(request,book_id):
pass
打开主urls.py
文件,编辑urlpatterns
:
from django.urls import path
from front import views
urlpatterns = [
path('', views.index, name='index'),
path('add_book/', views.add_book, name='add_book'),
path('book_detail/', views.book_detail, name='book_detail'),
]
创建3个模板文件,index.html
、add_book.html
、book_detail.html
。
front
的视图函数from django.shortcuts import render
def index(request):
return render(request, 'index.html')
def add_book(request):
pass
def book_detail(request,book_id):
pass
settings.py
文件DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'book_manager',
'USER': 'root',
'PASSWORD': 'root',
'HOST': '127.0.0.1',
'PORT': '3306',
}
}
使用数据库连接,需要安装
mysqlclient
pip install mysqlclient
app
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'front'
]
front.index
视图函数,获取并传递首页数据from django.shortcuts import render
from django.db import connection
def get_corsor():
return connection.cursor()
def index(request):
cursor = get_corsor()
cursor.execute("select * from book")
books = cursor.fetchall()
# [(1,'三国演义', '罗贯中'), ...]
return render(request, 'index.html', context={"books":books})
def add_book(request):
pass
def book_detail(request,book_id):
pass
index.html
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
head>
<body>
<nav>
<ul class="nav">
<li><a href="/">首页a>li>
<li><a href="{% url 'add_book' %}">发布图书a>li>
ul>
nav>
body>
html>
index.css
front/static/front
文件夹index.css
文件*{
margin:0;
padding: 0;
}
.nav{
background: #3a3a3a;
height: 65px;
overflow: hidden;
}
.nav li{
float:left;
list-style: none;
margin:0 20px;
line-height: 65px;
}
.nav li a{
color:#fff;
text-decoration: none;
}
.nav li a:hover{
color: lightblue;
}
index.html
顶部加载static
{% load static %}
<html lang="en">
index.css
文件{% load static %}
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
<link rel="stylesheet" href="{% static 'front/index.css' %}">
head>
抽取后的公共部分存入base.html
。
# base.html
{% load static %}
<html lang="en">
<head>
<meta charset="UTF-8">
<title>图书管理系统title>
<link rel="stylesheet" href="{% static 'front/base.css' %}">
head>
<body>
<nav>
<ul class="nav">
<li><a href="/">首页a>li>
<li><a href="{% url 'add_book' %}">发布图书a>li>
ul>
nav>
{% block content %}{% endblock %}
body>
html>
重构后的ndex.html
文件如下:
{% extends 'base.html' %}
{% block content %}
{% endblock %}
修改后的index.html
文件内容如下:
{% extends 'base.html' %}
{% block content %}
<table>
<thead>
<tr>
<th>序号th>
<th>书名th>
<th>作者th>
tr>
thead>
<tbody>
{% for book in books %}
<tr>
<td>{{ forloop.counter }}td>
<td>{{ book.1 }}td>
<td>{{ book.2 }}td>
tr>
{% endfor %}
tbody>
table>
{% endblock %}