Skip to content

Commit 95f78d2

Browse files
committed
更新了购物车案例的代码
1 parent 169188f commit 95f78d2

32 files changed

+448
-32
lines changed

Day31-Day35/shop/cart/admin.py

+1
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
class GoodsAdmin(admin.ModelAdmin):
77

88
list_display = ('id', 'name', 'price', 'image')
9+
search_fields = ('name', )
910

1011

1112
admin.site.register(Goods, GoodsAdmin)

Day31-Day35/shop/cart/migrations/0001_initial.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# Generated by Django 2.0.5 on 2018-05-25 05:11
1+
# Generated by Django 2.0.5 on 2018-05-25 06:28
22

33
from django.db import migrations, models
44

Day31-Day35/shop/cart/models.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,14 @@
22

33

44
class Goods(models.Model):
5+
"""商品模型类"""
56

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

1112
class Meta:
13+
1214
db_table = 'tb_goods'
13-
ordering = ('id',)
15+
ordering = ('id', )

Day31-Day35/shop/cart/views.py

+64-5
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from django.shortcuts import render
1+
from django.shortcuts import render, redirect
22

33
from cart.models import Goods
44

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

1010

11-
def show_cart(request):
12-
return render(request, 'cart.html')
11+
class CartItem(object):
12+
"""购物车中的商品项"""
13+
14+
def __init__(self, goods, amount=1):
15+
self.goods = goods
16+
self.amount = amount
17+
18+
@property
19+
def total(self):
20+
return self.goods.price * self.amount
21+
22+
23+
class ShoppingCart(object):
24+
"""购物车"""
25+
26+
def __init__(self):
27+
self.items = {}
28+
29+
def add_item(self, item):
30+
if item.goods.id in self.items:
31+
self.items[item.goods.id].amount += item.amount
32+
else:
33+
self.items[item.goods.id] = item
1334

35+
def remove_item(self, id):
36+
if id in self.items:
37+
self.items.remove(id)
1438

15-
def add_to_cart(request, no):
16-
pass
39+
def clear_all_items(self):
40+
self.items.clear()
41+
42+
@property
43+
def cart_items(self):
44+
return self.items.values()
45+
46+
@property
47+
def total(self):
48+
val = 0
49+
for item in self.items.values():
50+
val += item.total
51+
return val
52+
53+
54+
def add_to_cart(request, id):
55+
goods = Goods.objects.get(pk=id)
56+
# 通过request对象的session属性可以获取到session
57+
# session相当于是服务器端用来保存用户数据的一个字典
58+
# session利用了Cookie保存sessionid
59+
# 通过sessionid就可以获取与某个用户对应的会话(也就是用户数据)
60+
# 如果在浏览器中清除了Cookie那么也就清除了sessionid
61+
# 再次访问服务器时服务器会重新分配新的sessionid这也就意味着之前的用户数据无法找回
62+
# 默认情况下Django的session被设定为持久会话而非浏览器续存期会话
63+
# 通过SESSION_EXPIRE_AT_BROWSER_CLOSE和SESSION_COOKIE_AGE参数可以修改默认设定
64+
# Django中的session是进行了持久化处理的因此需要设定session的序列化方式
65+
# 1.6版开始Django默认的session序列化器是JsonSerializer
66+
# 可以通过SESSION_SERIALIZER来设定其他的序列化器(例如PickleSerializer)
67+
cart = request.session.get('cart', ShoppingCart())
68+
cart.add_item(CartItem(goods))
69+
request.session['cart'] = cart
70+
return redirect('/')
71+
72+
73+
def show_cart(request):
74+
cart = request.session.get('cart', None)
75+
return render(request, 'cart.html', {'cart': cart})

Day31-Day35/shop/manage.py

100755100644
File mode changed.

Day31-Day35/shop/shop/__init__.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
import pymysql
22

3-
pymysql.install_as_MySQLdb()
3+
pymysql.install_as_MySQLdb()

Day31-Day35/shop/shop/settings.py

+8-5
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
# See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/
2121

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

2525
# SECURITY WARNING: don't run with debug turned on in production!
2626
DEBUG = True
@@ -37,7 +37,7 @@
3737
'django.contrib.sessions',
3838
'django.contrib.messages',
3939
'django.contrib.staticfiles',
40-
'cart',
40+
'cart.apps.CartConfig',
4141
]
4242

4343
MIDDLEWARE = [
@@ -78,7 +78,7 @@
7878
DATABASES = {
7979
'default': {
8080
'ENGINE': 'django.db.backends.mysql',
81-
'NAME': 'Shop',
81+
'NAME': 'shop',
8282
'HOST': 'localhost',
8383
'PORT': 3306,
8484
'USER': 'root',
@@ -105,11 +105,12 @@
105105
},
106106
]
107107

108+
SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer'
108109

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

112-
LANGUAGE_CODE = 'en-us'
113+
LANGUAGE_CODE = 'zh-hans'
113114

114115
TIME_ZONE = 'Asia/Chongqing'
115116

@@ -122,5 +123,7 @@
122123

123124
# Static files (CSS, JavaScript, Images)
124125
# https://docs.djangoproject.com/en/2.0/howto/static-files/
125-
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
126+
127+
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'),]
128+
126129
STATIC_URL = '/static/'

Day31-Day35/shop/shop/urls.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020

2121
urlpatterns = [
2222
path('', views.index),
23+
path('add_to_cart/<int:id>', views.add_to_cart),
2324
path('show_cart', views.show_cart),
24-
path('add_to_cart/<int:no>', views.add_to_cart),
2525
path('admin/', admin.site.urls),
2626
]
21 KB
Binary file not shown.

Day31-Day35/shop/templates/cart.html

+7-7
Original file line numberDiff line numberDiff line change
@@ -21,9 +21,9 @@ <h1>购物车列表</h1>
2121
<hr>
2222
</div>
2323
<div class="right">
24-
<a href="list_goods" class="back">返回</a>
24+
<a href="/" class="back">返回</a>
2525
</div>
26-
{% if cart_items %}
26+
{% if cart %}
2727
<table style="clear: both;">
2828
<tr>
2929
<th>商品名称</th>
@@ -32,12 +32,12 @@ <h1>购物车列表</h1>
3232
<th>商品总价</th>
3333
<th>操作</th>
3434
</tr>
35-
{% for item in cart_items %}
35+
{% for item in cart.cart_items %}
3636
<tr>
37-
<td class="name">{{ item.name }}</td>
38-
<td class="price">&yen;{{ item.unit_price }}</td>
37+
<td class="name">{{ item.goods.name }}</td>
38+
<td class="price">&yen;{{ item.goods.price }}</td>
3939
<td>{{ item.amount }}</td>
40-
<td class="price">&yen;{{ item.total_price }}</td>
40+
<td class="price">&yen;{{ item.total }}</td>
4141
<td>
4242
<a href="" class="del">删除</a>
4343
</td>
@@ -47,7 +47,7 @@ <h1>购物车列表</h1>
4747
<td colspan="5" class="total price">&yen;{{ cart.total }}元</td>
4848
</tr>
4949
</table>
50-
<a href="clear_cart" class="back">清空购物车</a>
50+
<a href="" class="back">清空购物车</a>
5151
{% else %}
5252
<h3 style="clear: both;">购物车中暂时没有商品!</h3>
5353
{% endif %}

Day31-Day35/shop_origin/cart/__init__.py

Whitespace-only changes.

Day31-Day35/shop_origin/cart/admin.py

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
from django.contrib import admin
2+
3+
from cart.models import Goods
4+
5+
6+
class GoodsAdmin(admin.ModelAdmin):
7+
8+
list_display = ('id', 'name', 'price', 'image')
9+
10+
11+
admin.site.register(Goods, GoodsAdmin)

Day31-Day35/shop_origin/cart/apps.py

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
from django.apps import AppConfig
2+
3+
4+
class CartConfig(AppConfig):
5+
name = 'cart'
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# Generated by Django 2.0.5 on 2018-05-25 05:11
2+
3+
from django.db import migrations, models
4+
5+
6+
class Migration(migrations.Migration):
7+
8+
initial = True
9+
10+
dependencies = [
11+
]
12+
13+
operations = [
14+
migrations.CreateModel(
15+
name='Goods',
16+
fields=[
17+
('id', models.AutoField(db_column='gid', primary_key=True, serialize=False)),
18+
('name', models.CharField(db_column='gname', max_length=50)),
19+
('price', models.DecimalField(db_column='gprice', decimal_places=2, max_digits=10)),
20+
('image', models.CharField(db_column='gimage', max_length=255)),
21+
],
22+
options={
23+
'db_table': 'tb_goods',
24+
'ordering': ('id',),
25+
},
26+
),
27+
]

Day31-Day35/shop_origin/cart/migrations/__init__.py

Whitespace-only changes.
+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
from django.db import models
2+
3+
4+
class Goods(models.Model):
5+
6+
id = models.AutoField(primary_key=True, db_column='gid')
7+
name = models.CharField(max_length=50, db_column='gname')
8+
price = models.DecimalField(max_digits=10, decimal_places=2, db_column='gprice')
9+
image = models.CharField(max_length=255, db_column='gimage')
10+
11+
class Meta:
12+
db_table = 'tb_goods'
13+
ordering = ('id',)

Day31-Day35/shop_origin/cart/tests.py

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
from django.test import TestCase
2+
3+
# Create your tests here.

Day31-Day35/shop_origin/cart/views.py

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
from django.shortcuts import render
2+
3+
from cart.models import Goods
4+
5+
6+
def index(request):
7+
goods_list = list(Goods.objects.all())
8+
return render(request, 'goods.html', {'goods_list': goods_list})
9+
10+
11+
def show_cart(request):
12+
return render(request, 'cart.html')
13+
14+
15+
def add_to_cart(request, no):
16+
pass

Day31-Day35/shop_origin/manage.py

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
#!/usr/bin/env python
2+
import os
3+
import sys
4+
5+
if __name__ == "__main__":
6+
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "shop.settings")
7+
try:
8+
from django.core.management import execute_from_command_line
9+
except ImportError as exc:
10+
raise ImportError(
11+
"Couldn't import Django. Are you sure it's installed and "
12+
"available on your PYTHONPATH environment variable? Did you "
13+
"forget to activate a virtual environment?"
14+
) from exc
15+
execute_from_command_line(sys.argv)
+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
import pymysql
2+
3+
pymysql.install_as_MySQLdb()

0 commit comments

Comments
 (0)