- 安装
pip install Django
- 新建项目
django-admin.py startproject mysite
- 开启web
python manage.py runserver 0.0.0.0:80
报错:
- Invalid HTTP_HOST header: ‘192.168.199.191’. You may need to add u’192.168.199.191’ to ALLOWED_HOSTS.
解决:去django-admin.py startproject project-name创建的项目中去修改 setting.py 文件:
ALLOWED_HOSTS = [‘*’] #在这里请求的host添加了*
- Invalid HTTP_HOST header: ‘192.168.199.191’. You may need to add u’192.168.199.191’ to ALLOWED_HOSTS.
使用MySQL数据库,修改setting.py文件
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', # 或者使用 mysql.connector.django 'NAME': 'test', 'USER': 'test', 'PASSWORD': 'test123', 'HOST':'localhost', 'PORT':'3306', } }
以下内容以创建admin模块为例,没有使用框架自带的管理功能
- 创建应用app
python manage.py startapp admin
添加视图 admin/views.py
from django.http import HttpResponse def index(request): return HttpResponse("Hello, world.")
添加url 新建文件 admin/urls.py
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), ]
在项目配置文件(mysite/urls.py)中添加url
from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', include('admin.urls')), ]
创建model admin/models.py
类对应表 ,类属性对应字段,类属性的类型对应字段类型from django.db import models class User(models.Model): name = models.CharField(max_length=20) passwd = models.CharField(max_length=100)
修改文件site/setting.py
INSTALLED_APPS = [ 'admin.apps.AdminConfig', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ]
生成表结构并添加到数据库
python manage.py makemigrations admin python manage.py migrate
创建admin/template,admin/static 用于放置模板文件和静态文件
–admin/views.py中使用模板文件(admin/template/index.html)def index(request): template = loader.get_template('index.html') context = { 't': 'test', } return HttpResponse(template.render(context, request))
admin/template/index.html文件:
{% load static %} <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}" /> <h1>{{t}}</h1>
目录结构如下:
admin/ ├── admin.py ├── apps.py ├── __init__.py ├── migrations │ ├── __init__.py ├── models.py ├── static │ ├── css │ │ └── style.css │ ├── image │ └── js ├── templates │ └── index.html ├── tests.py ├── urls.py
Django 1
最新推荐文章于 2024-06-13 10:06:41 发布