Django工程的建立以及小网站的编写
这篇博文会详细的介绍如何创建django工程,介绍我如何做了第一个网站。本文基于windows7安装了python2.7.12,Django1.8.18(LTS)版。采用的IDE为pycharm。建议安装Django的时候采用pip安装,因为可能自己电脑环境缺少哪个包的话,pip能给你安装完全。命令是
pip install django==1.8.
本文的目的是建立一个小网站,能够在测试过程中随时记录所出现的bug,网站命名为Buglist,根据描述,便知道主要的用途就是和数据库交互,并且是在Linux服务器上部署,所以采用mysql数据库,并且还要记录是谁进行登陆,记录这些bug,所以要用django的后台管理页面。so,创建一个buglist工程吧。
让我们看看Django项目的结构:
|- buglist/
|- manage.py
|- templates/
|- buglist/
|- __init__.py
|- settings.py
|- urls.py
|- wsgi.py
manage.py: 一个命令行交互文件,用于显示项目的运行情况,不用对这个文件做任何修改。
- templates/:用来存放静态文件,css,js,ico文件等等
- buglist/: 你项目的目录下包含着以下文件:
- __init__.py : 空的Python文件,用来告诉Python将这个项目目录视为一个Python模块。
- settings.py : 项目的配置和设置文件,用命令行生成的Django项目会自动生成默认配置。
- urls.py : URL配置文件,每一行URL都对应一个相应的视图(view)
- uwsgi.py : 配置您的项目,让它作为一个WSGI程序运行。
在工程中新建文件夹
此时需要在settings.py文件中修改几个地方,数据库
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'buglist',
'USER':'buglist',
'PASSWORD':'buglist',
'HOST':'', ----此处默认即为本地数据库
'PORT':'', -----此处默认即为mysql默认端口
}
}
时区及静态文件夹的设置
TIME_ZONE = 'Asia/Shanghai' STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR,'static')
STATICFILES_DIRS = ('static/css',
'static/bootstrap',
'static/images',
'static/js',
)
创建一个app handle 可以采用tool --> Run manage.py Task 来创建或者采用python manage.py startapp handle来创建,不要忘记在settings.py中添加
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'handle',
)
首先完成前段部分,login.html,采用POST的方式往后台传输数据,采用了boostrap,简单易用,并且采用了模板语言
<!Doctype html>
{% load staticfiles %}
<html>
<head>
<meta http-equiv=Content-Type content="text/html;charset=utf-8">
<meta name="description" content="BugList">
<link rel="icon" href="{% static "images/favicon.ico" %}" type="image/x-icon"/>
<link rel="stylesheet" href="{% static "login.css" %}" type="text/css"/>
<link rel="stylesheet" href="{% static "css/bootstrap.min.css"%}" type="text/css"/>
<title>BugList</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-sm-6 col-md-4 col-md-offset-4">
<div class="account-wall">
<h1 class="text-center login-title">Sign in to continue</h1>
<form class="form-signin" method="POST" action="/login/">
{% csrf_token %}
<input name="user" type="user" class="form-control" id="user" placeholder="Username" required autofocus>
<input name="password" type="password" class="form-control" id= 'password' placeholder="Password" required>
<button class="btn btn-lg btn-primary btn-block" type="submit" id="">Sign in</button>
<p style="color: red;text-align: center;"> {{ loginstatus }} </p>
</form> </div>
</div>
</div>
</div> <script type="text/javascript" src="{% static "jquery-3.2.0.min.js" %}" ></script>
<script type="text/javascript" src="{% static "js/bootstrap.min.js" %}"></script>
</body>
</html>
web模板,采用模板语言的话就是扩展性比较好,layout.html
<!DOCTYPE html>
{% load staticfiles %}
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="{% static "favicon.ico" %} " type="image/x-icon" /> <title>BugList</title> <!-- Bootstrap core CSS -->
<link href="{% static "css/bootstrap.min.css" %}" rel="stylesheet" type="text/css"/>
<!-- Custom styles for this template -->
<link href="{% static "dashboard.css" %}" rel="stylesheet" type="text/css"/>
<link href="{% static "custom.css" %}" rel="stylesheet" type="text/css"/>
{% block css %}
{% endblock %}
</head> <body> <nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container-fluid">
<div class="navbar-header">
<div class="navbar-brand"><a style='text-decoration:none;' href="/">BugList</a></div>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-right">
<li class="dropdown">
{% if user.is_active %}
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false" id="login_user">{{ user.username }}<span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a href="/logout/">logout</a></li>
</ul>
{% endif %}
</li>
</ul>
</div>
</div>
</nav> <div class="container-fluid">
<div class="row">
<div class="col-sm-2 col-md-2 sidebar">
<ul class="nav nav-sidebar" id="bar">
<li ><a href="/overview/">Overview</a></li>
<li ><a href="/search/" >Search Errors</a></li>
<li ><a href="/record/" >Record Errors</a></li>
</ul>
</div>
<div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
{% block con %}
{% endblock %}
</div>
</div>
</div>
<script src="{% static "jquery-3.2.0.min.js" %}"></script>
<script src="{% static "js/bootstrap.min.js"%}"></script>
<script src="{% static "custom.js" %}"></script>
{% block js %}
{% endblock %}
</body>
</html>
登陆首页,index.html
{% extends "web/layout.html" %}
{% block con %}
<h1>Welcome to BugList Service</h1>
{% endblock %}
概览页面 overview.html
{% extends "web/layout.html" %}
{% block con %}
<h2 class="sub-header">Overviews</h2>
<div class="table-responsive">
<table class="table table-striped">
<thead>
<tr>
<th>numbers</th>
<th>title</th>
<th>auther</th>
<th>time</th>
</tr>
</thead>
<tbody>
{% for record in context_obj %}
<tr>
<th><a href="/deltails/{{record.id }}">{{ record.id }}</a> </th>
<th>{{ record.title }}</th>
<th>{{ record.auther }}</th>
<th>{{ record.time }}</th>
</tr>
{% endfor %}
</tbody> </table>
</div> {% endblock %}
记录页面 record.html
{% extends "web/layout.html" %}
{% load staticfiles %} {% block css %}
<link href="{% static "dcalendar.picker.css" %}" rel="stylesheet"/>
{% endblock %} {% block con %}
<h2 class="sub-header">Record</h2>
<div class="container" id = "record">
<div class="form-group">
<label for="time">  title  </label>
<input type="text" id="title" size="30" name="title"/>
</div>
<div class="form-group">
<label for="details">details</label>
<br/>
<textarea name="details" cols="100" rows="5" id="details"></textarea>
</div>
<div class="checkbox">
<label><input type="checkbox" />Check me out</label>
</div>
<button type="submit" class="btn btn-default" id="Submit">Submit</button>
</div> {% endblock %} {% block js %}
<script type="text/javascript">
$(function () {
$("#Submit").click(function () {
var myDate = new Date();
var time = myDate.toLocaleDateString().replace(/\//g,"-");
var title = $("#title").val();
var details = $("#details").val();
if ((title && title.trim()) && (details && details.trim())){
data = {'title':title,'details':details,'time':time};
AjaxRequest('/counts/',data,null);
$("#title").val("");
$("#details").val("") ;
}
});
});
</script>
{% endblock %}
详情页面 details.html
{% extends "web/layout.html" %}
{% block con %}
<h2 class="sub-header">Deltails</h2>
<div class="blog-header">
<h1 class="blog-title">{{ record.title }}</h1>
<p class="lead blog-description">      auther: {{ record.auther }}</p>
<p class="lead blog-description">      time: {{ record.time }}</p>
<p class="lead blog-description">  details: </p>
<hr/>
<p>
{{ record.details }}
</p>
</div> {% endblock %}
搜索页面 search.html
{% extends "web/layout.html" %}
{% load staticfiles %}
{% block css %}
<link rel="stylesheet" href="{% static "dcalendar.picker.css" %}"/>
{% endblock %}
{% block con %}
<h2 class="sub-header">Search</h2>
<div class="container">
<div id="div_to_search">
<label for="Auther">Auther</label>
<input type="text" name="Auther" id="Auther_to_serach" />
<label for="StartTime">StartTime</label>
<input type="text" name="StartTime" id="StartTime" />
<label for="EndTime">EndTime</label>
<input type="text" name="EndTime" id="EndTime"/>
<label for="Type"> Type</label>
<select name="Type" id="Type">
<option value='All'>All</option>
<option value='Solved'>Solved</option>
<option value='Unsolved'>Unsolved</option>
</select>
<input style="width:60px;cursor:pointer;" type="submit" value='Check' id="Check"/>
</div>
<hr/>
<div class="table-responsive">
<table class="table table-striped">
<thead>
<tr>
<th>numbers</th>
<th>title</th>
<th>auther</th>
<th>time</th>
</tr>
</thead>
<tbody id="tbody">
</tbody> </table>
</div>
</div> {% endblock %}
{% block js %}
<script type="text/javascript" src="{% static "dcalendar.picker.js" %}"></script>
<script type="text/javascript">
$('#StartTime').dcalendarpicker({
format:'yyyy-mm-dd'
});
$('#EndTime').dcalendarpicker({
format:'yyyy-mm-dd'
});
function callback(arg) {
document.getElementById("tbody").innerHTML = arg;
}
$(function () {
$("#Check").click(function () {
var data = {};
var count = 0;
$("#div_to_search :text").each(function () {
data[$(this).attr('name')] = $(this).val();
$(this).val("");
});
//data['Type']=$("#div_to_search :selected").val();
$.each(data,function (i,item) {
if (!item){
count++;
}
});
if(count>2){
alert('you must input at least one parameters');
return false;
}
var st = data['StartTime'];
var et = data['EndTime'];
if ( st && et ){
if (tab(st,et)){
AjaxRequest("/search/",data,callback);
}
else{
alert('the time you input is not correct!');
}
}else{
AjaxRequest("/search/",data,callback);
}
});
});
</script>
{% endblock %}
个人写的js代码 custom.js
/**
* Created by sumoning on 2017/4/17.
*/ function AjaxRequest(url,data,func) {
$.ajax({
type: 'POST',
url: url,
data:data,
cache: false,
async: true,
success: func
});
}
/*
$(function () {
$("#bar").children().click(function () {
$(this).parent().children().removeClass('active');
$(this).addClass('active');
});
});*/ function tab(date1,date2){
var oDate1 = new Date(date1);
var oDate2 = new Date(date2);
if(oDate1.getTime() > oDate2.getTime()){
return false;
} else {
return true;
}
}
表的设计 model.py
#!/usr/bin/env python
#!_*_coding:utf-8_*_ from django.db import models
from django.contrib.auth.models import User # Create your models here. class context(models.Model):
title = models.CharField(max_length=100)
auther = models.CharField(max_length=20)
time = models.DateField()
details = models.TextField()
主url设计 buglist/url.py
"""buglist URL Configuration The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import include, url
from handle import urls
17 from django.contrib import admin urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'',include(urls)),
]
附属url 设计buglist/handle/url.py
#!/usr/bin/env python
#!_*_coding:utf-8_*_ from django.conf.urls import url
import views urlpatterns = [
url(r'^accounts/login/','django.contrib.auth.views.login',{'template_name':'login/login.html'}),
url(r'^login/',views.Login),
url(r'^logout/',views.Logout),
url(r'^overview/',views.Overview),
url(r'^deltails/(\d+)',views.Deltails),
url(r'^record/',views.Record),
url(r'^counts/',views.Counts),
url(r'^search/',views.Search),
url(r'^$',views.Index),
]
视图设计 buglist/handle/view.py
#/usr/bin/env python
#!_*_coding:utf-8_*_ from django.shortcuts import render,render_to_response
from django.http import HttpResponse,HttpResponseRedirect
from django.contrib import auth
from django.contrib.auth.decorators import login_required
from django.template.context import RequestContext
from django.views.decorators.csrf import csrf_exempt
from models import context
import traceback
import datetime
from django.utils import timezone
from django.contrib.auth.models import User # Create your views here. def Login(request):
if request.user.is_authenticated():
return HttpResponseRedirect('/')
data = {'loginstatus':'','user':''}
if request.method == "POST":
username = request.POST.get('user')
password = request.POST.get('password')
user = auth.authenticate(username=username,password=password)
if user is not None:
auth.login(request,user)
data['user'] = user
return HttpResponseRedirect('/')
data['loginstatus'] = 'your username or password id uncorrect!' return render_to_response('login/login.html',data,context_instance=RequestContext(request)) def Logout(request):
auth.logout(request)
return render_to_response('login/login.html',context_instance=RequestContext(request)) @login_required
def Index(request):
return render_to_response('web/index.html',{'user':request.user}) @login_required
def Overview(request):
context_obj = context.objects.all().order_by('-id')
return render_to_response('web/overview.html',{'context_obj':context_obj,'user':request.user}) @login_required
def Deltails(request,id):
record = context.objects.get(id=id)
return render_to_response('web/details.html',{'record':record,'user':request.user}) @login_required
def Record(request):
return render_to_response('web/record.html',{'user':request.user}) @login_required
@csrf_exempt
def Counts(request):
title,time,details= request.POST.get('title'),request.POST.get('time'),request.POST.get('details')
try:
obj = context.objects.create(title=title,time=time,details=details,auther=request.user)
return render_to_response('web/record.html', {'user': request.user})
except:
traceback.print_exc() @login_required
@csrf_exempt
def Search(request):
if request.method == 'POST':
datas = {}
str = ""
get_data = request.POST
context_obj = None
for re in get_data:
if get_data.get(re):
datas[re] = get_data.get(re)
if len(datas.keys()) == 1 :
if 'Auther' in datas.keys():
try:
context_obj = context.objects.filter(auther = datas['Auther']).order_by("-id")
except:
traceback.print_exc()
elif 'StartTime' in datas.keys():
try:
st = datetime.datetime.strptime(datas['StartTime'], "%Y-%m-%d").date()
no = timezone.localtime(timezone.now()).strftime("%Y-%m-%d")
et = datetime.datetime.strptime(no,"%Y-%m-%d").date()
context_obj = context.objects.filter(time__range=(st, et)).order_by("-id")
except:
traceback.print_exc()
elif 'EndTime' in datas.keys():
try:
st = datetime.datetime.strptime('2017-01-01', "%Y-%m-%d").date()
et = datetime.datetime.strptime(datas['EndTime'],"%Y-%m-%d").date()
context_obj = context.objects.filter(time__range=(st, et)).order_by("-id")
except:
traceback.print_exc()
else:
pass
elif len(datas.keys()) == 2:
if 'Auther' in datas.keys():
if 'StartTime' in datas.keys():
st = datetime.datetime.strptime(datas['StartTime'], "%Y-%m-%d").date()
no = timezone.localtime(timezone.now()).strftime("%Y-%m-%d")
et = datetime.datetime.strptime(no, "%Y-%m-%d").date()
try:
context_obj = context.objects.filter(auther=datas['Auther'],time__range=(st, et)).order_by("-id")
except:
traceback.print_exc()
elif 'EndTime' in datas.keys():
try:
st = datetime.datetime.strptime('2017-01-01', "%Y-%m-%d").date()
et = datetime.datetime.strptime(datas['EndTime'], "%Y-%m-%d").date()
context_obj = context.objects.filter(auther=datas['Auther'],time__range=(st, et)).order_by("-id")
except:
traceback.print_exc()
else:
pass
else:
try:
st = datetime.datetime.strptime(datas['StartTime'], "%Y-%m-%d").date()
et = datetime.datetime.strptime(datas['EndTime'], "%Y-%m-%d").date()
context_obj = context.objects.filter(time__range=(st, et)).order_by("-id")
except:
traceback.print_exc()
else:
st = datetime.datetime.strptime(datas['StartTime'], "%Y-%m-%d").date()
et = datetime.datetime.strptime(datas['EndTime'], "%Y-%m-%d").date()
context_obj = context.objects.filter(auther=datas['Auther'],time__range=(st, et)).order_by("-id")
for re in context_obj:
str += "<tr>"
str += "<th><a href='/deltails/%d'>%d</a> </th>" % (re.id, re.id)
str += "<th>%s</th>" % (re.title)
str += "<th>%s</th>" % (re.auther)
str += "<th>%s</th>" % (re.time)
str += "<tr>"
return HttpResponse(str) else:
return render_to_response("web/search.html",{'user':request.user})
ok,最后run就可以啦
Django工程的建立以及小网站的编写的更多相关文章
- 最近用django做了个在线数据分析小网站
用最近做的理赔申请人测试数据集做了个在线分析小网站. 数据结构,算法等设置都保存在json文件里.将来对这个小破站扩充算法,只修改一下json文件就行. 当然,结果分析还是要加代码的.页面代码不贴了, ...
- pycharm建立第一个django工程-----windows中
pycharm建立第一个django工程 系统:win764 ip: 192.168.0.100 安装django pip install django 左上角建立一个名为Firstdjango工程 ...
- 建立第一个Django工程---linux中的python
建立第一个Django工程 环境: ip: 192.168.0.92 系统:centos7.5 安装django pip install django 启动一个HelloWorld工程 django- ...
- pycharm建立django工程
1.windows上安装了python 用pycharm建立django工程,必须要连接本地的python,也就是windows上的pyhton,不能连接linux上的pyhton,否则报错:plea ...
- django学习笔记——搭建博客网站
1. 配置环境,创建django工程 虚拟环境下建立Django工程,即创建一个包含python脚本文件和django配置文件的目录或者文件夹,其中manage.py是django的工程管理助手.(可 ...
- django从0到1搭建网站
曾经有人说我前端很水,那么在这一系列文章中我打算把前后端融合在一起来做一次网站的全面重构,希望可以把刚刚入行的同学带上正途 请尊重原创,转载请注明来源网站www.shareditor.com以及原 ...
- Python分布式爬虫打造搜索引擎完整版-基于Scrapy、Redis、elasticsearch和django打造一个完整的搜索引擎网站
Python分布式爬虫打造搜索引擎 基于Scrapy.Redis.elasticsearch和django打造一个完整的搜索引擎网站 https://github.com/mtianyan/Artic ...
- 0002 Django工程创建
1 创建一个目录,用于专门存放Django工程的虚拟环境 PyCharm默认虚拟环境在工程内,从而导致打包的时候,会把虚拟环境一起打包. 同时,虚拟环境中的插件较多,一个工程创建了一个虚拟环境,以后, ...
- 【踩坑经历】一次Asp.NET小网站部署踩坑和解决经历
2013年给1个大学的小客户部署过一个小型的Asp.NET网站,非常小,用的sqlite数据库,今年人家说要换台服务器,要重新部署一下,好吧,虽然早就过了服务时间,但无奈谁叫人家是客户了,二话不说,上 ...
随机推荐
- Apache JMeter的基本使用
安装 安装地址:http://jmeter.apache.org/download_jmeter.cgi 解压后运行jmeter.bat的批处理文件就可以了 JMeter测试脚本编写: 1,创建线程组 ...
- 【xsy2815】净空 大暴力
绝了场上居然没做这一题 题目大意:给你一个数$x=\Pi_{i=1}^{n}a_i!$. 你需要将x表示为$x=\Pi_{i=1}^{m}(c_i!)^{d_i}p$ 满足$p$无法再分解,且$(c_ ...
- redis常用命令(二)
一.集合(set) 单值多value,vaue不能重复 sadd/smembers/sismember 添加数据/获取set所有数据/判断是否存在某个值 scard 获取集合里面的元素个数 srem ...
- 02-04:springboot 访问静态资源
1.SpringBoot从classpath/static的目录下:(目录名称必须叫static,可以理解为根目录为static) 2.servletContext根目录下,进行查找: 在src/ma ...
- node爬虫gbk中文乱码问题
刚入坑node 写第二个node爬虫时,遇到了这个坑,记录一下. 主要步骤: 1.安装iconv-lite 输入npm install iconv-lite 2.将接收到的网页源码以二进制的方式存储下 ...
- Java NIO系列教程(七) FileChannel
Java NIO中的FileChannel是一个连接到文件的通道.可以通过文件通道读写文件. FileChannel无法设置为非阻塞模式,它总是运行在阻塞模式下. 打开FileChannel 在使用F ...
- redis cluster集群管理工具redis-trib.rb命令小结-运维笔记
redis-trib.rb是redis官方推出的管理redis集群的工具,集成在redis的源码src目录下,是基于redis提供的集群命令封装成简单.便捷.实用的操作工具.redis-trib.rb ...
- Maven Jetty9
<plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactI ...
- PHP初级程序员出路
分销系统 微信公众号开发 分销系统 微信小程序
- Http请求帮助类
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net ...