django專案實踐
阿新 • • 發佈:2022-04-05
第二部分: 程式開發:
建立Django部分:
在專案中下載mysql資料庫外掛
pip install mysqlclient
在目錄終端輸入指令:
django-admin startproject '專案名字' #建立django專案
cd '專案名字' #移動進專案
python manage.py startapp 'app名字' #建立app
開啟建立好的專案後 點選專案名下的__init__.py檔案 匯入資料庫外掛
import pymysql
pymysql.install_as_MySQLdb()
配置模型(models.py)
from django.db import models
# Create your models here.
class Teacher(models.Model):
username = models.CharField(max_length=30,verbose_name='員工',primary_key=True,db_index=True)
password = models.IntegerField(default=0,verbose_name='密碼')
age = models.IntegerField(default=0,verbose_name='年齡')
introduce = models.TextField(default='該員工懶,什麼都沒寫',verbose_name='簡介')
class Meta:
db_table = 'teacher'
verbose_name = '學生資訊管理表'
verbose_name_plural = verbose_name
def __str__(self):
return self.username
將app加入到django建立的檔案settings.py中
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'beta' #加入的名字取決於你建立的app的名字
]
在寫好模型'models.py'後,生成一個遷移檔案,然後進行資料庫對映
Python manage.py makemigrations #生成遷移檔案
Python manage.py migrate #資料庫對映
在'sittings.py'中配置連線資料庫
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME':'',
'USER':'',
'PASSWORD':'',
'HOST':'127.0.0.1',
'PORT':'3306',
接下來建立檢視函式(views.py):
from django.shortcuts import render,redirect
from .models import Teacher
# Create your views here.
def login(request):
result = {'error': ''}
if request.method == 'POST':
name = request.POST.get('username')
data = Teacher.objects.filter(username=name)
if data:
password = request.POST.get('password')
data1 = data.first()
if password == str(data1.password):
rep = redirect('/index')
#將使用者名稱儲存到session中
# request.session['username'] = name #繫結使用者ID儲存到資料庫
rep.set_cookie('is_login',data1.username) #儲存使用者的id發
return rep
else:
result['error'] = '密碼錯誤!!!'
else:
result['error'] = '使用者名稱不存在!!!'
return render(request, 'login.html',{'result': result})
def index(request):
teacher=Teacher.objects.all()
return render(request,'course.html',{'teachers':teacher})
def add(request):
data3 = request.COOKIES.get('is_login')
if not data3 == 'root':
return redirect('index')
if request.method == 'POST':
name = request.POST.get('nickname')
age = request.POST['age']
introduce = request.POST['introduce']
# Student.objects.create()
tt = Teacher()
tt.username = name
tt.age = age
tt.introduce = introduce
tt.save()
return redirect('index')
return render(request,'add.html')
# def addcw(request):
# if request.GET['username'] == 'root' and request.GET.get('password') == '1':
# return render(request,'add.html')
# else:
# return render(request,'login02.html')
def update(request):
if request.method == 'POST':
name = request.POST.get('nickname')
age = request.POST.get('age')
introduce = request.POST.get('introduce')
update = Teacher.objects.filter(username=name)
if update:
Teacher.objects.filter(username=name).update(
age=age,
introduce=introduce
)
return redirect('index')
return render(request,'update.html')
def delete(request,username):
Teacher.objects.get(username=username).delete()
return redirect('index')
def chaxun(request):
return render(request,'ss.html')
將網頁放到 ./templates下,將css,js放到static下
修改django專案下的sittings.py檔案:
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [ os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
或:
STATIC_URL = '/static/'
STATICFILES_DIRS = [
./static
]
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ["./templates"],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
前端網頁部分:
{% csrf_token %} #post提交時伺服器會驗證這串字元來確保使用者是在服務端返回的表單頁面中提交的資料,不然無法進行跨網頁操作
<!--action:要提交到的頁面; method:提交方式-->
<form action="{% url 'add' %}" method="post"> #這個為提交到的頁面和提交方式
<!--<form action="/add/" method="post">-->
總結:
在Django部分,前面搭建的功能基本一樣,新增不同的功能和新增需求都需要在資料庫和views.py中進行修改 並對models進行一定的增加,設好主鍵做好索引,就是解題的關鍵。
印象筆記,讓記憶永存。下載印象筆記 |