欢迎阅读!

潇湘夜雨

当前位置: 主页 > 软件与服务 >

python django框架入门

时间:2018-05-15 15:05来源:未知 作者:华嵩阳 点击:
一、环境准备 # 创建并激活虚拟环境(Windows使用`python -m venv venv`,不需要虚拟环境可以忽略) python3 -m venv venv source venv/bin/activate # 安装Django pip install django 二、创建项目和应用 django-
一、环境准备
 
# 创建并激活虚拟环境(Windows使用`python -m venv venv`,不需要虚拟环境可以忽略)
python3 -m venv venv
source venv/bin/activate
 
# 安装Django
pip install django
 
二、创建项目和应用
 
django-admin startproject mysite
cd mysite
 
 
$ find
.
./manage.py
./mysite
./mysite/asgi.py
./mysite/settings.py
./mysite/urls.py
./mysite/wsgi.py
./mysite/__init__.py
目录说明
manage.py:一个命令行工具,可以使你用多种方式对Django项目进行交互
内层的目录:项目的真正的Python包
_init _.py:一个空文件,它告诉Python这个目录应该被看做一个Python包
settings.py:项目的配置
urls.py:项目的URL声明
wsgi.py:项目与WSGI兼容的Web服务器入口
 
python manage.py startapp blog
$ ls
blog/  manage.py*  mysite/
$ find blog
blog
blog/admin.py
blog/apps.py
blog/migrations
blog/migrations/__init__.py
blog/models.py
blog/tests.py
blog/views.py
blog/__init__.py
 
 
三、配置项目设置(mysite/settings.py)
 
INSTALLED_APPS = [
    ...
    'blog.apps.BlogConfig',  # 添加新创建的应用
]
 
# 数据库配置(默认使用SQLite)
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}
 
# 设置中文
LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Shanghai'
四、创建数据模型(blog/models.py)
 
from django.db import models
from django.contrib.auth.models import User
 
class Article(models.Model):
    title = models.CharField("标题", max_length=200)
    content = models.TextField("内容")
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)
 
    def __str__(self):
        return self.title
 
class Comment(models.Model):
    article = models.ForeignKey(Article, on_delete=models.CASCADE)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    content = models.TextField("评论内容")
    created_at = models.DateTimeField(auto_now_add=True)
五、数据库迁移
 
python manage.py makemigrations
python manage.py migrate
 
 
$ python39 manage.py makemigrations
Migrations for 'blog':
  blog\migrations\0001_initial.py
    - Create model Article
    - Create model Comment
 
 
$ python39 manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, blog, contenttypes, sessions
Running 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 admin.0003_logentry_add_action_flag_choices... 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 auth.0009_alter_user_last_name_max_length... OK
  Applying auth.0010_alter_group_name_max_length... OK
  Applying auth.0011_update_proxy_permissions... OK
  Applying auth.0012_alter_user_first_name_max_length... OK
  Applying blog.0001_initial... OK
  Applying sessions.0001_initial... OK
 
 
$ ls -lht
total 157K
-rw-r--r-- 1 lzh 197121 148K 3月  31 21:47 db.sqlite3
drwxr-xr-x 1 lzh 197121    0 3月  31 21:46 blog/
drwxr-xr-x 1 lzh 197121    0 3月  31 21:45 mysite/
-rwxr-xr-x 1 lzh 197121  684 3月  31 20:35 manage.py*
 
 
# 创建超级用户
python manage.py createsuperuser
 
 
$ python39 manage.py createsuperuser
Superuser creation skipped due to not running in a TTY. You can run `manage.py createsuperuser` in your project to create one manually.
需在cmd命令下执行:
Username (leave blank to use 'lzh'): admin
Email address: test@django.cn
Password:
Password (again):
This password is too short. It must contain at least 8 characters.
This password is too common.
This password is entirely numeric.
Bypass password validation and create user anyway? [y/N]: y
Superuser created successfully.
 
六、配置管理后台(blog/admin.py)
 
from django.contrib import admin
from .models import Article, Comment
 
class ArticleAdmin(admin.ModelAdmin):
    list_display = ('title', 'author', 'created_at')
 
class CommentAdmin(admin.ModelAdmin):
    list_display = ('article', 'user', 'created_at')
 
admin.site.register(Article, ArticleAdmin)
admin.site.register(Comment, CommentAdmin)
七、配置URL路由(mysite/urls.py)
 
from django.contrib import admin
from django.urls import path, include
 
urlpatterns = [
    path('admin/', admin.site.urls),
    path('blog/', include('blog.urls')),
]
八、创建视图和模板
创建视图(blog/views.py)
 
from django.shortcuts import render
from .models import Article
 
def article_list(request):
    articles = Article.objects.all()
    return render(request, 'blog/article_list.html', {'articles': articles})
创建应用路由(blog/urls.py)
 
from django.urls import path
from . import views
 
urlpatterns = [
    path('', views.article_list, name='article_list'),
]
在blog下创建模板目录和文件(templates/blog/article_list.html)
<!DOCTYPE html>
<html>
<head>
    <title>文章列表</title>
</head>
<body>
    <h1>所有文章</h1>
    <ul>
        {% for article in articles %}
        <li>
            <h3>{{ article.title }}</h3>
            <p>作者:{{ article.author.username }}</p>
            <p>{{ article.content|truncatechars:100 }}</p>
            <small>{{ article.created_at }}</small>
        </li>
        {% endfor %}
    </ul>
</body>
</html>
 
九、启动开发服务器
 
python manage.py runserver
 
$ python39 manage.py runserver
Watching for file changes with StatReloader
Performing system checks...
 
System check identified no issues (0 silenced).
March 31, 2025 - 22:00:13
Django version 4.2.20, using settings 'mysite.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
 
 
访问以下地址验证:
 
管理后台:http://127.0.0.1:8000/admin
文章列表:http://127.0.0.1:8000/blog
 
$ python39 manage.py runserver
Watching for file changes with StatReloader
Performing system checks...
 
System check identified no issues (0 silenced).
March 31, 2025 - 22:29:20
Django version 4.2.20, using settings 'mysite.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
 
[31/Mar/2025 22:29:28] "GET /admin/ HTTP/1.1" 200 6614
[31/Mar/2025 22:29:30] "GET /admin/ HTTP/1.1" 200 6614
Not Found: /
[31/Mar/2025 22:29:37] "GET / HTTP/1.1" 404 2164
[31/Mar/2025 22:29:41] "GET /admin/ HTTP/1.1" 200 6614
[31/Mar/2025 22:29:43] "GET /blog/ HTTP/1.1" 200 163
 
十、扩展建议
添加Bootstrap样式:
vim blog/templates/blog/article_detail.html
如果模板找不到,需配置模板路径:
修改settings.py文件,设置TEMPLATES的DIRS值
'DIRS': [os.path.join(BASE_DIR,'templates')],
 
<link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.2.3/css/bootstrap.min.css" rel="stylesheet">
添加文章详情页:
 
# views.py
def article_detail(request, pk):
    article = Article.objects.get(pk=pk)
    return render(request, 'blog/article_detail.html', {'article': article})
 
# urls.py
path('<int:pk>/', views.article_detail, name='article_detail')
 
 
访问:http://127.0.0.1:8000/blog/1/
 
添加表单提交功能:
 
# forms.py
from django import forms
from .models import Comment
 
class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = ['content']
项目结构说明
text
Copy Code
mysite/
├── blog/
│   ├── migrations/
│   ├── templates/
│   │   └── blog/
│   ├── __init__.py
│   ├── admin.py
│   ├── apps.py
│   ├── models.py
│   ├── tests.py
│   ├── views.py
│   └── urls.py
├── mysite/
│   ├── __init__.py
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
└── manage.py
这个系统已包含:
 
用户认证系统(Django自带)
文章管理功能
评论系统基础框架
管理后台界面
基本的前端展示
后续可通过以下方式增强:
 
添加用户注册/登录功能
实现评论提交功能
增加分页组件
添加富文本编辑器
部署到生产环境(Nginx + Gunicorn)
 
(责任编辑:liangzh)
织梦二维码生成器
顶一下
(0)
0%
踩一下
(0)
0%
------分隔线----------------------------
栏目列表
推荐内容