django项目实践
第二部分: 程序开发:
创建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进行一定的增加,设好主键做好索引,就是解题的关键。
印象笔记,让记忆永存。下载印象笔记 |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构