首页 > 代码库 > Django工程的建立以及小网站的编写

Django工程的建立以及小网站的编写

  这篇博文会详细的介绍如何创建django工程,介绍我如何做了第一个网站。本文基于windows7安装了python2.7.12,Django1.8.18(LTS)版。采用的IDE为pycharm。建议安装Django的时候采用pip安装,因为可能自己电脑环境缺少哪个包的话,pip能给你安装完全。命令是

1 pip install django==1.8.18

  本文的目的是建立一个小网站,能够在测试过程中随时记录所出现的bug,网站命名为Buglist,根据描述,便知道主要的用途就是和数据库交互,并且是在Linux服务器上部署,所以采用mysql数据库,并且还要记录是谁进行登陆,记录这些bug,所以要用django的后台管理页面。so,创建一个buglist工程吧。技术分享

  让我们看看Django项目的结构:

1 |- buglist/   
2     |- manage.py  
3     |- templates/     
4     |- buglist/
5         |- __init__.py     
6         |- settings.py     
7         |- urls.py     
8         |- 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文件中修改几个地方,数据库

 1 DATABASES = {
 2     default: {
 3         ENGINE: django.db.backends.mysql,
 4         NAME: buglist,
 5         USER:buglist,
 6         PASSWORD:buglist,
 7         HOST:‘‘,                                     ----此处默认即为本地数据库
 8         PORT:‘‘,                                     -----此处默认即为mysql默认端口
 9     }
10 }

     时区及静态文件夹的设置

 1 TIME_ZONE = Asia/Shanghai
 2 
 3 
 4 STATIC_URL = /static/
 5 STATIC_ROOT = os.path.join(BASE_DIR,static)
 6 STATICFILES_DIRS = (static/css,
 7                     static/bootstrap,
 8                     static/images,
 9                     static/js,
10                 )

  创建一个app handle  可以采用tool --> Run manage.py Task 来创建或者采用python manage.py startapp handle来创建,不要忘记在settings.py中添加

1 INSTALLED_APPS = (
2     django.contrib.auth,
3     django.contrib.contenttypes,
4     django.contrib.sessions,
5     django.contrib.messages,
6     django.contrib.staticfiles,
7     handle,
8 )

  首先完成前段部分,login.html,采用POST的方式往后台传输数据,采用了boostrap,简单易用,并且采用了模板语言

 1 <!Doctype html>
 2 {% load staticfiles %}
 3 <html>
 4     <head>
 5         <meta http-equiv=Content-Type content="text/html;charset=utf-8">
 6         <meta name="description" content="BugList">
 7         <link rel="icon" href="{% static "images/favicon.ico" %}" type="image/x-icon"/>
 8         <link rel="stylesheet" href="{% static "login.css" %}" type="text/css"/>
 9         <link rel="stylesheet" href="{% static "css/bootstrap.min.css"%}" type="text/css"/>
10         <title>BugList</title>
11     </head>
12     <body>
13         <div class="container">
14             <div class="row">
15                 <div class="col-sm-6 col-md-4 col-md-offset-4">
16                     <div class="account-wall">
17                         <h1 class="text-center login-title">Sign in to continue</h1>
18                         <form class="form-signin" method="POST" action="/login/">
19                              {% csrf_token %}
20                             <input name="user" type="user" class="form-control" id="user" placeholder="Username" required autofocus>
21                             <input name="password" type="password" class="form-control" id= ‘password‘ placeholder="Password" required>
22                             <button class="btn btn-lg btn-primary btn-block" type="submit" id="">Sign in</button>
23                             <p style="color: red;text-align: center;"> {{ loginstatus }} </p>
24                         </form>
25 
26                     </div>
27                 </div>
28             </div>
29         </div>
30 
31     <script type="text/javascript" src="{% static "jquery-3.2.0.min.js" %}" ></script>
32     <script type="text/javascript" src="{% static "js/bootstrap.min.js" %}"></script>
33     </body>
34 </html>

    web模板,采用模板语言的话就是扩展性比较好,layout.html

 1 <!DOCTYPE html>
 2 {% load staticfiles %}
 3 <html lang="en">
 4     <head>
 5         <meta charset="utf-8">
 6         <meta http-equiv="X-UA-Compatible" content="IE=edge">
 7         <meta name="viewport" content="width=device-width, initial-scale=1">
 8         <meta name="description" content="">
 9         <meta name="author" content="">
10         <link rel="icon" href="{% static "favicon.ico" %} " type="image/x-icon" />
11 
12         <title>BugList</title>
13 
14         <!-- Bootstrap core CSS -->
15         <link href="{% static "css/bootstrap.min.css" %}" rel="stylesheet" type="text/css"/>
16         <!-- Custom styles for this template -->
17         <link href="{% static "dashboard.css" %}" rel="stylesheet" type="text/css"/>
18         <link href="{% static "custom.css" %}" rel="stylesheet" type="text/css"/>
19         {% block css %}
20         {% endblock %}
21     </head>
22 
23     <body>
24 
25         <nav class="navbar navbar-inverse navbar-fixed-top">
26             <div class="container-fluid">
27                 <div class="navbar-header">
28                     <div class="navbar-brand"><a style=‘text-decoration:none;‘ href="/">BugList</a></div>
29                 </div>
30                 <div id="navbar" class="navbar-collapse collapse">
31                     <ul class="nav navbar-nav navbar-right">
32                         <li class="dropdown">
33                             {% if user.is_active %}
34                                 <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>
35                                 <ul class="dropdown-menu">
36                                     <li><a href="/logout/">logout</a></li>
37                                 </ul>
38                             {% endif %}
39                         </li>
40                   </ul>
41                 </div>
42             </div>
43         </nav>
44 
45         <div class="container-fluid">
46             <div class="row">
47                 <div class="col-sm-2 col-md-2 sidebar">
48                     <ul class="nav nav-sidebar" id="bar">
49                         <li ><a href="/overview/">Overview</a></li>
50                         <li ><a href="/search/" >Search Errors</a></li>
51                         <li ><a href="/record/" >Record Errors</a></li>
52                     </ul>
53                 </div>
54                 <div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
55                     {% block con %}
56                     {% endblock %}
57                 </div>
58             </div>
59         </div>
60         <script src="{% static "jquery-3.2.0.min.js" %}"></script>
61         <script src="{% static "js/bootstrap.min.js"%}"></script>
62         <script src="{% static "custom.js" %}"></script>
63     {% block js %}
64     {% endblock %}
65     </body>
66 </html>

  登陆首页,index.html

1 {% extends "web/layout.html" %}
2 {% block con %}
3     <h1>Welcome to BugList Service</h1>
4 {% endblock %}

  概览页面  overview.html

 1 {% extends "web/layout.html" %}
 2 {% block con %}
 3     <h2 class="sub-header">Overviews</h2>
 4     <div class="table-responsive">
 5         <table class="table table-striped">
 6             <thead>
 7                 <tr>
 8                   <th>numbers</th>
 9                   <th>title</th>
10                   <th>auther</th>
11                   <th>time</th>
12                 </tr>
13             </thead>
14             <tbody>
15                 {% for record in context_obj %}
16                     <tr>
17                         <th><a href="/deltails/{{record.id }}">{{ record.id }}</a> </th>
18                         <th>{{ record.title }}</th>
19                         <th>{{ record.auther }}</th>
20                         <th>{{ record.time }}</th>
21                     </tr>
22                 {% endfor %}
23             </tbody>
24 
25 
26         </table>
27     </div>
28 
29 {% endblock %}

 记录页面 record.html

 1 {% extends "web/layout.html" %}
 2 {% load staticfiles %}
 3 
 4 {% block css %}
 5     <link  href="{% static "dcalendar.picker.css" %}" rel="stylesheet"/>
 6 {% endblock %}
 7 
 8 
 9 {% block con %}
10     <h2 class="sub-header">Record</h2>
11     <div class="container" id = "record">
12         <div class="form-group">
13              <label for="time">&nbsp&nbsptitle&nbsp&nbsp</label>
14              <input type="text"  id="title" size="30" name="title"/>
15         </div>
16         <div class="form-group">
17              <label for="details">details</label>
18              <br/>
19              <textarea name="details" cols="100" rows="5" id="details"></textarea>
20         </div>
21         <div class="checkbox">
22              <label><input type="checkbox" />Check me out</label>
23         </div>
24         <button type="submit" class="btn btn-default" id="Submit">Submit</button>
25     </div>
26 
27 
28 {% endblock %}
29 
30 {% block js %}
31     <script type="text/javascript">
32         $(function () {
33             $("#Submit").click(function () {
34                 var myDate = new Date();
35                 var time = myDate.toLocaleDateString().replace(/\//g,"-");
36                 var title = $("#title").val();
37                 var details = $("#details").val();
38                 if ((title && title.trim()) && (details && details.trim())){
39                     data = {title:title,details:details,time:time};
40                     AjaxRequest(/counts/,data,null);
41                     $("#title").val("");
42                     $("#details").val("") ;
43                 }
44             });
45         });
46     </script>
47 {% endblock %}

  详情页面 details.html

 1 {% extends "web/layout.html" %}
 2 {% block con %}
 3     <h2 class="sub-header">Deltails</h2>
 4     <div class="blog-header">
 5         <h1 class="blog-title">{{ record.title }}</h1>
 6         <p class="lead blog-description">&nbsp&nbsp&nbsp&nbsp&nbsp&nbspauther:&nbsp{{ record.auther }}</p>
 7         <p class="lead blog-description">&nbsp&nbsp&nbsp&nbsp&nbsp&nbsptime:&nbsp{{ record.time }}</p>
 8         <p class="lead blog-description">&nbsp&nbspdetails:&nbsp</p>
 9         <hr/>
10         <p>
11             {{ record.details }}
12         </p>
13     </div>
14 
15 {% endblock %}

      搜索页面 search.html

 1 {% extends "web/layout.html" %}
 2 {% load staticfiles %}
 3 {% block css %}
 4     <link rel="stylesheet" href="{% static "dcalendar.picker.css" %}"/>
 5 {% endblock %}
 6 {% block con %}
 7     <h2 class="sub-header">Search</h2>
 8     <div class="container">
 9         <div id="div_to_search">
10             <label for="Auther">Auther</label>
11             <input type="text" name="Auther" id="Auther_to_serach" />
12             <label for="StartTime">StartTime</label>
13             <input  type="text" name="StartTime" id="StartTime" />
14             <label for="EndTime">EndTime</label>
15             <input  type="text" name="EndTime" id="EndTime"/>
16             <label for="Type"> Type</label>
17             <select name="Type" id="Type">
18                 <option value=‘All‘>All</option>
19                 <option value=‘Solved‘>Solved</option>
20                 <option value=‘Unsolved‘>Unsolved</option>
21             </select>
22             <input style="width:60px;cursor:pointer;" type="submit" value=‘Check‘ id="Check"/>
23         </div>
24         <hr/>
25         <div class="table-responsive">
26             <table class="table table-striped">
27                 <thead>
28                     <tr>
29                       <th>numbers</th>
30                       <th>title</th>
31                       <th>auther</th>
32                       <th>time</th>
33                     </tr>
34                 </thead>
35                 <tbody id="tbody">
36                 </tbody>
37 
38 
39             </table>
40         </div>
41     </div>
42 
43 
44 {% endblock %}
45 {% block js %}
46     <script type="text/javascript" src="{% static "dcalendar.picker.js" %}"></script>
47     <script type="text/javascript">
48         $(#StartTime).dcalendarpicker({
49             format:yyyy-mm-dd
50          });
51         $(#EndTime).dcalendarpicker({
52             format:yyyy-mm-dd
53         });
54         function callback(arg) {
55             document.getElementById("tbody").innerHTML = arg;
56         }
57         $(function () {
58             $("#Check").click(function () {
59                 var  data = {};
60                 var count = 0;
61                 $("#div_to_search :text").each(function () {
62                    data[$(this).attr(name)]  = $(this).val();
63                    $(this).val("");
64                 });
65                 //data[‘Type‘]=$("#div_to_search :selected").val();
66                 $.each(data,function (i,item) {
67                     if (!item){
68                         count++;
69                     }
70                 });
71                 if(count>2){
72                     alert(you must input at least one parameters);
73                     return false;
74                 }
75                 var st = data[StartTime];
76                 var et = data[EndTime];
77                 if ( st && et  ){
78                     if (tab(st,et)){
79                         AjaxRequest("/search/",data,callback);
80                     }
81                     else{
82                         alert(the time you input is not correct!);
83                     }
84                 }else{
85                     AjaxRequest("/search/",data,callback);
86                 }
87             });
88         });
89     </script>
90 {% endblock %}

   个人写的js代码 custom.js

 1 /**
 2  * Created by sumoning on 2017/4/17.
 3  */
 4 
 5 function AjaxRequest(url,data,func) {
 6     $.ajax({
 7         type: ‘POST‘,
 8         url: url,
 9         data:data,
10         cache: false,
11         async: true,
12         success: func
13     });
14 }
15 /*
16 $(function () {
17    $("#bar").children().click(function () {
18        $(this).parent().children().removeClass(‘active‘);
19        $(this).addClass(‘active‘);
20    });
21 });*/
22 
23 function tab(date1,date2){
24     var oDate1 = new Date(date1);
25     var oDate2 = new Date(date2);
26     if(oDate1.getTime() > oDate2.getTime()){
27         return false;
28     } else {
29         return true;
30     }
31 }

    表的设计  model.py

 1 #!/usr/bin/env python
 2 #!_*_coding:utf-8_*_
 3 
 4 
 5 from django.db import models
 6 from django.contrib.auth.models import User
 7 
 8 # Create your models here.
 9 
10 
11 class context(models.Model):
12     title = models.CharField(max_length=100)
13     auther = models.CharField(max_length=20)
14     time = models.DateField()
15     details = models.TextField()

   主url设计  buglist/url.py

 1 """buglist URL Configuration
 2 
 3 The `urlpatterns` list routes URLs to views. For more information please see:
 4     https://docs.djangoproject.com/en/1.8/topics/http/urls/
 5 Examples:
 6 Function views
 7     1. Add an import:  from my_app import views
 8     2. Add a URL to urlpatterns:  url(r‘^$‘, views.home, name=‘home‘)
 9 Class-based views
10     1. Add an import:  from other_app.views import Home
11     2. Add a URL to urlpatterns:  url(r‘^$‘, Home.as_view(), name=‘home‘)
12 Including another URLconf
13     1. Add a URL to urlpatterns:  url(r‘^blog/‘, include(‘blog.urls‘))
14 """
15 from django.conf.urls import include, url
16 from handle import urls
17 from django.contrib import admin
18 
19 urlpatterns = [
20     url(r^admin/, include(admin.site.urls)),
21     url(r‘‘,include(urls)),
22 ]

    附属url 设计buglist/handle/url.py

 1 #!/usr/bin/env python
 2 #!_*_coding:utf-8_*_
 3 
 4 from django.conf.urls import  url
 5 import views
 6 
 7 urlpatterns = [
 8     url(r^accounts/login/,django.contrib.auth.views.login,{template_name:login/login.html}),
 9     url(r^login/,views.Login),
10     url(r^logout/,views.Logout),
11     url(r^overview/,views.Overview),
12     url(r^deltails/(\d+),views.Deltails),
13     url(r^record/,views.Record),
14     url(r^counts/,views.Counts),
15     url(r^search/,views.Search),
16     url(r^$,views.Index),
17 ]

    视图设计  buglist/handle/view.py

  1 #/usr/bin/env python
  2 #!_*_coding:utf-8_*_
  3 
  4 
  5 from django.shortcuts import render,render_to_response
  6 from django.http import HttpResponse,HttpResponseRedirect
  7 from django.contrib import auth
  8 from django.contrib.auth.decorators import login_required
  9 from django.template.context import RequestContext
 10 from django.views.decorators.csrf import csrf_exempt
 11 from models import context
 12 import traceback
 13 import datetime
 14 from django.utils import timezone
 15 from django.contrib.auth.models import User
 16 
 17 
 18 # Create your views here.
 19 
 20 
 21 def Login(request):
 22     if request.user.is_authenticated():
 23         return HttpResponseRedirect(/)
 24     data = http://www.mamicode.com/{loginstatus:‘‘,user:‘‘}
 25     if request.method == "POST":
 26         username = request.POST.get(user)
 27         password = request.POST.get(password)
 28         user = auth.authenticate(username=username,password=password)
 29         if user is not None:
 30             auth.login(request,user)
 31             data[user] = user
 32             return HttpResponseRedirect(/)
 33         data[loginstatus] = your username or password id uncorrect!
 34 
 35     return render_to_response(login/login.html,data,context_instance=RequestContext(request))
 36 
 37 def Logout(request):
 38     auth.logout(request)
 39     return render_to_response(login/login.html,context_instance=RequestContext(request))
 40 
 41 
 42 @login_required
 43 def Index(request):
 44     return render_to_response(web/index.html,{user:request.user})
 45 
 46 @login_required
 47 def Overview(request):
 48     context_obj = context.objects.all().order_by(-id)
 49     return render_to_response(web/overview.html,{context_obj:context_obj,user:request.user})
 50 
 51 @login_required
 52 def Deltails(request,id):
 53     record = context.objects.get(id=id)
 54     return render_to_response(web/details.html,{record:record,user:request.user})
 55 
 56 @login_required
 57 def Record(request):
 58     return render_to_response(web/record.html,{user:request.user})
 59 
 60 @login_required
 61 @csrf_exempt
 62 def Counts(request):
 63     title,time,details= request.POST.get(title),request.POST.get(time),request.POST.get(details)
 64     try:
 65         obj = context.objects.create(title=title,time=time,details=details,auther=request.user)
 66         return render_to_response(web/record.html, {user: request.user})
 67     except:
 68         traceback.print_exc()
 69 
 70 @login_required
 71 @csrf_exempt
 72 def Search(request):
 73     if request.method == POST:
 74         datas = {}
 75         str = ""
 76         get_data =http://www.mamicode.com/ request.POST
 77         context_obj = None
 78         for re in get_data:
 79             if get_data.get(re):
 80                 datas[re] = get_data.get(re)
 81         if len(datas.keys()) == 1 :
 82             if Auther in datas.keys():
 83                 try:
 84                     context_obj  = context.objects.filter(auther = datas[Auther]).order_by("-id")
 85                 except:
 86                     traceback.print_exc()
 87             elif StartTime in datas.keys():
 88                 try:
 89                     st = datetime.datetime.strptime(datas[StartTime], "%Y-%m-%d").date()
 90                     no = timezone.localtime(timezone.now()).strftime("%Y-%m-%d")
 91                     et = datetime.datetime.strptime(no,"%Y-%m-%d").date()
 92                     context_obj = context.objects.filter(time__range=(st, et)).order_by("-id")
 93                 except:
 94                     traceback.print_exc()
 95             elif EndTime in datas.keys():
 96                 try:
 97                     st = datetime.datetime.strptime(2017-01-01, "%Y-%m-%d").date()
 98                     et = datetime.datetime.strptime(datas[EndTime],"%Y-%m-%d").date()
 99                     context_obj = context.objects.filter(time__range=(st, et)).order_by("-id")
100                 except:
101                     traceback.print_exc()
102             else:
103                 pass
104         elif len(datas.keys()) == 2:
105             if Auther in datas.keys():
106                 if StartTime in datas.keys():
107                     st = datetime.datetime.strptime(datas[StartTime], "%Y-%m-%d").date()
108                     no = timezone.localtime(timezone.now()).strftime("%Y-%m-%d")
109                     et = datetime.datetime.strptime(no, "%Y-%m-%d").date()
110                     try:
111                         context_obj = context.objects.filter(auther=datas[Auther],time__range=(st, et)).order_by("-id")
112                     except:
113                         traceback.print_exc()
114                 elif EndTime in datas.keys():
115                     try:
116                         st = datetime.datetime.strptime(2017-01-01, "%Y-%m-%d").date()
117                         et = datetime.datetime.strptime(datas[EndTime], "%Y-%m-%d").date()
118                         context_obj = context.objects.filter(auther=datas[Auther],time__range=(st, et)).order_by("-id")
119                     except:
120                         traceback.print_exc()
121                 else:
122                     pass
123             else:
124                 try:
125                     st = datetime.datetime.strptime(datas[StartTime], "%Y-%m-%d").date()
126                     et = datetime.datetime.strptime(datas[EndTime], "%Y-%m-%d").date()
127                     context_obj = context.objects.filter(time__range=(st, et)).order_by("-id")
128                 except:
129                     traceback.print_exc()
130         else:
131             st = datetime.datetime.strptime(datas[StartTime], "%Y-%m-%d").date()
132             et = datetime.datetime.strptime(datas[EndTime], "%Y-%m-%d").date()
133             context_obj = context.objects.filter(auther=datas[Auther],time__range=(st, et)).order_by("-id")
134         for re in context_obj:
135             str += "<tr>"
136             str += "<th><a href=http://www.mamicode.com/‘/deltails/%d‘>%d " % (re.id, re.id)
137             str += "<th>%s</th>" % (re.title)
138             str += "<th>%s</th>" % (re.auther)
139             str += "<th>%s</th>" % (re.time)
140             str += "<tr>"
141         return HttpResponse(str)
142 
143     else:
144         return render_to_response("web/search.html",{user:request.user})

   ok,最后run就可以啦

Django工程的建立以及小网站的编写