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 runserver
python 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 models
class 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.title
class 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 views
urlpatterns = [
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 , Netsite
def 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 definition
INSTALLED_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',
]
# 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 = True
USE_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-field
DEFAULT_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 static
urlpatterns = [
path('admin/', admin.site.urls),
path('app/', include('app.urls')),
path('', include('app.urls')),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)