提交 b265f0c8 编写于 作者: 骆昊的技术专栏's avatar 骆昊的技术专栏

'添加了Django示例代码'

上级 ef8cf2ea
from django.contrib import admin
from demo.models import Teacher
class TeacherAdmin(admin.ModelAdmin):
list_display = ('no', 'name', 'job', 'intro', 'motto')
search_fields = ('name', 'intro')
ordering = ('no', )
admin.site.register(Teacher, TeacherAdmin)
from django.apps import AppConfig
class DemoConfig(AppConfig):
name = 'demo'
# Generated by Django 2.0.6 on 2018-07-03 02:20
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Teacher',
fields=[
('no', models.AutoField(db_column='tno', primary_key=True, serialize=False)),
('name', models.CharField(db_column='tname', max_length=20)),
('job', models.CharField(db_column='tjob', max_length=10)),
('intro', models.CharField(db_column='tintro', max_length=1023)),
('motto', models.CharField(db_column='tmotto', max_length=255)),
],
options={
'db_table': 'tb_teacher',
},
),
]
# Generated by Django 2.0.6 on 2018-07-03 03:42
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('demo', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='teacher',
name='photo',
field=models.CharField(db_column='tphoto', max_length=511, null=True),
),
]
# Generated by Django 2.0.6 on 2018-07-03 05:55
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('demo', '0002_teacher_photo'),
]
operations = [
migrations.AlterModelTable(
name='teacher',
table=None,
),
]
# Generated by Django 2.0.6 on 2018-07-03 06:12
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('demo', '0003_auto_20180703_1355'),
]
operations = [
migrations.AlterModelOptions(
name='teacher',
options={'ordering': ('-no',)},
),
migrations.AlterModelTable(
name='teacher',
table='tb_teacher',
),
]
from django.db import models
# Django框架中包含了ORM(对象关系映射)框架
# ORM可以帮助我们完成对象模型到关系模型的双向转换
class Teacher(models.Model):
no = models.AutoField(primary_key=True, db_column='tno', verbose_name='编号')
name = models.CharField(max_length=20, db_column='tname', verbose_name='姓名')
job = models.CharField(max_length=10, db_column='tjob', verbose_name='职位')
intro = models.CharField(max_length=1023, db_column='tintro', verbose_name='简介')
motto = models.CharField(max_length=255, db_column='tmotto', verbose_name='教学理念')
photo = models.CharField(max_length=511, db_column='tphoto', null=True)
class Meta(object):
db_table = 'tb_teacher'
ordering = ('-no', )
from django.shortcuts import render
from demo.models import Teacher
def home(request):
# 通过ORM框架实现持久化操作CRUD
ctx = {'teachers_list': list(Teacher.objects.all())}
return render(request, 'demo/home.html', ctx)
"""
Django settings for hellodjango project.
Generated by 'django-admin startproject' using Django 2.0.6.
For more information on this file, see
https://docs.djangoproject.com/en/2.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.0/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'j*jr(3-it8$lrp&u@e^!f%8!ws*=jx)ga*ln%l6aqftu-uy1=1'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'demo',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'hellodjango.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'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',
],
},
},
]
WSGI_APPLICATION = 'hellodjango.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'demo',
'HOST': '120.77.222.217',
'PORT': 3306,
'USER': 'root',
'PASSWORD': '123456',
}
}
# Password validation
# https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.0/topics/i18n/
LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Chongqing'
# internationalization
USE_I18N = True
# localization
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.0/howto/static-files/
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
STATIC_URL = '/static/'
"""hellodjango URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from demo import views
urlpatterns = [
path('', views.home),
path('admin/', admin.site.urls),
]
"""
WSGI config for hellodjango project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/2.0/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "hellodjango.settings")
application = get_wsgi_application()
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "hellodjango.settings")
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
<!DOCTYPE html>
{% load staticfiles %}
<html lang="en">
<head>
<meta charset="UTF-8">
<title>讲师信息</title>
</head>
<body>
{% for x in teachers_list %}
<h1>{{ x.name }}老师 - {{ x.job }}</h1>
<p><strong>讲师简介</strong></p>
<p>{{ x.intro }}</p>
<p><strong>教学理念</strong></p>
<p>{{ x.motto }}</p>
<p>
{% if x.photo %}
<img src="{% static x.photo %}">
{% endif %}
</p>
<hr>
{% endfor %}
</body>
</html>
\ No newline at end of file
import pymysql
pymysql.install_as_MySQLdb()
from django.test import TestCase
# Create your tests here.
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册