簡介:自學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())