Django

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Django相关的知识,希望对你有一定的参考价值。

django做个电影网站:
 
①E盘下建个movie文件夹→PyCharm新建项目选Django→location改为E:\movie→More Settings的Application写个dy;
 
(注:PyCharm新建好django项目后,启动项目是在settings.py等界面,按绿方块dj+根目录如movie右侧的绿三角,而非我所自定义并习惯了的F5键Run context configuration)
**************************分割线**************************
②项目文件夹movie:
***************分割线***************
配置文件settings.py:
 
DEBUG = True在部署到Linux服务器之前要改为False。INSTALLED_APPS尾已自动添加了dy…,不理会;若新建应用,则模仿dy…添加。
LANGUAGE_CODE = ‘zh-hans‘
TIME_ZONE = ‘Asia/Shanghai‘
 
DATABASES = {
    ‘default‘: {
        ‘ENGINE‘: ‘django.db.backends.mysql‘,
        #以下四项,和软件Navicat for MySQL的连接界面一样
        ‘HOST‘: ‘mysql.litianqiang.com‘,  # 潭州的远程mysql
        ‘PORT‘: ‘7150‘,  # mysql的默认端口3306;端口值在django中是str,MySQLdb中是int
        ‘USER‘: ‘movie‘,
        ‘PASSWORD‘: ‘……()‘,    #隐藏……处,用的院长的绰号
        ‘NAME‘: ‘movie‘,    #潭州学院那个目标数据库的名字
    }
}
***************分割线***************
路由文件(各正则网址)urls.py:
 
from django.conf.urls import url
from django.contrib import admin
from dy import views
 
urlpatterns = [
    url(r‘^admin/‘, admin.site.urls),
    url(r‘^chengy/‘, views.chengy),
    url(r‘^$‘, views.index),    #首页写为^$,而非^/;url函数的二参是函数体,不是带()的返回值
]
**************************分割线**************************
③应用文件夹dy:
***************分割线***************
让Python和数据库交互(俗称ORM)的文件models.py:
 
在E:\movie路径下进入cmd:python manage.py inspectdb > dy/models.py
回车后,settings.py中所配置的数据库movie中的各表,会以class的形式(首字母大写,去除表名中的_),自动写入models.py
***************分割线***************
各路由网址呈现什么内容的文件views.py:
 
from django.shortcuts import render
from django.http import HttpResponse    #网页显示字符串,太简陋,一般不用它
from dy.models import DyDymodels    #导入movie库中电影数据源所在的那张表
 
def chengy(request):
    return HttpResponse(‘hello,chengy‘)
 
def index(request):
    # dydymodels=DyDymodels.objects.get(id=1) #get()取一行记录,filter()取多行
    dydymodels=DyDymodels.objects.all()[:50]    #提取所有记录,展现前50行
    context={‘movies‘:dydymodels}
    return render(request,‘index.html‘,context=context)
***************分割线***************
应用文件夹dy下新建个templates文件夹,其内新建个index.html:
 
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>电影下载-首页</title>
</head>
<body>
{% for movie in movies %}
<li><a href="{{ movie.link }}">{{ movie.title }}</a></li>
{% endfor %}
</body>
</html>
****************************************分割线****************************************
开发网盘:
 
①E盘下建个wangpan文件夹→……Application写个disk;
***************分割线***************
②项目文件夹wangpan:
 
__init__.py:
import pymysql
pymysql.install_as_MySQLdb()
 
settings.py:
DATABASES = {
    ‘default‘: {
        ‘ENGINE‘: ‘django.db.backends.mysql‘,
        ‘HOST‘:‘localhost‘,‘PORT‘:‘3306‘,‘USER‘:‘chengy‘,‘PASSWORD‘:‘‘,
        ‘NAME‘: ‘网盘‘
    }
}
 
urls.py:
from django.conf.urls import url
from django.contrib import admin
from disk import views
urlpatterns = [
    url(r‘^admin/‘, admin.site.urls),
    url(r‘^$‘, views.index),
    url(r‘^upload/$‘, views.upload),
    url(r‘^s/(\w{32})/$‘, views.content),   #网址中的(),是content函数的二参等
    url(r‘^file/.*?$‘, views.download),
]
***************分割线***************
③应用文件夹disk:
 
models.py:
from django.db import models
class FileInfo(models.Model):
    # id=models.AutoField(primary_key=True)   #默认创建主键自增字段id
    user=models.CharField(max_length=20,null=False)
    fileName=models.CharField(max_length=30,null=False)
    fileSize=models.IntegerField(null=False)
    fileMd5=models.CharField(max_length=32,null=False)
 
在E:\wangpan进入cmd,依次执行如下两句,用models.py的各类,生成mysql的网盘库的各表:
python manage.py makemigrations
python manage.py migrate
******分割线******
views.py:
from django.shortcuts import render
from django.http import HttpResponse,HttpResponseRedirect
import hashlib
from disk.models import FileInfo
 
def index(request):
    return render(request,‘index.html‘)
 
def upload(request):
    #在用户电脑上读取文件并计算MD5值,而非上传到网盘服务器后才计算
    myFile=request.FILES.get(‘upfile‘)
    if not myFile:  #print(myFile)
        return HttpResponse(‘没上传文件‘)
    file=myFile.read()
    if not file:
        return HttpResponse(‘不能上传空文件‘)
    fileName=myFile.name
    fileSize=myFile.size
    fileMd5=hashlib.md5(file).hexdigest()
    existed=FileInfo.objects.filter(fileMd5=fileMd5)
    if existed:
        FileInfo(fileName=fileName, fileSize=fileSize, fileMd5=fileMd5).save()
        # return HttpResponse(‘文件成功秒传‘)   #AttributeError ‘tuple‘  no attribute ‘get‘
        return HttpResponseRedirect(‘/s/{}‘.format(fileMd5))    #s前有/
    with open(‘file/{}‘.format(fileMd5),‘wb‘) as f: #新建的文件夹file和manage.py同级,前无/
        f.write(file)
    FileInfo(fileName=fileName, fileSize=fileSize, fileMd5=fileMd5).save()
    # return HttpResponse(‘文件上传完成‘)
    return HttpResponseRedirect(‘/s/{}‘.format(fileMd5))
 
def content(request,fileMd5):
    fileInfo=FileInfo.objects.filter(fileMd5=fileMd5)   #类似正则的findall,提取某行记录要加[0]
    if not fileInfo:
        return HttpResponse(‘该文件不存在或已被删除‘)
    context={
        ‘fileName‘:fileInfo[0].fileName,
        ‘fileSize‘:fileInfo[0].fileSize,
        ‘fileUrl‘:‘/file/{}‘.format(fileInfo[0].fileName)}  #下载时默认的文件名取末/后的字串
    return render(request,‘content.html‘,context=context)
 
def download(request):
    referer=request.META.get(‘HTTP_REFERER‘)    #获取来路,只在部署到Linux前用
    if not referer:
        return HttpResponse(‘该文件不存在或已被删除‘)  #防止复制下载网址来直接下载
    fileMd5=referer[-33:-1]
    fileInfo=FileInfo.objects.filter(fileMd5=fileMd5)
    if not fileInfo:
        return HttpResponse(‘该文件不存在或已被删除‘)
    file=open(‘file/{}‘.format(fileMd5),‘rb‘).read()
    response=HttpResponse(file) #HttpResponse的一个最大用处:下载流数据
    response["Content-type"]="application/octet-stream"
    return response
***************分割线***************
④index.html:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>文件上传</title>
</head>
<body>
<form action="/upload/" method="post" enctype="multipart/form-data">
    {% csrf_token %}    <!--跨域攻击-->
    <input type="file" name="upfile">
    <input type="submit" value="上传">
</form>
</body>
</html>
 
content.html:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>文件下载</title>
</head>
<body>
<li>文件名:{{ fileName }}</li>
<br>    <!--换行符-->
<li>文件大小:{{ fileSize }}</li>
<br>
<li><a href="{{ fileUrl }}">点击下载</a></li>
</body>
</html>
****************************************分割线****************************************
小说网站:
 
①E盘下建个novel文件夹→……Application写个xs;
***************分割线***************
②settings.py:
DATABASES = {
    ‘default‘: {
        ‘ENGINE‘: ‘django.db.backends.mysql‘,
        ‘HOST‘: ‘mysql.litianqiang.com‘,
        ‘PORT‘: ‘7150‘,
        ‘USER‘: ‘novel‘,
        ‘PASSWORD‘: ‘……()‘,    #隐藏……处,用的院长的绰号
        ‘NAME‘: ‘novel‘,
    }
}
 
urls.py:
from django.conf.urls import url
from django.contrib import admin
from xs import views
urlpatterns = [
    url(r‘^admin/‘, admin.site.urls),
    url(r‘^$‘, views.index),
]
***************分割线***************
③models.py:
在E:\novel路径下进入cmd:python manage.py inspectdb > xs/models.py
 
views.py:
from django.shortcuts import render
from xs.models import NovelCopy
def index(request):
    novelsHot=NovelCopy.objects.filter().order_by(‘?‘)[:4]  #用?表示随机排序
    novelsXH=NovelCopy.objects.filter(sort=‘玄幻‘).order_by(‘?‘)[:4]
    novelsWX=NovelCopy.objects.filter(sort=‘武侠‘).order_by(‘?‘)[:5]
    context = {‘novelsHot‘:novelsHot,‘novelsXH‘:novelsXH,‘novelsWX‘:novelsWX}
    return render(request,‘index.html‘,context=context)
***************分割线***************
④index.html:
 
{% load static %}   <!--若static文件夹及settings.py末尾均改了名,在html中只需修改这一处-->
 
<!doctype html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="Keywords" content="" />
    <meta name="description" content="" />
    <title>Python探索馆 - Slice</title>
    <link rel="stylesheet" href="{% static ‘css/style.css‘ %}" />   <!-- Main Theme -->
    <!-- Font -->
    <link rel="stylesheet" href="http://at.alicdn.com/t/font_n5vylbuqe61or.css" />
  </head>
 
<body>
<!--===== Full Screen BG =====-->
<div class="full-pic"></div>
 
<!--===== Begin Header =====-->
<header class="header">
  <div class="fixed-head" style="position: fixed; width: 100%; -webkit-transform: translateZ(0);">
    <div class="wrap1000 head-wrap">
      <div class="logo"><a href="detail.html">Python学院图书馆</a></div>
      <div class="nav">
        <ul class="nav-list">
          <li><a href="detail.html"><span>首页</span></a></li>
          <li><a href="detail.html"><span>玄幻</span></a></li>
          <li><a href="detail.html"><span>修仙</span></a></li>
          <li><a href="detail.html"><span>都市</span></a></li>
          <li><a href="detail.html"><span>文学</span></a></li>
        </ul>
      </div>
 
      <div class="search">
        <form action="search.html" method="get" target="_blank">
          <input name="kw" placeholder="搜索书名" class="search-inp" type="text" maxlength="10" />
          <input id="search-submit-btn" type="submit" style="display: none;" />
          <label for="search-submit-btn"><i class="iconfont icon-search"></i></label>
        </form>
      </div>
    </div>
  </div>
</header>
 
<!--===== Begin Main =====-->
<section class="main">
  <div class="main-wrap wrap1000">
    <div class="hot-section">
 
      <div class="hot-shadow">
        <div class="hot-title">最热</div>
      </div>
 
      <div class="hot-content">
 
        <!-- 1、banner -->
        <div class="banner">
          <ul class="banner-imgs">
            <li>
              <a href="detail.html"><img src="{% static ‘img/1.jpg‘ %}" width="750" height="300" /></a>
            </li>
            <li>
              <a href="detail.html"><img src="{% static ‘img/2.jpg‘ %}" width="750" height="300" /></a>
            </li>
            <li>
              <a href="detail.html"><img src="{% static ‘img/3.jpg‘ %}" width="750" height="300" /></a>
            </li>
          </ul>
          <div class="control-page">
            <a class="iconfont icon-bannerzuo" href="javascript: void(0);"></a>
            <a class="iconfont icon-banneryou" href="javascript: void(0);"></a>
          </div>
        </div>
 
        <!-- 2、hot -->
        <div class="hot-recommend">
          <ul class="hot-list">
            {% for novel in novelsHot %}
            <li>
              <a href="detail.html">
                <div>
                  <img src="{{ novel.novelimg }}" width="" /><span></span>
                </div>
                <p>
                  <b>{{ novel.novelname }}</b>
                  <span class="author">{{ novel.author }} 著</span>
                  <span class="book-description">
                    {{ novel.description|safe }}    <!--把空格、换行等标点符号转为正常字符-->
                  </span>
                </p>
              </a>
            </li>
            {% endfor %}
          </ul>
        </div>
 
        <!-- 3、Xuanhuan -->
        <div class="xuanhuan">
          <div class="xuanhuan-title">
            <span>玄幻</span>
            <p class="txt">Fantasy</p>
            <p>Novel</p>
            <span class="more"><a href="more.html">更多>></a></span>
          </div>
          <div class="wrap890 xuanhuan-wrap">
            <ul class="book-list">
            {% for novel in novelsXH %}
                <li class="book">
                <div class="book-wrap">
                  <a class="cover" href="detail.html"><img src="{{ novel.novelimg }}" width="136" height="180" /></a>
                  <div class="book-presentation">
                    <h2><a href="detail.html">{{ novel.novelname }}</a></h2>
                    <p class="book-info">
                      <i></i>
                      <span>{{ novel.sort }}</span>
                      <span class="info-txt">{{ novel.state }}</span>
                      <span>314.14万字</span>
                    </p>
                    <p class="book-author">
                      <a href="javascript: void(0);">作者:
                        <span>{{ novel.author }}</span>
                      </a>
                    </p>
                    <p class="desc">
                      {{ novel.description|safe }}
                    </p>
                  </div>
                </div>
              </li>
            {% endfor %}
            </ul>
          </div>
        </div>
 
        <!-- 4、WuXia -->
        <div class="xuanhuan">
          <div class="xuanhuan-title">
            <span>武侠</span>
            <p class="txt">Ganghood</p>
            <p>Novel</p>
            <span class="more"><a href="more.html">更多>></a></span>
          </div>
          <div class="wrap890 xuanhuan-wrap">
            <ul class="book-list">  <!--照抄上文的玄幻遍历-->
              {% for novel in novelsWX ... %}
            </ul>
          </div>
        </div>
      </div>
    </div>
  </div>
</section>
 
<!--===== Begin Footer =====-->
<footer class="footer">
  <div class="wrap1000 footer-wrap">
    <div class="logo-footer">
      <a href="detail.html">
        <img src="{% static ‘img/footer_logo.png‘ %}" width="50" height="50" />
        <span class="footer-txt">潭州教育Python学院</span>
      </a>
      <span class="footer-font">
        TAN ZHOU PYTHON COLLEGE
      </span>
    </div>
    <div class="copy-right">
      <p>
        本站小说均来源互联网,仅供技术学习,请尊重原创作者切勿用商业用途,请下载后24小时内删除。
      </p>
      <p class="">
        Copyright ? 2017 All Rights Reserved 潭州教育网络科技有限公司PYTHON学院
      </p>
    </div>
  </div>
</footer>
 
<!-- Main Plugin -->
<script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script>
<script src="{% static ‘js/index.js‘ %}"></script>
 
</body>
</html>

以上是关于Django的主要内容,如果未能解决你的问题,请参考以下文章

DjangoDjango 文件下载最佳实践

DjangoDjango模块创建应用程序

DjangoDjango 如何支持 分组查询统计?

DjangoDjango Debug Toolbar调试工具配置

DjangoDjango中的模糊查询以及Q对象的简单使用

djangodjango-redis的使用方法