首页 > 编程 > Python > 正文

Django开发的简易留言板案例详解

2020-02-15 23:55:27
字体:
来源:转载
供稿:网友

本文实例讲述了Django开发的简易留言板。分享给大家供大家参考,具体如下:

Django在线留言板小练习

环境

ubuntu16.04 + python3 + django1.11

1、创建项目

django-admin.py startproject message

进入项目message

2、创建APP

python manager.py startapp guestbook

项目结构

.
├── guestbook
│   ├── admin.py
│   ├── apps.py
│   ├── __init__.py
│   ├── migrations
│   │   └── __init__.py
│   ├── models.py
│   ├── tests.py
│   └── views.py
├── manage.py
└── message
    ├── __init__.py
    ├── __pycache__
    │   ├── __init__.cpython-35.pyc
    │   └── settings.cpython-35.pyc
    ├── settings.py
    ├── urls.py
    └── wsgi.py

4 directories, 14 files

需要做的事:

配置项目setting 、初始化数据库、配置url 、编写views 、创建HTML文件

项目配置

打开message/settings.py

设置哪些主机可以访问,*代表所有主机

ALLOWED_HOSTS = ["*"]INSTALLED_APPS = [  'django.contrib.admin',  'django.contrib.auth',  'django.contrib.contenttypes',  'django.contrib.sessions',  'django.contrib.messages',  'django.contrib.staticfiles',  'guestbook',  #刚刚创建的APP,加入到此项目中]#数据库默认用sqlite3,后期可以换成MySQL或者SQL Server等TIME_ZONE = 'PRC' #时区设置为中国

创建数据库字段

#encoding: utf-8from django.db import modelsclass Message(models.Model):  username=models.CharField(max_length=256)  title=models.CharField(max_length=512)  content=models.TextField(max_length=256)  publish=models.DateTimeField()  #为了显示  def __str__(self):    tpl = '<Message:[username={username}, title={title}, content={content}, publish={publish}]>'    return tpl.format(username=self.username, title=self.title, content=self.content, publish=self.publish)

初始化数据库

# 1. 创建更改的文件root@python:/online/message# python3 manage.py makemigrationsMigrations for 'guestbook': guestbook/migrations/0001_initial.py  - Create model Message# 2. 将生成的py文件应用到数据库root@python:/online/message# python3 manage.py migrateOperations to perform: Apply all migrations: admin, auth, contenttypes, guestbook, sessionsRunning migrations: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying guestbook.0001_initial... OK Applying sessions.0001_initial... OK            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表