最近想学爬虫,但是呢,我想搭建一个网站来熟悉一下网页中的东西,我起初的想法是做一个个人博客网站,我django项目都创建了,我用了几天的时间来构思这个网站应该怎么做,正当我在构思的时候,我突然有了一个灵感,那就是我暑假放弃了的个人商城demo,于是我就用这个框架来做了我的个人商城网站。说这么多,主要是想解释我这个项目的命名为什么是my_blog了,而不是不是以shopping命名的项目了。好了,下面进入正题吧。
这里我先简单说一下这个网站能实现哪些功能,能够浏览商品,搜索商品,购买商品功能(没有付款接口,当然只是模拟付款),购物车功能,登录功能(没有用django自带的用户表,含验证登录与保持登录功能)。
我先说一下我做这个项目的版本:python3.6.3, django2.0.5用到的前端框架是bootstrap-3.3.7。这里我需要提一点,这个项目应该适合做过django项目的同学,最少也要使用django框架连接过数据库。不然做这个项目将会很吃力。
好了,我先上一下效果图吧。
商城首页:
点击导航栏中的‘男装’。
图片就贴到这里吧,不能都贴出来,不然就太垮了。我把项目的构架先贴出来
项目的第一步,一定是数据表,数据关系一定要先规划好,不然很有可能使项目做到一半需要大改,这样的话就非常伤脑筋了。这里我贴出models.py的代码。别忘了命令行python manage.py makemigrations , python mange.py migrate迁移数据库文件,与映射数据表到数据库。
from django.db import models
#用户表
class User(models.Model):
username = models.CharField(max_length=30, unique=True)
password = models.CharField(max_length=30)
ismerchant = models.BooleanField(default=False) #是否是商人
merchant_name = models.CharField(max_length=30, blank=True)
merchant_iphone = models.CharField(max_length=11, blank=True)
#商品表
class Commodity(models.Model):
types = (
(1, '请选择商品的类别'),
('男装', '男装'),
('美妆', '美妆'),
('手机', '手机'),
('食品', '食品'),
('电器', '电器'),
('鞋包', '鞋包'),
('百货', '百货'),
('女装', '女装'),
('汽车', '汽车'),
('水果', '水果'),
('运动', '运动'),
('电脑', '电脑'),
('家纺', '家纺'),
('内衣', '内衣'),
('家装', '家装'),
('母婴', '母婴'),
('家居', '家居'),
('文具', '文具'),
('其他', '其他'),
)
merchant_commodity_id = models.ForeignKey(User, to_field='username', on_delete=models.DO_NOTHING)
commodity_name = models.CharField(max_length=30)
commodity_introdice = models.CharField(max_length=255)
commodity_image = models.ImageField(upload_to = 'img')#自动存储到media中的img文件夹中
commodity_price = models.CharField(max_length=20, default='0')
commodity_store = models.CharField(max_length=10, default='none')
commodity_sort = models.CharField(max_length=10, choices=types)
date_issused = models.DateTimeField(auto_now=True)
class Meta:
#按上架时间倒序排序
ordering = ['-date_issused']
#购物车
class Shopping_Cat(models.Model):
commodity_id = models.CharField(max_length=10 , blank=True)#商品id
commodity_introdice = models.CharField(max_length=255, blank=True)#商品介绍
commodity_image = models.CharField(max_length=200, blank=True)
buy_number = models.CharField(max_length=50, blank=True)#购买数量
number_price = models.CharField(max_length=50, blank=True)#总数量
commodity_price = models.CharField(max_length=50, blank=True)
merchant_name = models.CharField(max_length=30, blank=True)#卖家名字
merchant_iphone = models.CharField(max_length=11, blank=True)
merchant_username = models.CharField(max_length=30, blank=True)
cusstomer_name = models.CharField(max_length=30, blank=True)#买家名字
cusstomer_iphone = models.CharField(max_length=11, blank=True)
cusstomer_username = models.CharField(max_length=30, blank=True)
receive_iphone = models.CharField(max_length=11, blank=True)#收件人名字
receive_name = models.CharField(max_length=50, blank=True)
receive_adress = models.CharField(max_length=100, blank=True)
date_issused = models.DateTimeField(auto_now=True)
class Meta:
#按加入购物车的时间倒序排序
ordering = ['-date_issused']
#下单表,这里的字段属性和购物车的表一样
class Indent(models.Model):
commodity_id = models.CharField(max_length=10 , blank=True)
commodity_introdice = models.CharField(max_length=255, blank=True)
commodity_image = models.CharField(max_length=200, blank=True)
buy_number = models.CharField(max_length=50, blank=True)
number_price = models.CharField(max_length=50, blank=True)
commodity_price = models.CharField(max_length=50, blank=True)
merchant_name = models.CharField(max_length=30, blank=True)
merchant_iphone = models.CharField(max_length=11, blank=True)
merchant_username = models.CharField(max_length=30, blank=True)
cusstomer_name = models.CharField(max_length=30, blank=True)
cusstomer_iphone = models.CharField(max_length=11, blank=True)
cusstomer_username = models.CharField(max_length=30, blank=True)
receive_iphone = models.CharField(max_length=11, blank=True)
receive_name = models.CharField(max_length=50, blank=True)
receive_adress = models.CharField(max_length=100, blank=True)
date_issused = models.DateTimeField(auto_now=True)
class Meta:
#按购买的时间倒序排序
ordering = ['-date_issused']
将数据表注册到django后台代码,可以在django后台添加数据。
from django.contrib import admin
from .models import Commodity, User, Shopping_Cat, Indent
class CommodityAdmin(admin.ModelAdmin):
list_display = ['id', 'merchant_commodity_id', 'commodity_name', 'commodity_sort', 'commodity_introdice', 'commodity_image', 'commodity_price', 'commodity_store', 'date_issused']
admin.site.register(Commodity, CommodityAdmin)
class UserAdmin(admin.ModelAdmin):
list_display = ['username', 'password', 'ismerchant', 'merchant_name' ,'merchant_iphone']
admin.site.register(User, UserAdmin)
class Shopping_CatAdmin(admin.ModelAdmin):
list_display = ['commodity_id', 'commodity_introdice', 'buy_number', 'number_price', 'commodity_price', 'merchant_name', 'cusstomer_name', 'receive_name', 'receive_adress' ]
admin.site.register(Shopping_Cat, Shopping_CatAdmin)
class IndentAdmin(admin.ModelAdmin):
list_display = ['commodity_id', 'commodity_introdice', 'buy_number', 'number_price', 'commodity_price', 'merchant_name', 'cusstomer_name', 'receive_name', 'receive_adress' ]
admin.site.register(Indent, IndentAdmin)
urls.py的配置。我由于想快速开发我的网站,我就没有将url include分开来写。
"""my_blog URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, re_path
from django.conf.urls.static import static
from django.views.static import serve
from . import settings
from blogs import views
urlpatterns = [
path('admin/', admin.site.urls),
#meidia的相关配置
re_path(r'media/(?P.*)$', serve, {'document_root':settings.MEDIA_ROOT}),
path('', views.index, name= 'home'),
path('', views.commodity_details, name='commodity_detail'),
path('search/commodity', views.search_commodity, name = 'search_commodity'),
path('search/', views.search_sort, name = 'search_sort'),
path('login', views.login, name = 'login'),
path('user_login', views.user_login, name = 'user_login'),
path('user_register', views.user_register, name = 'user_register'),
path('buy_detail_', views.buy_detail, name = 'buy_detail'),
path('buy_success_', views.buy_success, name = 'buy_success'),
path('shopping_cat_', views.shopping_cat, name = 'shopping_cat'),
path('add_shopping_cat_success_', views.add_shopping_cat_success, name = 'add_shopping_cat_success'),
path('my_shopping_cart', views.my_shopping_cart, name = 'my_shopping_cart'),
path('change_indent_', views.change_indent, name = 'change_indent'),
path('change_success_', views.change_success, name= 'change_success'),
path('delete_success_', views.delete_cat, name= 'delete_success'),
]
# urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
逻辑代码的话我加上注释就直接贴出来了。
from django.shortcuts import render,HttpResponse, redirect, HttpResponseRedirect
import random
from .models import Commodity, User, Indent, Shopping_Cat
def index(request):
#定义一个空字典,将要展示的商品存放到页面上
context = {}
sorts = Commodity.objects.all()
random_names = []
for sort in sorts:
random_names.append(sort.commodity_name)
random_name = random.sample(random_names,1)
context['random_name'] = ''.join(random_name)
commoditys = Commodity.objects.order_by('?')[:30]
commodity_sorts = ['男装', '美妆', '手机', '食品', '电器', '鞋包', '百货', '女装', '汽车', '水果', '运动', '电脑', '家纺', '内衣', '家装', '母婴', '家居', '文具', '其他']
context['commodity_sorts'] = commodity_sorts
context['commoditys'] = commoditys
context['username'] = request.session.get('username')
return render(request, 'commodity.html', context=context)
#用于展示商品的详情页
def commodity_details(request, id):
commodity_detail = Commodity.objects.filter(id = id).first()
context = {}
context['commodity_detail'] = commodity_detail
context['hide'] = 'display: none;'#传给前端,让前端视图隐藏
context['username'] = request.session.get('username')
context['id'] = id
return render(request, 'commodity_detail.html' ,context=context)
#根据搜索栏中的关键词查找商品
def search_commodity(request):
keys = request.GET.get('search', '')
commodity_search = Commodity.objects.all()
context = {}
search_result = []
sorts = Commodity.objects.all()
random_names = []
for sort in sorts:
random_names.append(sort.commodity_name)
random_name = random.sample(random_names,1)
context['random_name'] = ''.join(random_name)
context['username'] = request.session.get('username')
commodity_sorts = ['男装', '美妆', '手机', '食品', '电器', '鞋包', '百货', '女装', '汽车', '水果', '运动', '电脑', '家纺', '内衣', '家装', '母婴', '家居', '文具', '其他']
context['commodity_sorts'] = commodity_sorts
for i in commodity_search:
if keys in str(i.commodity_introdice):
search_result.append(i)
elif keys in str(i.commodity_sort):
search_result.append(i)
if search_result == []:
context['message'] = '对不起。商城没有找到你想搜索的商品!'
else:
context['commoditys'] = search_result
return render(request, 'commodity.html',context=context)
#搜索栏下方的导航栏的方法
def search_sort(request, sort):
context = {}
sorts = Commodity.objects.all()
random_names = []
for sor in sorts:
random_names.append(sor.commodity_name)
#随机取一条数据放入搜索框
random_name = random.sample(random_names,1)
context['random_name'] = ''.join(random_name)
#根据商品类别的查找
commoditys = Commodity.objects.filter(commodity_sort= sort)
context['commoditys'] = commoditys
#获取session判断用户是登录状态
context['username'] = request.session.get('username')
commodity_sorts = ['男装', '美妆', '手机', '食品', '电器', '鞋包', '百货', '女装', '汽车', '水果', '运动', '电脑', '家纺', '内衣', '家装', '母婴', '家居', '文具', '其他']
context['commodity_sorts'] = commodity_sorts
return render(request, 'commodity.html' , context=context)
#进入登录页面
def login(request):
return render(request, 'login.html')
#登录功能
def user_login(request):
if request.method == 'POST':
username = request.POST.get('username', '')
password = request.POST.get('password', '')
#验证登录
users = User.objects.filter(username=username, password=password)
if username == '' or password =='':
return render(request, 'login.html',{'message':'用户名和密码不能为空'})
if users:
# request.session['is_login'] = '1'
#登录后给浏览器发送登录者的用户名(保持登录状态)
request.session['username'] = users[0].username
#设置保持登录时间 参数0表示Cookie将在用户的浏览器关闭时过期,None表示永不过期,整数表示在多少秒后过期
request.session.set_expiry(0)
return HttpResponseRedirect(request.POST.get('next', '/') or '/')
return render(request, 'login.html',{'message':'用户名或密码错误'})
#用户注册功能
def user_register(request):
if request.method == 'POST':
username = request.POST.get('register_username', '')
password = request.POST.get('register_password', '')
again_password = request.POST.get('again_password', '')
merchant_iphone = request.POST.get('merchant_iphone', '')
merchant_name = request.POST.get('merchant_name', '')
username_exist = User.objects.filter(username = username)
if username_exist:
return render(request, 'register.html', {'message': '用户名已存在'})
elif password != again_password:
return render(request, 'register.html', {'message': '两次密码输入不一致'})
else:
User.objects.create(username = username, password = password, merchant_name = merchant_name, merchant_iphone =merchant_iphone).save()
return render(request, 'login.html')
return render(request, 'register.html')
#购买详情页
def buy_detail(request, id):
commodity = Commodity.objects.filter(id = id).first()
context={}
context['commodity_name'] = commodity.commodity_name
context['commodity_image'] = commodity.commodity_image
context['commodity_store'] = commodity.commodity_store
context['commodity_price'] = commodity.commodity_price
context['id'] = id
username = request.session.get('username')
if username:
users = User.objects.filter(username=username).first()
context['merchant_name'] = users.merchant_name
context['merchant_iphone'] = users.merchant_iphone
context['hide'] = 'display: none;'
context['username'] = username
return render(request, 'buy_detail.html',context = context)
else:
return render(request, 'login.html')
#立即下单购买成功
def buy_success(requset ,id):
if requset.method == 'POST':
users = Commodity.objects.filter(id = id).first()
cusstomer = User.objects.filter(username=requset.session.get('username')).first()
context={}
context['id'] = id
context['commodity_introdice'] = users.commodity_introdice
context['commodity_image'] = users.commodity_image
context['commodity_price'] = users.commodity_price
print(type(context['commodity_price']))
context['buy_number'] = requset.POST.get('buy_number', '')
context['number_price'] = requset.POST.get('number_price', '')
context['province'] = requset.POST.get('province', '')
context['town'] = requset.POST.get('town', '')
context['area'] = requset.POST.get('area', '')
context['merchant_username'] = users.merchant_commodity_id.username
context['merchant_iphone'] = users.merchant_commodity_id.merchant_iphone
context['merchant_name'] = users.merchant_commodity_id.merchant_name
context['cusstomer_name'] = cusstomer.merchant_name
context['cusstomer_iphone'] = cusstomer.merchant_iphone
context['cusstomer_username'] = cusstomer.username
context['address_detail'] = requset.POST.get('address_detail', '')
context['address'] = context['province'] + '省 ' + context['town'] + ' ' +context['area'] + ' ' + context['address_detail']
context['address_name'] = requset.POST.get('address_name', '')
context['address_iphone'] = requset.POST.get('address_iphone', '')
Indent.objects.create(commodity_id=id,commodity_introdice=context['commodity_introdice'],commodity_image=context['commodity_image'] ,
buy_number = context['buy_number'], number_price=context['number_price'],commodity_price=context['commodity_price'],
merchant_name=context['merchant_name'],merchant_iphone=context['merchant_iphone'],merchant_username=context['merchant_username'],
cusstomer_name=context['cusstomer_name'], cusstomer_iphone =context['cusstomer_iphone'],cusstomer_username=context['cusstomer_username'],
receive_iphone= context['address_iphone'],receive_name=context['address_name'],receive_adress=context['address']).save()
return render(requset, 'buy_success.html', context= context)
return render(requset, 'buy_detail.html.html')
#加入购物车
def shopping_cat(request, id):
commodity = Commodity.objects.filter(id = id).first()
context={}
context['commodity_name'] = commodity.commodity_name
context['commodity_image'] = commodity.commodity_image
context['commodity_store'] = commodity.commodity_store
context['commodity_price'] = commodity.commodity_price
context['id'] = id
username = request.session.get('username')
if username:
users = User.objects.filter(username=username).first()
context['merchant_name'] = users.merchant_name
context['merchant_iphone'] = users.merchant_iphone
context['hide'] = 'display: none;'
context['username'] = username
return render(request, 'shopping_cat.html',context = context)
else:
return render(request, 'login.html')
#加入购物车成功
def add_shopping_cat_success(requset ,id):
if requset.method == 'POST':
users = Commodity.objects.filter(id = id).first()
cusstomer = User.objects.filter(username=requset.session.get('username')).first()
context={}
context['id'] = id
context['commodity_introdice'] = users.commodity_introdice
context['commodity_image'] = users.commodity_image
context['commodity_price'] = users.commodity_price
context['buy_number'] = requset.POST.get('buy_number', '')
context['number_price'] = requset.POST.get('number_price', '')
context['province'] = requset.POST.get('province', '')
context['town'] = requset.POST.get('town', '')
context['area'] = requset.POST.get('area', '')
context['merchant_username'] = users.merchant_commodity_id.username
context['merchant_iphone'] = users.merchant_commodity_id.merchant_iphone
context['merchant_name'] = users.merchant_commodity_id.merchant_name
context['cusstomer_name'] = cusstomer.merchant_name
context['cusstomer_iphone'] = cusstomer.merchant_iphone
context['cusstomer_username'] = cusstomer.username
context['address_detail'] = requset.POST.get('address_detail', '')
context['address'] = context['province'] + '省 ' + context['town'] + ' ' +context['area'] + ' ' + context['address_detail']
context['address_name'] = requset.POST.get('address_name', '')
context['address_iphone'] = requset.POST.get('address_iphone', '')
Shopping_Cat.objects.create(commodity_id=id,commodity_introdice=context['commodity_introdice'],commodity_image=context['commodity_image'] ,
buy_number = context['buy_number'], number_price=context['number_price'],commodity_price=context['commodity_price'],
merchant_name=context['merchant_name'],merchant_iphone=context['merchant_iphone'],merchant_username=context['merchant_username'],
cusstomer_name=context['cusstomer_name'], cusstomer_iphone =context['cusstomer_iphone'],cusstomer_username=context['cusstomer_username'],
receive_iphone= context['address_iphone'],receive_name=context['address_name'],receive_adress=context['address']).save()
return render(requset, 'add_shopping_cat_success.html', context= context)
return render(requset, 'buy_detail.html.html')
def my_shopping_cart(request):
username = request.session.get('username')
if username :
shopping_cart = Shopping_Cat.objects.filter(cusstomer_username = username)
context = {}
context['username'] = username
context['shopping_cart'] = shopping_cart
context['hide'] = 'display: none;'
return render(request, 'my_shopping_cart.html',context=context)
return render(request,'login.html')
def change_indent(request, id):
change_cat = Shopping_Cat.objects.filter(id = id).first()
context = {}
context['change_cat'] = change_cat
context['province'] = change_cat.receive_adress.split(' ')[0]
context['town'] = change_cat.receive_adress.split(' ')[1]
context['area'] = change_cat.receive_adress.split(' ')[2]
commodity = Commodity.objects.filter(id = change_cat.commodity_id).first()
context['commodity'] = commodity.commodity_store
return render(request, 'change_indent.html', context=context)
def change_success(request, id):
context = {}
if request.method == 'POST':
context['buy_number'] = request.POST.get('buy_number', '')
shopping_cats = Shopping_Cat.objects.get(id = id)
context['province'] = request.POST.get('province', '')
context['town'] = request.POST.get('town', '')
context['area'] = request.POST.get('area', '')
context['address_detail'] = request.POST.get('address_detail', '')
context['address_name'] = request.POST.get('address_name', '')
context['number_price'] = request.POST.get('number_price', '')
context['address_iphone'] = request.POST.get('address_iphone', '')
context['username'] = request.session.get('username')
shopping_cart = Shopping_Cat.objects.filter(cusstomer_username = context['username'])
context['shopping_cart'] = shopping_cart
context['hide'] = 'display: none;'
context['address'] = context['province'] + '省 ' + context['town'] + ' ' +context['area'] + ' ' + context['address_detail']
shopping_cats.buy_number = context['buy_number']
shopping_cats.receive_adress = context['address']
shopping_cats.receive_name = context['address_name']
shopping_cats.number_price = context['number_price']
shopping_cats.receive_iphone = context['address_iphone']
shopping_cats.save()
return render(request, 'my_shopping_cart.html', context = context)
return render(request, 'commodity.html')
def delete_cat(request ,id):
context = {}
context['username'] = request.session.get('username')
shopping_cats = Shopping_Cat.objects.get(id = id)
shopping_cats.delete()
shopping_cart = Shopping_Cat.objects.filter(cusstomer_username = context['username'])
context['shopping_cart'] = shopping_cart
context['hide'] = 'display: none;'
return render(request, 'my_shopping_cart.html', context =context)
这里就不贴前端代码了,我等下将我的那个项目的链接直接附在下面,等会你们可以直接前往下载。
https://download.csdn.net/download/qq_41983562/11106925
也可以关注公众号留言免费领取
百度云盘
链接:https://pan.baidu.com/s/1fRtYfN-_jfLYa81XNEfsQQ
提取码:wxod