通过一个helloworld来了解django在虚拟环境中的安装与运行
1.在python3下面建一个文件夹,最好以venv命名
python3 -m venv django_venv
如果出错:请使用下面的命令创建虚拟环境
pip install virtualenvvirtualenv env_name --python=python3
2.激活虚拟环境
ubunto下操作:
source env_name /bin/activate //激活环境
windows下操作:
(cmd) cd env_name/Scripts
activete
3.安装Django 1.11
pip install django==1.11
4.建项目
django-admin startproject helloworld
5.运行
cd helloworld
python manage.py runserver
(默认端口8000)
# 指定端口
python manage.py runserver 0.0.0.0:8888
# sudo ufw allow 8888
6.测试
http http://localhost:8888
7.在helloworld下面创建一个hello app
python manage.py startapp helloapp
写 helloapp/views.py
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def hello(request):
return HttpResponse('Hello World!')
配置 从浏览器发来的请求路由
写helloapp/urls.py
from django.conf.urls import url,include
from django.contrib import admin
from helloapp.views import hello
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^hello/', hello),
]
在helloworld/settings.py中启用helloapp
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'helloapp',
]