Skip to content

Commit

Permalink
更新了购物车案例的代码
Browse files Browse the repository at this point in the history
  • Loading branch information
jackfrued committed May 25, 2018
1 parent 169188f commit 95f78d2
Show file tree
Hide file tree
Showing 32 changed files with 448 additions and 32 deletions.
1 change: 1 addition & 0 deletions Day31-Day35/shop/cart/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
class GoodsAdmin(admin.ModelAdmin):

list_display = ('id', 'name', 'price', 'image')
search_fields = ('name', )


admin.site.register(Goods, GoodsAdmin)
2 changes: 1 addition & 1 deletion Day31-Day35/shop/cart/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Generated by Django 2.0.5 on 2018-05-25 05:11
# Generated by Django 2.0.5 on 2018-05-25 06:28

from django.db import migrations, models

Expand Down
4 changes: 3 additions & 1 deletion Day31-Day35/shop/cart/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,14 @@


class Goods(models.Model):
"""商品模型类"""

id = models.AutoField(primary_key=True, db_column='gid')
name = models.CharField(max_length=50, db_column='gname')
price = models.DecimalField(max_digits=10, decimal_places=2, db_column='gprice')
image = models.CharField(max_length=255, db_column='gimage')

class Meta:

db_table = 'tb_goods'
ordering = ('id',)
ordering = ('id', )
69 changes: 64 additions & 5 deletions Day31-Day35/shop/cart/views.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from django.shortcuts import render
from django.shortcuts import render, redirect

from cart.models import Goods

Expand All @@ -8,9 +8,68 @@ def index(request):
return render(request, 'goods.html', {'goods_list': goods_list})


def show_cart(request):
return render(request, 'cart.html')
class CartItem(object):
"""购物车中的商品项"""

def __init__(self, goods, amount=1):
self.goods = goods
self.amount = amount

@property
def total(self):
return self.goods.price * self.amount


class ShoppingCart(object):
"""购物车"""

def __init__(self):
self.items = {}

def add_item(self, item):
if item.goods.id in self.items:
self.items[item.goods.id].amount += item.amount
else:
self.items[item.goods.id] = item

def remove_item(self, id):
if id in self.items:
self.items.remove(id)

def add_to_cart(request, no):
pass
def clear_all_items(self):
self.items.clear()

@property
def cart_items(self):
return self.items.values()

@property
def total(self):
val = 0
for item in self.items.values():
val += item.total
return val


def add_to_cart(request, id):
goods = Goods.objects.get(pk=id)
# 通过request对象的session属性可以获取到session
# session相当于是服务器端用来保存用户数据的一个字典
# session利用了Cookie保存sessionid
# 通过sessionid就可以获取与某个用户对应的会话(也就是用户数据)
# 如果在浏览器中清除了Cookie那么也就清除了sessionid
# 再次访问服务器时服务器会重新分配新的sessionid这也就意味着之前的用户数据无法找回
# 默认情况下Django的session被设定为持久会话而非浏览器续存期会话
# 通过SESSION_EXPIRE_AT_BROWSER_CLOSE和SESSION_COOKIE_AGE参数可以修改默认设定
# Django中的session是进行了持久化处理的因此需要设定session的序列化方式
# 1.6版开始Django默认的session序列化器是JsonSerializer
# 可以通过SESSION_SERIALIZER来设定其他的序列化器(例如PickleSerializer)
cart = request.session.get('cart', ShoppingCart())
cart.add_item(CartItem(goods))
request.session['cart'] = cart
return redirect('/')


def show_cart(request):
cart = request.session.get('cart', None)
return render(request, 'cart.html', {'cart': cart})
Empty file modified Day31-Day35/shop/manage.py
100755 → 100644
Empty file.
2 changes: 1 addition & 1 deletion Day31-Day35/shop/shop/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
import pymysql

pymysql.install_as_MySQLdb()
pymysql.install_as_MySQLdb()
13 changes: 8 additions & 5 deletions Day31-Day35/shop/shop/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
# See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '+gqc54!5+uhvc^o0)fjvihmg&5uu^u+#s5m*fc+e+@bw*(+!w*'
SECRET_KEY = '3(n^av%_kt*^2zhz0!iwkxv6_wp^ed7-dpow*vqr7ck0_6=9^e'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
Expand All @@ -37,7 +37,7 @@
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'cart',
'cart.apps.CartConfig',
]

MIDDLEWARE = [
Expand Down Expand Up @@ -78,7 +78,7 @@
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'Shop',
'NAME': 'shop',
'HOST': 'localhost',
'PORT': 3306,
'USER': 'root',
Expand All @@ -105,11 +105,12 @@
},
]

SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer'

# Internationalization
# https://docs.djangoproject.com/en/2.0/topics/i18n/

LANGUAGE_CODE = 'en-us'
LANGUAGE_CODE = 'zh-hans'

TIME_ZONE = 'Asia/Chongqing'

Expand All @@ -122,5 +123,7 @@

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.0/howto/static-files/
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]

STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'),]

STATIC_URL = '/static/'
2 changes: 1 addition & 1 deletion Day31-Day35/shop/shop/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@

urlpatterns = [
path('', views.index),
path('add_to_cart/<int:id>', views.add_to_cart),
path('show_cart', views.show_cart),
path('add_to_cart/<int:no>', views.add_to_cart),
path('admin/', admin.site.urls),
]
Binary file added Day31-Day35/shop/static/images/Thumbs.db
Binary file not shown.
14 changes: 7 additions & 7 deletions Day31-Day35/shop/templates/cart.html
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@ <h1>购物车列表</h1>
<hr>
</div>
<div class="right">
<a href="list_goods" class="back">返回</a>
<a href="/" class="back">返回</a>
</div>
{% if cart_items %}
{% if cart %}
<table style="clear: both;">
<tr>
<th>商品名称</th>
Expand All @@ -32,12 +32,12 @@ <h1>购物车列表</h1>
<th>商品总价</th>
<th>操作</th>
</tr>
{% for item in cart_items %}
{% for item in cart.cart_items %}
<tr>
<td class="name">{{ item.name }}</td>
<td class="price">&yen;{{ item.unit_price }}</td>
<td class="name">{{ item.goods.name }}</td>
<td class="price">&yen;{{ item.goods.price }}</td>
<td>{{ item.amount }}</td>
<td class="price">&yen;{{ item.total_price }}</td>
<td class="price">&yen;{{ item.total }}</td>
<td>
<a href="" class="del">删除</a>
</td>
Expand All @@ -47,7 +47,7 @@ <h1>购物车列表</h1>
<td colspan="5" class="total price">&yen;{{ cart.total }}元</td>
</tr>
</table>
<a href="clear_cart" class="back">清空购物车</a>
<a href="" class="back">清空购物车</a>
{% else %}
<h3 style="clear: both;">购物车中暂时没有商品!</h3>
{% endif %}
Expand Down
Empty file.
11 changes: 11 additions & 0 deletions Day31-Day35/shop_origin/cart/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
from django.contrib import admin

from cart.models import Goods


class GoodsAdmin(admin.ModelAdmin):

list_display = ('id', 'name', 'price', 'image')


admin.site.register(Goods, GoodsAdmin)
5 changes: 5 additions & 0 deletions Day31-Day35/shop_origin/cart/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from django.apps import AppConfig


class CartConfig(AppConfig):
name = 'cart'
27 changes: 27 additions & 0 deletions Day31-Day35/shop_origin/cart/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Generated by Django 2.0.5 on 2018-05-25 05:11

from django.db import migrations, models


class Migration(migrations.Migration):

initial = True

dependencies = [
]

operations = [
migrations.CreateModel(
name='Goods',
fields=[
('id', models.AutoField(db_column='gid', primary_key=True, serialize=False)),
('name', models.CharField(db_column='gname', max_length=50)),
('price', models.DecimalField(db_column='gprice', decimal_places=2, max_digits=10)),
('image', models.CharField(db_column='gimage', max_length=255)),
],
options={
'db_table': 'tb_goods',
'ordering': ('id',),
},
),
]
Empty file.
13 changes: 13 additions & 0 deletions Day31-Day35/shop_origin/cart/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
from django.db import models


class Goods(models.Model):

id = models.AutoField(primary_key=True, db_column='gid')
name = models.CharField(max_length=50, db_column='gname')
price = models.DecimalField(max_digits=10, decimal_places=2, db_column='gprice')
image = models.CharField(max_length=255, db_column='gimage')

class Meta:
db_table = 'tb_goods'
ordering = ('id',)
3 changes: 3 additions & 0 deletions Day31-Day35/shop_origin/cart/tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.test import TestCase

# Create your tests here.
16 changes: 16 additions & 0 deletions Day31-Day35/shop_origin/cart/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
from django.shortcuts import render

from cart.models import Goods


def index(request):
goods_list = list(Goods.objects.all())
return render(request, 'goods.html', {'goods_list': goods_list})


def show_cart(request):
return render(request, 'cart.html')


def add_to_cart(request, no):
pass
15 changes: 15 additions & 0 deletions Day31-Day35/shop_origin/manage.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#!/usr/bin/env python
import os
import sys

if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "shop.settings")
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
3 changes: 3 additions & 0 deletions Day31-Day35/shop_origin/shop/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import pymysql

pymysql.install_as_MySQLdb()
Loading

0 comments on commit 95f78d2

Please sign in to comment.