由于写着发现太繁琐了,所以能省略的就省略了,如有不能理解之处,请联系我
环境: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
输入账户密码,
好了,点击添加就可以加入用户信息了
就先到这里吧,以后有时间我在追加,太繁琐了.