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 = ['*'] # 允许所有主机访问
相关推荐
huangkj-henan27 分钟前
DA217应用笔记
笔记
Young_2022020229 分钟前
学习笔记——KMP
笔记·学习
行然梦实1 小时前
学习日记_20241110_聚类方法(K-Means)
学习·kmeans·聚类
马船长1 小时前
制作图片木马
学习
秀儿还能再秀1 小时前
机器学习——简单线性回归、逻辑回归
笔记·python·学习·机器学习
WCF向光而行1 小时前
Getting accurate time estimates from your tea(从您的团队获得准确的时间估计)
笔记·学习
wang09072 小时前
工作和学习遇到的技术问题
学习
Li_0304063 小时前
Java第十四天(实训学习整理资料(十三)Java网络编程)
java·网络·笔记·学习·计算机网络
心怀梦想的咸鱼3 小时前
ue5 蓝图学习(一)结构体的使用
学习·ue5
Tttian6223 小时前
Vue全栈开发旅游网项目(11)-用户管理前端接口联调
前端·vue.js·django