基本信息
源码名称:python web编程实例(sqlite增删改查)
源码大小:18.60M
文件格式:.rar
开发语言:Python
更新时间:2020-07-13
友情提示:(无需注册或充值,赞助后即可获取资源下载链接)
嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):813200300
本次赞助数额为: 2 元×
微信扫码支付:2 元
×
请留下您的邮箱,我们将在2小时内将文件发到您的邮箱
源码介绍
web编程,在原有网页上增加内容;增加新网页,可以新建topic 然后再该topic下 发布消息,如下图
运行方式:python manage.py runserver
然后访问 http://localhost:8000/ 即可
from django.shortcuts import render from django.http import HttpResponseRedirect from learningNote.models import Topic, Entry from django.urls import reverse from .forms import TopicForm,EntryForm # Create your views here. def index(request): """ 学习笔记的主页 """ return render(request, 'learningNote/index.html') def topics(request): """ 显示所有的主题 """ topics = Topic.objects.order_by('date_added') context = {'topics': topics} return render(request, 'learningNote/topics.html', context) def topic(request, topic_id): """ 显示单个主题及其所有的条目 """ topic = Topic.objects.get(id=topic_id) entries = topic.entry_set.order_by('-date_added') context = {'topic': topic, 'entries': entries} return render(request, 'learningNote/topic.html', context) # 函数new_topic() 需要处理两种情形: 刚进入new_topic 网页(在这种情况下, 它应显示一个空表单) ; 对提交的表单数据进行处理, 并将用户重定向到网页topics def new_topic(request): """添加新主题""" if request.method != 'POST': # 未提交数据: 创建一个新表单 form = TopicForm() # 如果请求方法不是POST, 请求就可能是GET, 因此我们需要返回一个空表单 else: form = TopicForm(request.POST) if form.is_valid(): # 必须先通过检查确定它们是有效的 form.save() # 表单中的数据写入数据库 # 函数reverse() 根据指定的URL模型确定URL, 这意味着Django将在页面被请求时生成URL。 # 调用HttpResponseRedirect() 将用户重定向到显示新增条目所属主题的页面 return HttpResponseRedirect(reverse('learningNote:topics')) context = {'form': form} return render(request, 'learningNote/new_topic.html', context) def new_entry(request, topic_id): """ 在特定的主题中添加新条目 """ topic = Topic.objects.get(id=topic_id) if request.method != 'POST': # 未提交数据 , 创建一个空表单 form = EntryForm() else: # POST 提交的数据 , 对数据进行处理 form = EntryForm(data=request.POST) if form.is_valid(): new_entry = form.save(commit=False) new_entry.topic = topic new_entry.save() return HttpResponseRedirect(reverse('learningNote:topic', args=[topic_id])) context = {'topic': topic, 'form': form} return render(request, 'learningNote/new_entry.html', context) def edit_entry(request, entry_id): """编辑既有条目""" entry = Entry.objects.get(id=entry_id) topic = entry.topic if request.method != 'POST': # 初次请求, 使用当前条目填充表单 form = EntryForm(instance=entry) else: # POST提交的数据, 对数据进行处理 # 让Django根据既有条目对象创建一个表单实例, 并根据request.POST 中的相关数据对其进行修改 form = EntryForm(instance=entry, data=request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('learningNote:topic', args=[topic.id])) context = {'entry': entry, 'topic': topic, 'form': form} return render(request, 'learningNote/edit_entry.html', context)