django搭建簡單購物網站(功能不完整)

簡介:自學django,從搭建簡單的購物網站開始,網站的功能不完整,目前完成:用戶注冊,用戶登錄和注銷,商品展示,商品詳情,購物車(不完整,沒創建模型,但是已完成表單獲取和session記錄,沒什么大礙),購買支付頁面沒做。本文只是展示部分代碼,html文件可在github下載。

github項目代碼:github.com/IBigBin6/shoponline

軟件環境:ubuntu16.04,安裝mysql,django,python

前期配置:

數據庫配置數據庫支持中文設置:

mysql -u root -p

輸入密碼后進入mysql

create database shoponline;創建數據庫;

use shoponline;指向數據庫對象

show variables like 'character_set_database';查看數據庫編碼

alter database shoponline character set utf8;將數據庫編碼更換為utf-8;


為項目新建一個文件夾:

mkdir testprj

cd testprj

位置:testprj/

利用django新建一個項目

django-admin startproject shoponline

進入shoponline下的shoponline文件夾

cd shoponline/shoponline


位置:testprj/shoponline/shoponline/

新建一個文件夾:

apps:mkdir apps?

media:mkdir?media

static:mkdir static

templates:mkdir template(并在里面建立一個catalog文件夾:mkdir catalog


進入apps:

cd apps

位置:testprj/shoponline/shoponline/apps/

新建一個app:catalog:

django-admin startappcatalog

在此建一個空的__init__.py文件

touch __init__.py


位置:testprj/shoponline/shoponline/

修改settings.py

vim settings.py

在后面添加

SETTINGS_DIR=os.path.dirname(__file__) ?#得到當前文件settings.py的目錄路徑

STATICFILES_DIRS=(os.path.join(SETTINGS_DIR,’static’),) ?#設置靜態文件的路徑,沒用到

MEDIA_ROOT=os.path.join(SETTINGS_DIR,’media’) ?#設置media目錄路徑,存放照片。

MEDIA_URL=’/media/’

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

#(用于session序列化,支持存儲特殊類型的對象數據)

修改

TEMPLATES = [

{

'BACKEND': 'django.template.backends.django.DjangoTemplates',

'DIRS': [os.path.join(SETTINGS_DIR,"templates")],#設置templates路徑,存放html。

'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',],},},]

將這句話注釋#,不使用csrf認證

# ??'django.middleware.csrf.CsrfViewMiddleware',

更改數據庫類型和配置數據庫:

DATABASES = {

'default': {

'ENGINE': 'django.db.backends.mysql',

'NAME': 'shoponline',#數據庫名字,下面是一些用戶名,密碼(自定)

'USER': 'root',

'PASSWORD': '123456',

'HOST': 'localhost',

'PORT': 3306,

'TEST': {}

}}

INSTALLED_APPS = [

'django.contrib.admin',

'django.contrib.auth',

'django.contrib.contenttypes',

'django.contrib.sessions',

'django.contrib.messages',

'django.contrib.staticfiles',

'shoponline.apps.catalog',?#注冊app:catalog,可以使用。

]

退出編輯。

修改urls.py:

vim urls.py

內容為:

from django.conf.urls import url,include

from django.contrib import admin

from django.conf import settings

urlpatterns = [

url(r'^admin/',include(admin.site.urls)), #設置admin的url路徑

url(r'^',include('shoponline.apps.catalog.urls')),

]

至此,配置工作完成!

編程部分:

(主要修改models.py,urls.py,views.py,admin.py,以及templates/catalog/下的網頁模板html文件)

各文件位置

models.py,urls.py,views.py,admin.py都在testprj/shoponline/shoponline/apps/catalog/

html模板testprj/shoponline/shoponline/templates/catalog/

每次修改后,應該執行變更

位置:testprj/shoponline/

生成變更文檔:

python manage.py check

python manage.py makemigrations

python manage.py migrate (應用變更)

(聲明結束)

開始編程:

models.py

模型文件:用于建立數據庫模型,即存儲什么數據,對象屬性的類型聲明(類似數據庫里面的建立表格)

代碼:

#-*-coding:utf-8-*-

from __future__ import unicode_literals

import django.utils.timezone as timezone

from django.db import models

# Create your models here.

defupload_path_handler(instance,filename):

filename=instance.name+'.jpg'

return "{file}".format(file=filename) ?#用于名字filename更改

class Product(models.Model): #建立產品模型

name=models.CharField("名稱",max_length=255,unique=True)

slug=models.SlugField("Slug",max_length=50,unique=True)

price=models.DecimalField("價格",max_digits=9,decimal_places=2)

description=models.TextField("描述")

quantity=models.IntegerField("數量")

image=models.ImageField("圖片",upload_to=upload_path_handler,max_length=50)

# ???categories=models.ManyToManyField(Category)

def __unicode__(self):

return self.name

def get_absolute_url(self):

return reverse('product',args=(self.slug,))

#沒用到

class Category(models.Model):

name=models.CharField("名稱",max_length=250,unique=True)

description=models.TextField("描述")

created_at=models.DateTimeField("創建時間",auto_now_add=True)

updated_at=models.DateTimeField("更新時間",auto_now=True)

def __unicode__(self):

return self.name

#沒用到

class Cart(models.Model):

created_at=models.DateTimeField("時間",auto_now=True)

products=models.ManyToManyField(Product)

total=models.DecimalField("總額",max_digits=9,decimal_places=2)

admin.py

管理文件:用于admin頁面對產品進行數據錄入,管理員后臺錄入產品信息,添加,刪除操作等。

from django.contrib import admin

# Register your models here.

from .models import Product,Category

@admin.register(Product) #注冊產品Product,后會有Porduct的管理條項

class ProductAdmin(admin.ModelAdmin):

list_display=('name','description','price','quantity','image') #管理的顯示產品頁面顯示Product的那幾個屬性

list_display_links=('name',)

list_per_page=50

ordering=['name']

search_field=['name','description']

@admin.register(Category)

class CategoryAdmin(admin.ModelAdmin):

list_display=('name','description','created_at','updated_at')

list_display_links=('name',)

list_per_page=50

ordering=['name']

search_fields=['name','description']


模型創建好了,就可以輸出數據了

創建超級用戶(用于登錄管理頁面):

python manage.py createsuperuser

輸入用戶名和密碼即可

啟動服務器:python manage.py runserver 0.0.0.0:8001

(若占用端口,則用命令:ps -ef |grep 8001

查看PID,第一個數(PID),接著結束進程:kill -9 PID)

ifconfig查看ip地址

瀏覽器進入管理頁面,登陸...

網址:192.168.XX.XX:8001/admin(ip地址)


urls.py

#!/usr/bin/env python

# encoding: utf-8

from django.conf.urls import url

from . import views

from django.conf import settings

from django.conf.urls.static import static

#設置瀏覽器打開所用的鏈接名字,對應什么view,那個html文件,即鏈接是打開什么網頁

urlpatterns=[

url(r'^$',views.index,{'template_name':'catalog/index.html'},name='index'),

url(r'^product/(?P[-\w]+)$',views.show_product,

{'template_name':'catalog/show_product.html'},name='show_product'),

url(r'^register$',views.register,{'template_name':'catalog/register.html'}),

]+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)#設置文件下載到的路徑

views.py

視圖文件:用于對urls聲明的鏈接,對應做出顯示,執行一些數據處理,后將數據顯示到html(template_name)文件中

#-*- coding:utf-8 -*-

from django.shortcuts import render

from django.contrib import auth

# Create your views here.

from .models import Category,Product,Cart

from django.contrib.auth.models import User

def register(request,template_name):

if request.POST:

username=request.POST.get('username','')

password=request.POST.get('password','')

email=request.POST.get('email','')

alert=""

try:

u= User.objects.get(username=username)

except:

user=User.objects.create_user(username=username,

password=password,email=email)

user.save()

alert="注冊成功!"

return render(request,template_name,locals())

pass

alert="用戶名已經使用,可以直接登錄!"

return render(request,template_name,locals())

return render(request,template_name)

def index(request,template_name):

page_title='Welcome to the shop'

p=Product.objects.all()

cart=request.session.get('cart',[])

request.session['cart']=cart

username=request.POST.get('username','')

password=request.POST.get('password','')

logout=request.POST.get('logout')

user=auth.authenticate(username=username,password=password)

if user is not None and user.is_active:

auth.login(request,user)

if logout=='Y':

auth.logout(request)

if request.POST.get('del_index'):

rowIndex=request.POST.get('del_index')

request.session['cart'].pop(int(rowIndex))

return render(request,template_name,locals())

def show_product(request,template_name,product_name):

p=Product.objects.get(name=product_name)

page_title=p.name

cart=request.session.get('cart',[])

request.session['cart']=cart

if request.POST.get('add_name'):

newp=Product.objects.get(name=request.POST['add_name'])

if not newp in request.session[cart]:

request.session['cart'].append(newp)

if request.POST.get('del_index'):

rowIndex=request.POST.get('del_index')

request.session['cart'].pop(int(rowIndex))

return render(request,template_name,locals())

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,786評論 6 534
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,656評論 3 419
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,697評論 0 379
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,098評論 1 314
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,855評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,254評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,322評論 3 442
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,473評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,014評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,833評論 3 355
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,016評論 1 371
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,568評論 5 362
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,273評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,680評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,946評論 1 288
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,730評論 3 393
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,006評論 2 374

推薦閱讀更多精彩內容