Django 5 学习笔记 2024版

1. 官方中文文档

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

2. 第一个应用 博客

总目录

<1>依赖安装:

python 复制代码
pip install django

<2> 创建 工程 myapp

python 复制代码
django-admin startproject myapp
cd myapp

<3>创建 应用 app

python 复制代码
> python manage.py startapp app 

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

配置数据库: myapp/settings.py

对应文件: app/models.py

python 复制代码
python manage.py makemigrations 
python manage.py migrate

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

<6> 配置 后台

主要文件: app/admin.py

生成管理员账号:

python 复制代码
python manage.py createsuperuser

账号:admin

邮箱:admin@qq.com

密码:abc123

<7> 运行服务器

python 复制代码
python manage.py runserver

python manage.py runserver 0.0.0.0:8080

<8> 美化 后台页面

python 复制代码
pip install django-simpleui

myapp/setting.py

python 复制代码
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

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

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

python 复制代码
# 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

python 复制代码
# 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

python 复制代码
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

python 复制代码
# 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

python 复制代码
# 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',
]

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 = 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

python 复制代码
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)

4. 关于设置中文显示参考

app/models.py

python 复制代码
# 订单表
class Order(models.Model):
    id = models.AutoField(primary_key=True)
    customer_name = models.CharField(max_length=255 ,verbose_name = "订单")
    customer_phone = models.CharField(max_length=20)
    payment_method = models.CharField(max_length=50)
    payment_status = models.BooleanField(default=False)
    date = models.DateField()
    operator = models.CharField(max_length=100)
    verbose_name = "订单"
    class Meta:
        verbose_name = '订单表'
        verbose_name_plural = verbose_name

# 订单详情表
class OrderDetail(models.Model):
    serial_number = models.AutoField(primary_key=True)
    order_id = models.ForeignKey(Order, on_delete=models.CASCADE)
    product = models.CharField(max_length=255)
    quantity = models.IntegerField()
    class Meta:
        verbose_name = '订单详情表'
        verbose_name_plural = verbose_name

app/app.py

python 复制代码
from django.apps import AppConfig


class BlogConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'blog'
    verbose_name = '博客'

myapp/settings.py

python 复制代码
LANGUAGE_CODE = 'zh-hans'  # 中文,简体
TIME_ZONE = 'Asia/Shanghai'  # 中国标准时间

ALLOWED_HOSTS = ['*'] # 允许所有主机访问
相关推荐
Rinai_R3 分钟前
计算机组成原理的学习笔记(7)-- 存储器·其二 容量扩展/多模块存储系统/外存/Cache/虚拟存储器
笔记·物联网·学习
吃着火锅x唱着歌3 分钟前
PHP7内核剖析 学习笔记 第四章 内存管理(1)
android·笔记·学习
ragnwang5 分钟前
C++ Eigen常见的高级用法 [学习笔记]
c++·笔记·学习
胡西风_foxww1 小时前
【es6复习笔记】rest参数(7)
前端·笔记·es6·参数·rest
Web阿成2 小时前
3.学习webpack配置 尝试打包ts文件
前端·学习·webpack·typescript
雷神乐乐2 小时前
Spring学习(一)——Sping-XML
java·学习·spring
李雨非-19期-河北工职大2 小时前
思考: 与人交际
学习
哦哦~9212 小时前
深度学习驱动的油气开发技术与应用
大数据·人工智能·深度学习·学习
小木_.3 小时前
【python 逆向分析某有道翻译】分析有道翻译公开的密文内容,webpack类型,全程扣代码,最后实现接口调用翻译,仅供学习参考
javascript·python·学习·webpack·分享·逆向分析