由于寫着發現太繁瑣了,是以能省略的就省略了,如有不能了解之處,請聯系我
環境:Ubuntu django
工具:sublime Python MTV 模型
由于該流程比較繁瑣,必然存在某些錯誤,歡迎指正
我是之前早就完成的,現在發到網上,在順序上或許會有些問題,如有不解之處,請指正,我會盡快修改
以下以模拟天天果園為例,介紹後端流程(簡易版)
1、檢視已安裝的Django版本
1、進入到終端 以及 Python 的互動模式
python3 / ipython3
2、互動模式中 輸入 import django
如果未報錯:說明已經安裝過
如果報錯:說明未安裝
3、檢視已安裝的版本
互動模式中:django.VERSION
2、安裝
1、線上安裝 - 使用 pip / pip3
sudo pip3 install django
(預設安裝Django的最高版本)
sudo pip3 install django==1.11.8
(指定安裝1.11.8版本)
2、離線安裝
1、下載下傳所需要的Django包
2、在環境中解壓 Django 包
tar -xvf Django-1.11.8.tar.gz
3、進入到 Django-1.11.8
cd Django-1.11.8
4、安裝
sudo python3 setup.py install
1.在Linux系統下進入終端,建立一個檔案夾Django
[email protected]:~/desktop$ mkdir Django
django-admin startproject fruitday
/home/jack/desktop/Django/fruitday/fruitday下的檔案如下:
我的路徑是:/home/jack/desktop/Django/fruitday
這是修改語言和時區,預設為英語和UTC時間
在fruitday/fruitday/settings下
LANGUAGE_CODE = 'zh-Hans'
TIME_ZONE = 'Asia/Shanghai'
在終端下運作python3 manage.py runserver
如:[email protected]:~/desktop/Django/fruitday$ python3 manage.py runserver
這是啟動服務,可在本地浏覽器中打開
在浏覽器中輸入以下網址 http://localhost:8000 或 http://127.0.0.1:8000 打開進入的界面是中文
若是不修改時區和語言
時間是在終端上顯示(這是尚未修改時區的圖檔)
2.建立應用
python3 manage.py startapp cartinfo
python3 manage.py startapp userinfo
python3 manage.py startapp memberapp
路徑/home/jack/desktop/Django/fruitday/fruitday下
settings.py 中進行注冊
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'cartinfo',
'userinfo',
'memberapp',
]
設定模闆(templates)
模闆實質就是HTML檔案
在任意應用檔案夾下建立即可
如:/home/jack/desktop/Django/fruitday/memberapp/templates
先用别的例子給做一下
先在fruitday檔案夾下的URL中設定:例如:
"""fruitday URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url, include
from django.contrib import admin
from memberapp import views
from django.views.generic import TemplateView # 直接通路template中的html檔案
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^userinfo/', include('userinfo.urls')),
url(r'^cartinfo/', include('cartinfo.urls')),
url(r'^', views.index, name='index'),
# url(r'', TemplateView.as_view(template_name='login.html'),
# name='test'), # 直接通路template中的login.html檔案
url(r'^detail/$', views.detail_one, name='detail'),
]
我以userinfo繼續往下走
在userinfo的檔案夾下設定URL
如下:
from django.conf.urls import url
# from .views import *
from userinfo import views
urlpatterns = [
url('^login', views.login_, name='login'),
url('^register/$', views.register_, name='register'),
url('^address/$', views.user_address, name='address'),
url('^addads/$', views.add_address, name='addads'),
url('^delads/', views.delete_address, name='delads')
以userinfo中的registerin往下走
建立views(檔案在userinfo檔案夾下,自動生成的)
from django.shortcuts import render
from .models import *
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth.hashers import make_password, check_password
from django.core.exceptions import ObjectDoesNotExist
import logging
def signin(request):
return render(request, 'login.html')
def registerin(request):
return render(request, 'register.html')
def login_(request):
if request.method == 'POST':
user = UserInfo()
# user.uname = request.POST.get('username')
# user.upassword = request.POST.get('pwd')
user.uname = request.POST['username']
user.upassword = request.POST['pwd']
print(user.uname)
print(user.upassword)
try:
find_user = UserInfo.objects.filter(uname=user.uname)
print(find_user)
if len(find_user) <= 0:
return render(request, 'login.html', {'message': '使用者未注冊'})
# if not check_password(user.upassword, find_user[0].upassword):
if user.upassword != find_user[0].upassword:
return render(request, 'login.html', {'message': '使用者名或密碼錯誤'})
except ObjectDoesNotExist as e:
logging.warning(e)
if find_user[0].isdelete:
return render(request, 'login.html', {'message': '使用者不存在'})
if not find_user[0].isactive:
return render(request, 'login.html', {'message': '使用者未激活'})
request.session['user_id'] = find_user[0].id
request.session['user_name'] = find_user[0].uname
return render(request, 'index.html')
return render(request, 'login.html')
def register_(request):
if request.method == 'POST':
new_user = UserInfo()
new_user.uname = request.POST.get('username')
# user.upassword = request.POST.get('pwd')
try:
olduser = UserInfo.objects.filter(uname=new_user.uname)
if len(olduser) > 0:
return render(request, 'register.html', {'message': '使用者已存在'})
except ObjectDoesNotExist as e:
logging.warning(e)
if request.POST.get('upwd') != request.POST.get('cpwd'):
return render(request, 'register.html', {'message': '密碼不一緻'})
new_user.upassword = make_password(
request.POST.get('upwd'), 'python', 'pbkdf2_sha1')
new_user.email = request.POST.get('email')
new_user.uphone = request.POST.get('phone')
try:
new_user.save()
except ObjectDoesNotExist as e:
logging.warning(e)
return render(request, 'login.html')
return render(request, 'register.html')
def user_address(request):
# 查該使用者位址
# 擷取該使用者的id
# 查詢該id使用者的全部位址
# return
userid = request.session.get('user_id')
try:
address = Address.objects.filter(user_id=userid)
except ObjectDoesNotExist as e:
logging.warning(e)
return render(request, 'user_center_site.html', {'address': address})
def add_address(request):
# 添加位址
# 擷取該使用者的id
# 擷取前端資料
# 插入新增位址資料
# return
if request.method == 'POST':
userid = request.session.get('user_id')
aname = request.POST.get('aname')
ads = request.POST.get('address')
phone = request.POST.get('phone')
try:
user = UserInfo.objects.get(id=userid)
Address.objects.create(aname=aname, addr=ads,
uphone=phone, user=user)
address = Address.objects.filter(user_id=userid)
except ObjectDoesNotExist as e:
logging.warning(e)
return render(request, 'user_center_site.html', {'address': address})
return render(request, 'user_center_site.html')
def delete_address(request):
print('ahello')
# 删除位址
# 擷取該使用者的id
# 擷取位址id
# 查詢使用者id,位址id相同的資料
# 删除該資料(實體删除)/更新該資料的删除字段的值(邏輯删除)
# return
userid = request.session.get('user_id')
print('bhello')
adsid = request.GET.get('adsid')[:-1]
print('chello')
try:
delads = Address.objects.get(user_id=userid, id=adsid)
print('dhello')
delads.delete()
print('hello')
address = Address.objects.filter(user_id=userid)
except ObjectDoesNotExist as e:
logging.warning(e)
print('dshello')
return render(request, 'user_center_site.html', {'address': address})
# 完成删除a标簽
# 完成models中def拼接url方法(類似詳情頁連結)
# a标簽
# 完成models中def拼接url方法(類似詳情頁連結)
OK 接下來可以建立模闆了
在之前建立的templates檔案夾中建立register.html
<!DOCTYPE html>
<html >
<head>
{% load staticfiles %}
<meta charset="UTF-8">
<title>會員注冊</title>
</head>
<body>
<form action="/userinfo/register/" method='post'>
{% csrf_token %}
使用者名:<input type="text" name='username'>
密碼:<input type="password" name='upwd'>
确認密碼:<input type="password" name='cpwd'>
郵箱:<input type="text" name='email'>
電話:<input type="text" name='phone'>
<p>{{message}}</p>
<input type="submit" name="送出" value='注冊'>
</form>
</body>
</html>
儲存後,在浏覽器輸入http://localhost:8000/userinfo/register/即可進入以下界面
我隻将登陸的代碼給提供
在之前建立的templates檔案夾中建立login.html
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>天天果園登入</title>
{% load staticfiles %}
</head>
<body>
<form action="{%url 'login' %}" method="post">
{% csrf_token %}
<input type="text" name='username'>
<input type="password" name='pwd'>
<p>{{message}}</p>
<p>{{mesage}}</p>
<input type="submit" name="送出" value='登入'>
</form>
</body>
</html>
下面我說一下靜态檔案,之後會用到我在這裡先說一下吧
在fruitday檔案夾下建立static檔案夾,具體路徑如:
/home/jack/desktop/Django/fruitday/static
在其檔案夾下建立image檔案夾,我在裡面存放圖檔
在fruitday檔案夾下的settings設定 (最後一行) STATIC_URL = '/static/'
接下來是建立模型,資料庫,背景
先說資料庫吧
在資料庫建立一個庫 指令;create database fruitday:
在settings設定如下
OK 然後去建立模型,userinfo檔案夾下有一個models.py檔案,寫入以下内容
from django.db import models
# Create your models here.
class UserInfo(models.Model):
email = models.EmailField('郵箱', max_length=40, null=False)
uname = models.CharField('使用者名', max_length=40, null=False)
upassword = models.CharField('密碼', max_length=400, null=False)
isactive = models.BooleanField('是否激活', default=True)
uphone = models.CharField('電話', max_length=40, null=False)
isdelete = models.BooleanField('是否删除', default=False)
def __str__(self):
return self.uname
class Meta:
db_table = 'userinfo'
verbose_name = '使用者資訊'
verbose_name_plural = verbose_name
在該檔案夾下打開admin.py,寫入以下内容
from django.contrib import admin
# Register your models here.
from .models import *
admin.site.register(UserInfo)
好了,完成一半多了
打開終端CD到fruitday,找到manage.py
執行: python3 manage.py makemigrations
接着執行: python3 manage.py migrate
得到下圖:
主要看OK,是不是有報錯
全部是OK的話就沒啥問題了
執行:python3 manage.py runserver
好的 開始打開背景吧
先建立超級使用者
python3 manage.py createsuperuser
賬戶密碼自己随便填吧
結束後再運作python3 manage.py runserver
在浏覽器中輸入localhost:8000/admin
輸入賬戶密碼,
好了,點選添加就可以加入使用者資訊了
就先到這裡吧,以後有時間我在追加,太繁瑣了.