Django 入门指南

在Django中创建一个简单的博客应用程序,你需要遵循以下步骤:

  1. 创建一个新的应用程序。
  2. 定义模型以存储博客数据。
  3. 创建管理员用户。
  4. 创建一个视图来显示博客文章。
  5. 创建一个URL配置。
  6. 创建一个简单的模板。

以下是具体的代码示例:




# 在你的Django项目的根目录下运行这个命令来创建一个新的应用程序
python manage.py startapp blog

blog/models.py 文件中定义模型:




from django.db import models
from django.contrib.auth.models import User
 
class Post(models.Model):
    title = models.CharField(max_length=200)
    content = models.TextField()
    pub_date = models.DateTimeField('date published')
    author = models.ForeignKey(User, on_delete=models.CASCADE)
 
    def __str__(self):
        return self.title

blog/admin.py 文件中注册模型,以便可以通过管理员界面进行管理:




from django.contrib import admin
from .models import Post
 
admin.site.register(Post)

blog/views.py 文件中创建一个视图来显示所有博客文章:




from django.shortcuts import render
from .models import Post
 
def post_list(request):
    posts = Post.objects.all()
    return render(request, 'blog/post_list.html', {'posts': posts})

blog/urls.py 文件中创建URL配置:




from django.urls import path
from .views import post_list
 
urlpatterns = [
    path('', post_list, name='post_list'),
]

blog/templates/blog/post_list.html 文件中创建一个简单的模板:




<!DOCTYPE html>
<html>
<head>
    <title>Blog Posts</title>
</head>
<body>
    <h1>Blog Posts</h1>
    <ul>
        {% for post in posts %}
        <li>
            <a href="{{ post.get_absolute_url }}">{{ post.title }}</a>
        </li>
        {% empty %}
        <li>No posts available.</li>
        {% endfor %}
    </ul>
</body>
</html>

确保你已经在项目的 settings.py 文件中添加了 blog 应用程序:




INSTALLED_APPS = [
    # ...
    'blog.apps.BlogConfig',
    # ...
]

现在你可以运行开发服务器并查看博客文章列表:




python manage.py runserver

在浏览器中访问 http://127.0.0.1:8000/ 查看博客文章列表。

评论已关闭

推荐阅读

Vue中使用mind-map实现在线思维导图
2024年08月04日
VUE
Web前端最全Vue实现免密登录跳转的方式_vue怎么样不登录返回首页,最强技术实现
2024年08月04日
VUE
vue3 项目搭建教程(基于create-vue,vite,Vite + Vue)
2024年08月04日
VUE
Vue-颜色选择器实现方案——>Vue-Color( 实战*1+ Demo*7)
2024年08月04日
VUE
Vue项目卡顿慢加载?这些优化技巧告诉你!_vue数据多渲染卡顿
2024年08月04日
VUE
vue中的keep-alive详解与应用场景
2024年08月04日
VUE
Vue、React实现excel导出功能(三种实现方式保姆级讲解)
2024年08月04日
vue-office/docx插件实现docx文件预览
2024年08月04日
VUE
java调用js文件的两种方法(支持V8引擎)
2024年08月04日
JavaScript:解决计算精度问题/mathjs/bignumber.js/big.js/decimal.js
2024年08月04日
两周从爬虫小白变大神 _yjs_js_security_passport
2024年08月04日
JS笔记(对象、函数、数组)
2024年08月04日
Markdown.js:强大的纯JavaScript Markdown解析器
2024年08月04日
Vue项目:js模拟点击a标签下载文件并重命名,URL文件地址下载方法、请求接口下载文件方法总结。
2024年08月04日
vue 父组件怎么获取子组件里面的data数据
2024年08月04日
VUE
个人开发实现AI套壳网站快速搭建(Vue+elementUI+SpringBoot)
2024年08月04日
el-table 表格封装并改造实现单元格可编辑
2024年08月04日
none
nodejs环境下创建vue项目、SSH密钥登陆!!!
2024年08月04日
vue+quill+element-ui实现视频、图片上传及缩放保姆级教程,轻松使用富文本
2024年08月04日
【three.js】22. Imported Models导入模型
2024年08月04日