mysql迅速搭建网页_Django + mysql 快速搭建简单web投票系统
了解学习pyhton web的简单demo
1. 安装Django, 安装pyhton 自行百度
2. 执行命令创建project django-admin.py startproject mysite
3. 执行命令创建app python manage.py startapp polls
目录结构: polls/templates/polls 目录 和 polls/admin.py 都是自己手动创建的。
4. 编辑setting.py 添加app polls 同时打开admin
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'polls',
# Uncomment the next line to enable the admin:
'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
)
5. 编辑setting.py 添加数据库连接信息
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'polls', # Or path to database file if using sqlite3.
'USER': 'root', # Not used with sqlite3.
'PASSWORD': '123', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
6. 创建Modle模型 :
# coding=utf-8
from django.db import models
# Create your models here.
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __unicode__(self):
return self.question_text
class Choice(models.Model):
question = models.ForeignKey(Question)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __unicode__(self):
return self.choice_text
7. 执行数据库同步 (ORM)自动根据model定义创建表接口 (我这里使用的mysql)
首先创建数据库
create database polls;
然后执行命令:
python manage.py syncdb
8. 检查数据库中表的创建:
use polls
show tables
9. 创建admin.py
# coding=utf-8
from django.contrib import admin
from .models import Question, Choice
# Register your models here.
class ChoiceInline(admin.TabularInline):
model = Choice
extra = 3
class QuestionAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['question_text']}),
('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),
]
inlines = [ChoiceInline]
list_display = ('question_text', 'pub_date')
admin.site.register(Choice)
admin.site.register(Question, QuestionAdmin)
10. 启动应用
python manage.py runserver
11. 编写视图控制层
视图起着承前启后的作用,前是指前端页面,后是指后台数据库。将数据库表中的内容查询出来显示到页面上。
编写polls/views.py文件:
# coding=utf-8
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from .models import Question, Choice
# Create your views here.
# 首页展示所有问题
def index(request):
# latest_question_list2 = Question.objects.order_by('-pub_data')[:2]
latest_question_list = Question.objects.all()
context = {'latest_question_list': latest_question_list}
return render(request, 'polls/index.html', context)
# 查看所有问题
def detail(request, question_id):
question = get_object_or_404(Question, pk=question_id)
return render(request, 'polls/detail.html', {'question': question})
# 查看投票结果
def results(request, question_id):
question = get_object_or_404(Question, pk=question_id)
return render(request, 'polls/results.html', {'question': question})
# 选择投票
def vote(request, question_id):
p = get_object_or_404(Question, pk=question_id)
try:
selected_choice = p.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
# Redisplay the question voting form.
return render(request, 'polls/detail.html', {
'question': p,
'error_message': "You didn't select a choice.",
})
else:
selected_choice.votes += 1
selected_choice.save()
# Always return an HttpResponseRedirect after successfully dealing
# with POST data. This prevents data from being posted twice if a
# user hits the Back button.
return HttpResponseRedirect(reverse('polls:results', args=(p.id,)))
12. 配置视图展示层与逻辑控制层url映射
url是一个请求配置文件,页面中的请求转交给由哪个函数处理,由该文件决定。
首先配置polls/urls.py(该文件需要创建)
from django.conf.urls import url
from . import views
urlpatterns = [
# ex : /polls/
url(r'^$', views.index, name='index'),
# ex : /polls/5/
url(r'^(?P[0-9]+)/$', views.detail, name='detail'),
# ex : /polls/5/results/
url(r'^(?P[0-9]+)/results/$', views.results, name='results'),
# ex : /polls/5/vote
url(r'^(?P[0-9]+)/vote/$', views.vote, name='vote'),
]
接着,编辑mysite/urls.py文件。
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^polls/', include('polls.urls', namespace="polls")),
url(r'^admin/', include(admin.site.urls)),
]
13. 创建视图模板
模板就是前端页面,用来将数据显示到web页面上。
首先创建polls/templates/polls/目录,分别在该目录下创建index.html、detail.html和results.html文件。
index.html
{% if latest_question_list %}
{% for question in latest_question_list %}
{{ question.question_text }}
{% endfor %}
{% else %}
No polls are available.
{% endif %}
detail.html
{{ question.question_text }}
{% if error_message %}
{{ error_message }}
{% endif %}
{% csrf_token %}
{% for choice in question.choice_set.all %}
{{ choice.choice_text }}
{% endfor %}
results.html
{{ question.question_text }}
{% for choice in question.choice_set.all %}
{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}
{% endfor %}
Vote again?
mysql迅速搭建网页_Django + mysql 快速搭建简单web投票系统相关推荐
- 【快速搭建系列】idea快速搭建SSH2框架(struts2+spring5+hibernate5)
[快速搭建系列]idea快速搭建SSH2框架(struts2+spring5+hibernate5) 压了很久的文,都差点忘记了 网上关于SSH的框架教程五花八门的,自己踩了一周多的坑说什么也要搞一个 ...
- python制作查询网页_django+mysql实现网页查询
django+mysql实现网页查询 实现网页查询并返回结果,将查询关键字保存至数据库 环境: vscode 编辑器 python3.8.2 djangoVersion: 2.0 pip list P ...
- 搭建微服务_快速搭建 SpringCloud 微服务开发环境的脚手架
本文作者:HelloGitHub-秦人 本文适合有 SpringBoot 和 SpringCloud 基础知识的人群,跟着本文可使用和快速搭建 SpringCloud 项目. HelloGitHub ...
- android快速搭建界面,怎么样能快速搭建一个Android APP的界面和框架?
繁花如伊 自己从零开始快速搭建Android app架构简单的看下这三个架构模式:MVC:Model-View-Controller,经典模式,很容易理解,主要缺点有两个:View对Model的依赖, ...
- ecology9 后端开发环境搭建_利用Vagrant快速搭建开发环境
Docker大家应该都了解吧,一个非常方便的技术,可以让我们随时随地部署应用.但是部署应用虽然方便了,开发环境的搭建还是那样的,要自己安装一大堆软件.那么有没有类似的工具可以方便我们呢?这就是本文要的 ...
- 从零使用OpenCV快速实现简单车牌识别系统
这篇文章献给所有第一次听说车牌识别ANPR但需要短时间实现的苦逼同学们. 最近的小学期实训做的是一个车牌识别系统,说实话真不知道学校怎么想的,虽然说图像处理也算的上是数字媒体很重要的一块分支了,但咱这 ...
- 快速搭建Android应用后台服务器
一直没单独一个人搭建过后台,之前都是用的云服务后台,跟着帖子一步一步走,最终完美实现后台与移动端的数据沟通,顿时感觉棒棒哒,特此记录一下.很感谢下面帖子的博主得无私分享! 一.后台的搭建 1.自己动手 ...
- 玩转SpringBoot 2 快速搭建 | Spring Initializr 篇
SpringBoot 为我们提供了外网 Spring Initializr 网页版来帮助我们快速搭建 SpringBoot 项目,如果你不想用 IDEA 中的插件,这种方式也是不错的选择.闲话少说,直 ...
- 神经网络快速搭建之一站式访问
快速搭建人工神经网络 一.简单概念综述 1.1.本文涉及内容 1.2.实际问题的抛出 1.3.最为原始的神经网络 二.神经网络的优化以及实际问题模型的优化 2.1.从损失函数来看 2.2.从学习率来看 ...
最新文章
- Tensorflow会话
- C++标准库中sstream和strstream的区别
- 小心!你的脸正在成为色情片主角……
- Shadow of Survival
- Nodejs模块、自定义模块、CommonJs的概念和使用
- iOS开发针对对Masonry下的FPS优化讨论
- java 解压到内存,Java GZip 基于内存实现压缩和解压的方法
- WPF中DatePiker值绑定以及精简查询
- 对话即平台:利用人工智能以及云平台打造你的智能机器人
- ubuntu 用户管理 adduser vs useradd
- python,numpy中np.random.choice()的用法详解及其参考代码
- 如何升级浏览器_涨姿势|教你用手机一键升级路由器软件(固件)
- JavaScript开发者的工具箱
- The type XXX is not API (restriction on required library 'D:\jdk-64\jre\lib\rt.jar')
- chromedriver 下载_解决ChromeDriver安装与配置问题
- 最新尚硅谷Git和GitHub视频教程完整版
- Linux:telnet命令安装
- Flutter小说APP
- ArcGIS学习总结(二)——空间数据处理
- 解决微信大字体下H5布局混乱