Python实现简单的淘宝网——Django框架

项目演示:

Django实现简易淘宝网站

一、安装Django

在之前的博客中有相关文章,介绍了Django项目的搭建,今天在这里来给大家分享一下,之前课程设计做的一个由Django实现的简单淘宝网站。
Django的入门开发教程——搭建第一个项目(Windows系统)

二、目录介绍

taobao/
├── manage.py  # 管理文件
└── taobao  # 项目目录
    ├── __init__.py
    ├── settings.py  # 配置
    ├── urls.py  # 路由 --> URL和函数的对应关系
    └── wsgi.py  # runserver命令就使用wsgiref模块做简单的web server

三、运行Django项目

cd taobao切换进入Django项目路径,然后执行以下命令:
python manage.py runserver

四、Setting配置文件

  1. 模板文件配置
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR + '/templates/'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]
  1. 静态文件配置
STATIC_URL = '/templates/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "templates"),
]

五、创建的App

一个Django项目可以分为很多个APP,用来隔离不同功能模块的代码。
控制台切换路径到当前Django项目下,直接使用以下命令创建:
python manage.py startapp cart:创建购物车
python manage.py startapp items:创建商品类目
python manage.py startapp pay:创建支付
python manage.py startapp user:创建用户

创建App的应用如下:
在这里插入图片描述
创建出来的app还需要到setting.py注册才能用

INSTALLED_APPS = [
    'django.contrib.admin',#这是一个管理站点,管理后台应用
    'django.contrib.auth',#这是一个权限框架。
    'django.contrib.contenttypes',#这是一个内容类型的框架
    'django.contrib.sessions',#这是一个会话(session)框架。
    'django.contrib.messages',#这是一个消息框架。
    'django.contrib.staticfiles',#这是一个用来管理静态文件的框架
    'items.apps.ItemsConfig',
    'user.apps.UsersConfig',
]

重定向:
重定向

六、简单淘宝网的前端

1. 购物车

<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" type="text/css" href="/templates/style.css">
  <title>王菜鸟的淘宝网--我的购物车</title>
</head>

<body class='relative cart-list'>
  {% if list %}
  <div class='item-list'>
    {% for l in list %}
    <div class='item-container'>
      <img class='items' src={{l.image}} />
      <div class="inline-block item-desc">
        {{ l.price }}
        {% if l.postal %}
        包邮
        {% endif %}
        {{ l.title | safe}}
        {{ l.shopNick }}
        {{ l.payNum }}
      </div>
      <div class='option'>
        <div class='count inline-block'>
          数量 {{l.count}}
        </div>
      </div>
    </div>
    {% endfor %}
    <form action="{%url 'pay:success' %}" method="POST">
      {% csrf_token %}
      <button class="to-pay">去结算</button>
    </form>

  </div>
  {% else %}
  <p>亲,您的购物车是空的呢!请去添加商品到购物车吧~</p>
  <a href="{%url 'items:index' %}">点击此处返回首页</a>
  {% endif %}
</body>

</html>

2. 商品页

<html lang="en">
  <head>
    <meta charset="utf -8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>王菜鸟的淘宝网</title>

    <style>
      form {
        display: inline;
      }

      .add-to-cart {
        color: #fff;
        border-color: #f40;
        background: #f40;
        cursor: pointer;
        width: 100px;
        height: 22px;
        text-align: center;
        font-family: 'Hiragino Sans GB', 'microsoft yahei', sans-serif;
        font-size: 10px;
        border-width: 1px;
        border-style: solid;
        -moz-border-radius: 2px;
        -webkit-border-radius: 2px;
        border-radius: 2px;
      }

      .to-pay {
        position: absolute;
        bottom: 10px;
        right: 50%;
        color: #fff;
        border-color: #f40;
        background: #f40;
        cursor: pointer;
        width: 100px;
        height: 35px;
        text-align: center;
        font-family: 'Hiragino Sans GB', 'microsoft yahei', sans-serif;
        font-size: 20px;
        line-height: 35px;
        border-width: 1px;
        border-style: solid;
        -moz-border-radius: 2px;
        -webkit-border-radius: 2px;
        border-radius: 2px;
      }

      .relative {
        position: relative;
      }
      .hidden {
        display: none;
      }

      .inline-block {
        display: inline-block;
      }
      .item-list .item-container {
        vertical-align: top;
        display: inline-block;
        width: 18%;
        border: 1px solid #eee;
        background: #fff;
        padding: 5px;
        height: 335px;
        position: relative;
        margin-bottom: 15px;
      }

      .item-list .item-desc {
        width: 100%;
        font-size: 15px;
        text-align: justify;
      }

      .item-list .items {
        height: 240px;
        width: 100%;
      }

      .item-list .option {
        position: absolute;
        bottom: 2px;
      }

      .cart-list {
        padding-bottom: 80px;
      }

      .nav {
        margin-bottom: 10px;
      }

      .nav .go-to-cart {
        display: block;
        color: #fff;
        border-color: #f40;
        background: #f40;
        cursor: pointer;
        width: 60px;
        height: 22px;
        line-height: 22px;
        text-align: center;
        font-family: 'Hiragino Sans GB', 'microsoft yahei', sans-serif;
        font-size: 10px;
        border-width: 1px;
        border-style: solid;
        -moz-border-radius: 2px;
        -webkit-border-radius: 2px;
        border-radius: 2px;
      }
    </style>
  </head>
{% load static %}
  <body>
    <div class="nav"> 
        <img src="{% static "banner.jpg" %}">
          <h3 style="text-align:center;">亲,欢迎您来到天猫购物哟,快来看看有没有喜欢的加入购物车吧。</h3>
          
    </div>
    <div class="nav">
        {% if request.sessions.user %}
            欢迎你{{ request.session.user }}
        {% else %}
            <a href="{%url 'user:register'%}">注册</a>
            <a href="{%url 'user:login'%}">登录</a>
            <a href="https://www.taobao.com/" target="_blank">点击此处访问淘宝官网!</a>
        {% endif %}
        <a class="go-to-cart" href="{%url 'cart:list'%}">去购物车</a>
    </div>

    {% if list %}
    <div class="item-list">
      {% for l in list %}
      <div class="item-container">
        <img class="items" src="{{l.image}}" />
        <div class="inline-block item-desc">
          {{ l.price }} {% if l.postal %} 包邮 {% endif %} {{ l.title | safe}}
          {{ l.shopNick }} {{ l.payNum }}
        </div>
        <div class="option">
          <div class="count inline-block">
            库存 {{l.count}}
          </div>
          <form action="{%url 'cart:add-to-cart' l.id%}" method="POST">
            {% csrf_token %}
            <input class="hidden" />
            <button
              class="add-to-cart"
              onclick="window.alert('添加成功')"
              type="submit"
            >
              加入购物车
            </button>
          </form>
        </div>
      </div>
      {% endfor %}
    </div>
    {% else %}
    <p>亲,您的购物车是空的呢!请去添加商品到购物车吧~</p>
    {% endif %}

      <h3 style="text-align:center;">技术支持:王菜鸟</h3>
      <h5 style="text-align:center;">Powered by The king of rookies!</h5>
      <h6 style="text-align:center;">[email protected]</h6>

  </body>
</html>

3. 支付页面

<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>购物车结算</title>
</head>

<body>
  <div>
    支付成功!亲,欢迎下次光临呢~
    <a href="{%url 'items:index' %}">点击此处返回首页</a>
  </div>
</body>

</html>
form {
  display: inline;
}

.add-to-cart {
  color: #FFF;
  border-color: #F40;
  background: #F40;
  cursor: pointer;
  width: 100px;
  height: 22px;
  text-align: center;
  font-family: "Hiragino Sans GB", "microsoft yahei", sans-serif;
  font-size: 10px;
  border-width: 1px;
  border-style: solid;
  -moz-border-radius: 2px;
  -webkit-border-radius: 2px;
  border-radius: 2px;
}

.to-pay {
  position: absolute;
  bottom: 10px;
  right: 50%;;
  color: #FFF;
  border-color: #F40;
  background: #F40;
  cursor: pointer;
  width: 100px;
  height: 35px;
  text-align: center;
  font-family: "Hiragino Sans GB", "microsoft yahei", sans-serif;
  font-size: 20px;
  line-height: 35px;
  border-width: 1px;
  border-style: solid;
  -moz-border-radius: 2px;
  -webkit-border-radius: 2px;
  border-radius: 2px;
}


.relative {
  position: relative;
}
.hidden {
  display: none
}

.inline-block {
  display: inline-block;
}
.item-list .item-container {
  vertical-align: top;
  display: inline-block;
  width: 18%;
  border: 1px solid #eee;
  background: #fff;
  padding: 5px;
  height: 335px;
  position: relative;
  margin-bottom: 15px;
}

.item-list  .item-desc {
  width: 100%;
  font-size: 15px;
  text-align: justify;
}

.item-list .items {
  width: 100%;
}

.item-list .option {
  position: absolute;
  bottom: 2px;
}

.cart-list {
  padding-bottom: 80px; 
}

.nav {
  margin-bottom: 10px;
}

.nav .go-to-cart {
  display: inline-block;
  color: #FFF;
  border-color: #F40;
  background: #F40;
  cursor: pointer;
  width: 60px;
  height: 22px;
  line-height: 22px;
  text-align: center;
  font-family: "Hiragino Sans GB", "microsoft yahei", sans-serif;
  font-size: 10px;
  border-width: 1px;
  border-style: solid;
  -moz-border-radius: 2px;
  -webkit-border-radius: 2px;
  border-radius: 2px;
}

.nav .go-to-login {
  display: inline-block;
  margin-left: 5px;
  color: #FFF;
  border-color: #F40;
  background: #F40;
  cursor: pointer;
  width: 60px;
  height: 22px;
  line-height: 22px;
  text-align: center;
  font-family: "Hiragino Sans GB", "microsoft yahei", sans-serif;
  font-size: 10px;
  border-width: 1px;
  border-style: solid;
  -moz-border-radius: 2px;
  -webkit-border-radius: 2px;
  border-radius: 2px;
}

5. 用户注册

<!DOCTYPE html>
<html>
  <head>
    <title>注册</title>
	
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="this is my page">
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    
    <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
 
  	<style type="text/css">
		body{
            background: #353f42;


{% comment %}
			background-image: url(https://imgchr.com/content/images/system/home_cover_1552414407320_3a5f92.jpg);
			background-repeat: no-repeat;
			/* 当内容高度大于图片高度时,背景图像的位置相对于viewport固定 */    
			background-attachment: fixed;  /*此条属性必须设置否则可能无效*/    
			/* 让背景图基于容器大小伸缩 */   
			background-size: cover;  
			/* 设置背景颜色,背景图加载过程中会显示背景色 */   
			background-color: #CCCCCC; {% endcomment %}
		}
		#user_reg{
			font-family: 微软雅黑;
			font-size: 40px;
			text-align: center;
			margin-top: 200px;
		}
		form{
			width: 500px;					/*设置宽度,方便使其居中*/
			margin: 40px auto auto auto;	/*上右下左*/
			font-size: 25px;
		}
		input{
			height: 30px;
			width: 12em;
			margin-top: 5px;
			margin-bottom: 5px;
		}
		/*input标签下的属性选择器*/
		input[type="submit"],input[type="reset"]{
			height: 25px;
			width: 5em;
			margin-top: 5px;
			margin-left: 6px;
		}
	</style>
  </head>
  
  <script type="text/javascript">
	//onblur失去焦点事件,用户离开输入框时执行 JavaScript 代码:
	//函数1:验证邮箱格式
  	function validate_username(username){
  		//定义正则表达式的变量:邮箱正则
  		var emailReg=/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
  		//console.log(username);
  		if(username !="" && username.search(emailReg) != -1)
  		{
  			document.getElementById("test_user").innerHTML = "<font color='green' size='3px'>√邮箱格式正确</font>";
  		}else{
  			document.getElementById("test_user").innerHTML = "<font color='red' size='3px'>邮箱格式错误</font>";
  		}
  	}
  
 	//函数2:验证密码是否符合要求:匹配6位密码,由数字和字母组成:
  	function validate_password(password){
  		//^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6-10}$
		//测试密码:12345y
  		var passwordReg=/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6}$/;
  		if(password != "" && password.search(passwordReg) != -1)
  		{
  			document.getElementById("test_pw").innerHTML = "<font color='green' size='3px'>√密码格式正确</font>";
  		}else{
  			document.getElementById("test_pw").innerHTML = "<font color='red' size='3px'>密码格式错误</font>";
  			alert("密码有6位,由数字和字母组成!");
  		}
  	}
  	
	//函数3:验证两次输入的密码是否一样
  	 function validate_password2(password2){
  		var password = document.getElementById("password").value;
  		//测试:console.log(password);
  		//测试:console.log(password2);
  		if (password == ""){
			document.getElementById("is_test_pw").innerHTML = "<font color='red' size='3px'>密码不为空</font>";
		}else if(password==password2){
  			document.getElementById("is_test_pw").innerHTML = "<font color='green' size='3px'>√两次输入的密码相同</font>";
  		}else{
  			document.getElementById("is_test_pw").innerHTML = "<font color='red' size='3px'>两次输入的密码不相同</font>";
  			console.log("密码有6位,由数字和字母组成!");
  		}
  	} 
  	
	//函数4:验证表单是否已经填好
  	function validate_form(){
  		var username = document.getElementById("username").value;
  		var password = document.getElementById("password").value;
  		var password2 = document.getElementById("password2").value;
  		//console.log("表单填写正确,可以正常提交!");
  	
  		//这三个,如果任何一个有问题,都返回false
  		//[email protected]		12345y
  		var emailReg=/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
  		var passwordReg=/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6}$/;
  		
  		if(username != "" && emailReg.test(username)){
  			if(password !="" && passwordReg.test(password)){
  				if(password2==password){
  					alert("信息填写正确,可以正常提交!");
  					console.log("信息填写正确,可以正常提交!");
  					return true;
  				}else{
  					alert("密码不一致,提交失败,请重新填写!");
  					console.log("密码不一致,提交失败,请重新填写!");
  					return false;
  				}
  			}else{
  				alert("密码格式错误,提交失败,请重新填写!");
  				console.log("密码格式错误,提交失败,请重新填写!");
  				return false;
  			}
  		}else{
  			alert("注册的账号不符合要求,提交失败,请重新填写!");
  			console.log("注册的账号不符合要求,提交失败,请重新填写!");
  			return false;
  		}
  	}
  </script>
  
 <body>
  	<div id="user_reg">用户注册:</div>
	<form action="{%url 'user:onRegister'%}" method="post" name="form" >
		<table>
			<tr>
				<td>请输入用户名:</td>
				<td><input type="text" id="username" name="name" placeholder="只能用邮箱注册" onblur="validate_username(this.value)"/></td>
				<td id="test_user"></td>
			</tr>
			<tr>
				<td>请输入密码:</td>
				<td><input type="password" id="password" name="password" placeholder="6位密码由数字和字母组成" onblur="validate_password(this.value)"/></td>
				<td id="test_pw"></td>
			</tr>
			<tr>
				<td>请确认密码:</td>
				<td><input type="password" id="password2" name="password2" onblur="validate_password2(this.value)" /></td>
				<td id="is_test_pw"></td>
			</tr>
			<tr>
				<td></td>
				<td ><input type="submit" id="submit_form" value="注册" onclick="return validate_form()"/>
					<input type="reset" value="重置"/>
				</td>
			</tr>
		</table>
	</form>
</body>
</html>

6. 用户登录

<head>
    <meta charset="UTF-8">
    <title>登录</title>
    <style>
        body {
            background: #353f42;
        }

        * {
            padding: 0;
            margin: 0;
        }

        .main {
            margin: 0 auto;
            padding-left: 25px;
            padding-right: 25px;
            padding-top: 15px;
            width: 350px;
            height: 350px;
            background: #FFFFFF;
            /*以下css用于让登录表单垂直居中在界面,可删除*/
            position: absolute;
            top: 50%;
            left: 50%;
            margin-top: -175px;
            margin-left: -175px;
        }

        .title {
            width: 100%;
            height: 40px;
            line-height: 40px;
        }

        .title span {
            font-size: 18px;
            color: #353f42;
        }

        .title-msg {
            width: 100%;
            height: 64px;
            line-height: 64px;
        }

        .title:hover {
            cursor: default;
        }

        .title-msg:hover {
            cursor: default;
        }

        .title-msg span {
            font-size: 12px;
            color: #707472;
        }

        .input-content {
            width: 100%;
            height: 120px;
        }

        .input-content input {
            width: 330px;
            height: 40px;
            border: 1px solid #dad9d6;
            background: #ffffff;
            padding-left: 10px;
            padding-right: 10px;
        }

        .enter-btn {
            width: 350px;
            height: 40px;
            color: #fff;
            background: #0bc5de;
            line-height: 40px;
            text-align: center;
            border: 0px;
        }

        .foor {
            width: 100%;
            height: auto;
            color: #9b9c98;
            font-size: 12px;
            margin-top: 20px;
        }

        .enter-btn:hover {
            cursor: pointer;
            background: #1db5c9;
        }

        .foor div:hover {
            cursor: pointer;
            color: #484847;
            font-weight: 600;
        }

        .left {
            float: left;
        }

        .right {
            float: right;
        }
    </style>
</head>
<body>
<div class="main">
    <div class="title">
        <span>密码登录</span>
    </div>

    <div class="title-msg">
        <span>请输入登录账户和密码</span>
    </div>

    <form class="login-form" action="{%url 'user:login'%}" method="post" novalidate>
        <!--输入框-->
        <div class="input-content">
            <!--autoFocus-->
            <div>
                <input type="text" autocomplete="off"
                       placeholder="用户名" name="user" required/>
            </div>
            <div style="margin-top: 16px">
                <input type="password"
                       autocomplete="off" placeholder="登录密码" name="password" required maxlength="32"/>
            </div>
        </div>

        <!--登入按钮-->
        <div style="text-align: center">
            <button type="submit" class="enter-btn">
            <a href="{%url 'items:index' %}">登录</a>
            </button>

        </div>

    </form>

</div>
</body>

七、Django的视图层

from django.shortcuts import render, redirect
from django.http import HttpResponse, HttpResponseRedirect
from django.urls import reverse
from django.views.decorators.csrf import csrf_exempt

from data.cartItems import context as cartContext
# from data.itemList import context as itemContext
from user.models import UserList


def register(request):
    return render(request, 'user/register.html')

@csrf_exempt
def login(request):
    if request.method == "POST":
        userName = request.POST.get('user', None)
        password = request.POST.get('password', None)
        message = "所有字段都必须填写!"
        if userName and password:  # 确保用户名和密码都不为空
            username = userName.strip()
            # 用户名字符合法性验证
            # 密码长度验证
            # 更多的其它验证.....
            try:
                user = UserList.objects.get(name=userName)
                if user.password == password:
                    request.session['user'] = user.name
                    return redirect('/')
                else:
                    message = "密码不正确!"
            except:
                message = "用户名不存在!"
        return render(request, 'user/login.html', {"message": message})
    return render(request, 'user/login.html')

@csrf_exempt
def onRegister(request):
    username = request.POST.get('name', None)
    password = request.POST.get('password', None)
    UserList.objects.create(name=username,password=password)
    return render(request, 'user/login.html')

这里给出资源下载的地址,欢迎三连。

Django实现简易淘宝网

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章