当前位置: 首页 > news >正文

Django 5 学习笔记 2024版

1. 官方中文文档

Django 文档 | Django 文档 | Django (djangoproject.com)

2. 第一个应用 博客

总目录

 

<1>依赖安装:

pip install django

<2> 创建 工程 myapp

django-admin startproject myapp
cd myapp

<3>创建 应用 app

> python manage.py startapp app 

<4> 配置模型生成数据库表 

配置数据库: myapp/settings.py

对应文件: app/models.py

python manage.py makemigrations 
python manage.py migrate

<5> 配置文件\路由\视图

<6> 配置 后台

主要文件: app/admin.py

生成管理员账号:

python manage.py createsuperuser

账号:admin

邮箱:admin@qq.com

密码:abc123

<7> 运行服务器

python manage.py runserverpython manage.py runserver 0.0.0.0:8080

<8> 美化 后台页面

pip install django-simpleui

myapp/setting.py 

INSTALLED_APPS = ['simpleui', # 注意这里'django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles',...     
]

3. 文件参考例:

app/templates/app/post_list.html

<!DOCTYPE html>
<html>
<head><title>Blog</title>
{% load static %}<link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}">
</head>
<body><h1>博客</h1>{% for post in posts %}<div><h2><a href="{% url 'post_detail' pk=post.pk %}">{{ post.title }}</a></h2><p>{{ post.content|truncatewords:30 }}</p><p>{{post.f_name}} 发布于 </p></div>{% endfor %}<img  class="bd-placeholder-img" width="200" height="250" src="{{ post.icon2.url }}" alt="" srcset="">
</body>
</html>

app/templates/app/post_detail.html

<!DOCTYPE html>
<html>
<head><title>{{ post.title }}</title>
</head>
<body><img src="{{ post.image.url}}" alt="" srcset=""><h1>{{ post.title }}</h1><p>{{ post.content }}</p><p>Published: {{ post.created_at }}</p>
</body>
</html>

app/admin.py

# from django.contrib import admin# Register your models here.
from django.contrib import admin
from .models import Post, pru ,Netsite@admin.register(Post)
class PostAdmin(admin.ModelAdmin):list_display = ('title', 'author','other','created_at', 'updated_at', 'publish_date')class PruAdmin(admin.ModelAdmin):list_display = ('title','p_name', 'P_jg','p_sl')
admin.site.register(pru, PruAdmin)admin.site.site_header='BPC管理后台'
admin.site.site_title='BPC管理后台'
admin.site.index_title='BPC管理后台'class NetAdmin(admin.ModelAdmin):list_display = ('title', 'content')admin.site.register(Netsite, NetAdmin) 

 

app/models.py

# from django.db import models# Create your models here.
from django.db import modelsclass Post(models.Model):title = models.CharField(max_length=200 , verbose_name="标题" )author = models.CharField(max_length=100, verbose_name="作者", default="匿名") # 添加作者字段other = models.CharField(max_length=100, verbose_name="另外", default="other") # 添加作者字段content = models.TextField()# f_name = models.CharField("客户姓名", max_length=30)created_at = models.DateTimeField(auto_now_add=True)updated_at = models.DateTimeField(auto_now=True)publish_date = models.DateField(null=True)icon = models.FileField(upload_to='blog\static\img', null=True)# icon2 = models.ImageField(upload_to='media/', null=True)icon2 = models.ImageField(default='bank.png', blank=True)class pru(models.Model):title = models.CharField(max_length=200 , verbose_name="标题", default="标题")p_name = models.CharField(max_length=200 , verbose_name="名字")P_jg = models.CharField(max_length=100, verbose_name="价格", default="20") # 添加作者字段p_sl = models.CharField(max_length=100, verbose_name="数量", default="1") # 添加作者字段content = models.TextField()    def __str__(self):return self.titleclass Netsite(models.Model):title = models.CharField(max_length=200 , verbose_name="标题", default="标题")content = models.TextField( verbose_name="内容", default="http://")

app/urls.py

from django.urls import path
from . import viewsurlpatterns = [path('', views.post_index, name='post_index'),path('', views.post_list, name='post_list'),path('post/<int:pk>/', views.post_detail, name='post_detail'),
]

app/views.py

# from django.shortcuts import render# Create your views here.
from django.shortcuts import render
from .models import Post, pru , Netsitedef post_index(request):posts = Post.objects.all()Netsites = Netsite.objects.all()return render(request, 'app/index.html', {'posts': posts, 'Netsites': Netsites})def post_list(request):posts = Post.objects.all()return render(request, 'app/post_list.html', {'posts': posts})def pru_list(request):prus = pru.objects.all()return render(request, 'app/post_list.html', {'prus': prus})def post_detail(request, pk):post = Post.objects.get(pk=pk)return render(request, 'app/post_detail.html', {'post': post})

myapp/settings.py

# Application definitionINSTALLED_APPS = ['simpleui', # 管理后台'django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles','app',
]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',
]ALLOWED_HOSTS = ['*'] # 允许所有主机访问# Internationalization
# https://docs.djangoproject.com/en/5.1/topics/i18n/LANGUAGE_CODE = 'zh-hans'  # 中文,简体
TIME_ZONE = 'Asia/Shanghai'  # 中国标准时间# LANGUAGE_CODE = 'en-us'# TIME_ZONE = 'UTC'USE_I18N = TrueUSE_TZ = True# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/5.1/howto/static-files/STATIC_URL = 'static/'
STATIC_DIR = [os.path.join(BASE_DIR, 'static')]MEDIA_URL = 'media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')# Default primary key field type
# https://docs.djangoproject.com/en/5.1/ref/settings/#default-auto-fieldDEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'# 隐藏右侧SimpleUI广告链接和使用分析
SIMPLEUI_HOME_INFO = False 
SIMPLEUI_ANALYSIS = False 

myapp/urls.py

from django.contrib import admin
from django.urls import include, path
from django.conf import settings
from django.conf.urls.static import staticurlpatterns = [path('admin/', admin.site.urls),path('app/', include('app.urls')),path('', include('app.urls')),
] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


http://www.mrgr.cn/news/30006.html

相关文章:

  • go语言使用总结(持续更新)
  • NoETL
  • 【go从零单排】XML序列化和反序列化
  • Kafka新节点加入集群操作指南
  • PICO+Unity MR空间网格
  • go语言 分布式一致
  • Python日志模块全面指南:如何高效记录与管理日志
  • 【最佳实践】优雅地处理 Java 中的空指针
  • 阿里通义千问开源Qwen2.5系列模型:Qwen2-VL-72B媲美GPT-4
  • 【Finetune】(二)、transformers之Prompt-Tuning微调
  • 配网缺陷检测无人机航拍图像数据集(不规范绑扎,螺栓销钉缺失)数据集总共3000张左右,标注为voc格式
  • QT开发:深入详解QtCore模块事件处理,一文学懂QT 事件循环与处理机制
  • Mysql系列-索引优化
  • 鸿萌数据恢复服务: 修复 Windows, Mac, 手机中 “SD 卡无法读取”错误
  • 鹏哥C语言43---函数的嵌套调用和链式访问
  • 73、Python之函数式编程:“一行流”大全,人生苦短,我用Python
  • scanf()函数的介绍及基础用法
  • Ubuntu LLaMA-Factory实战
  • 全新 HLOB 模型:预测限价订单簿中间价格变化方向的利器
  • Qt窗口——QToolBar
  • C++map,set,multiset,multimap详细介绍
  • 基于Jeecgboot3.6.3的flowable流程增加任务节点操作按钮的控制(一)
  • 【pytorch学习笔记,利用Anaconda安装pytorch和paddle深度学习环境+pycharm安装---免额外安装CUDA和cudnn】
  • Spring Boot中的响应与分层解耦架构
  • 如何兼容性地开发响应式站点——WEB开发系列40
  • ‍♀️焦虑症患者的救赎之路:这5项运动让你重拾宁静与力量!