django笔记

一、 项目所需要命令

1.镜像安装命令

pip3 install -i https://mirrors.aliyun.com/pypi/simple django==4.2.5

2.创建项目

django-admin startproject blog

3.运行项目

python manage.py runserver

4.创建子应用

python ../manage.py startapp user

5.生成迁移文件

python manage.py makemigrations 

6.执行迁移

python manage.py migrate

7.创建管理员账户

python manage.py createsuperuser

二、目录结构

在这里插入图片描述

三、settings

"""
Django settings for backend project.

Generated by 'django-admin startproject' using Django 3.2.4.

For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""

from pathlib import Path
import os
import sys

# Build paths inside the project like this: BASE_DIR / 'subdir'.
# BASE_DIR = Path(__file__).resolve().parent.parent
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
print(BASE_DIR)

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-l+hg)43b0u5(#@(c(@_f8&nf(4ln+(9d((kdw97jq1d(s)jk#u'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition
sys.path.insert(0, os.path.join(BASE_DIR, 'apps'))
INSTALLED_APPS = [
    'simpleui',
    # 系统的子应用
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    # 自定义的子应用
    'content.apps.ContentConfig',
    'user.apps.UserConfig',
    # 第三方的子应用
    'rest_framework',                           # drf
    'wangeditor',                               # 富文本编辑器

]

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',
]

ROOT_URLCONF = 'backend.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'backend.wsgi.application'


# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'HOST': '127.0.0.1',
        'PORT': 3306,  						# 数据库端口
        'USER': 'root',  					# 数据库用户名
        'PASSWORD': 'root',  				# 数据库用户密码
        'NAME': 'blog'  			# 数据库名字
    }
}


# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/

LANGUAGE_CODE = 'zh-Hans'

TIME_ZONE = 'Asia/Shanghai'

USE_I18N = True

USE_L10N = True

USE_TZ = False


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/

STATIC_URL = '/static/'

# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

'''在django认证系统中配置自定义的模型类'''
AUTH_USER_MODEL = 'user.User'  # 应用名.模型类名

四、models

user

from django.contrib.auth.models import AbstractUser
from django.db import models

'''用户模型类'''


class User(AbstractUser):
    # 手机号【必填、唯一】
    mobile = models.CharField(max_length=11, unique=True, verbose_name='手机号')

    # 头像
    avatar = models.CharField(max_length=255, blank=True,
                              default='https://lmg.jj20.com/up/allimg/4k/s/02/2109250006343S5-0-lp.jpg',
                              verbose_name='用户头像')

    # 个人签名
    signature = models.CharField(max_length=60, blank=True, null=True, verbose_name='个人签名')

    class Meta:
        db_table = 'tb_user'
        verbose_name = '01、用户'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.username

blog

from django.db import models
'''
文章类别表
'''


class Category(models.Model):
    name = models.CharField(max_length=20, verbose_name='类别名称')

    class Meta:
        db_table = 'tb_category'
        verbose_name = '01、文章类别'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name


'''文章表'''


class Article(models.Model):
    # 外键
    category_id = models.BigIntegerField(verbose_name='文章所属类别')
    author_id = models.BigIntegerField(verbose_name='文章所属作者')
    #
    title = models.CharField(max_length=30, verbose_name='标题')
    body = models.TextField(verbose_name='文章内容')
    create_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    modified_time = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        db_table = 'tb_article'
        verbose_name = '02、文章'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.title

五、 apps

user

from django.apps import AppConfig


class UserConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'user'
    verbose_name = 'A_用户管理'

blog

from django.apps import AppConfig


class ContentConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'content'
    verbose_name = 'B_内容管理'

六、admin

user

from django.contrib import admin

from user.models import User


@admin.register(User)
class UserAdmin(admin.ModelAdmin):
    list_display = [
        'id', 'username', 'mobile',  'signature',
        'last_login', 'date_joined',
        'avatar',
    ]

blog

from django.contrib import admin

from content.models import Category, Article


@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
    list_display = [
        'id', 'name',
    ]


@admin.register(Article)
class ArticleAdmin(admin.ModelAdmin):
    list_display = [
        'id', 'title', 'category_id', 'author_id', 'create_time', 'modified_time'
    ]

七、views

user

from django.shortcuts import render

# Create your views here.

blog

from django.db.models import Q
from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView

from content.models import Article


class ArticleAPIview(APIView):
    def get(self, request):
        # article_queryset = Article.objects.all().order_by('-id')
        # article_queryset = Article.objects.filter(category_id__gte=1) #__gte>=2;__gt>2;__lte<=2;__lt<2
        # article_queryset = Article.objects.filter(title='哈哈哈') #__gte>=2;__gt>2;__lte<=2;__lt<2
        # article_queryset = Article.objects.filter(Q(title='哈哈哈')|Q(title='嘿嘿嘿')|Q(title='呵呵呵'))
        # article_queryset = Article.objects.filter(title__in=['嘿嘿嘿', '哈哈哈'])
        # article_queryset = Article.objects.get(id=2)#查询到的对象
        # result_list = []
        # for article_obj in article_queryset:
        #     id = article_obj.id
        #     category_id = article_obj.category_id
        #     title = article_obj.title
        #     body = article_obj.body
        #     author = article_obj.author_id
        #     create_time = article_obj.create_time
        #     modified_time = article_obj.modified_time
        #     article_dict = {
        #         'id': id,
        #         'category_id': category_id,
        #         'body': body,
        #         'title': title,
        #         'author': author,
        #         'create_time': create_time,
        #         'modified_time': modified_time,
        #     }
        #     result_list.append(article_dict)
        #接收前端数据
        params = request.query_params #字典
        id = params.get('id')
        article_obj = Article.objects.get(id=id)  # 查询到的对象
        res = {
            'id': article_obj.id,
            'category_id': article_obj.category_id,
            'body': article_obj.body,
            'title': article_obj.title,
            'author_id': article_obj.author_id,
            'create_time': article_obj.create_time,
            'modified_time': article_obj.modified_time,
        }

        # return Response(res)
        return render(request, 'home.html', res)

八、url

项目urls

"""backend URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('content/', include('content.urls'))
]

user

hhh 

blog


from django.urls import path

from content.views import ArticleAPIview

urlpatterns = [
    path('article/', ArticleAPIview.as_view())
]

九、模板

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>博客</title>
</head>
<body>

    {% for k, v in res.items %}
       {{k}}: {{v}}
       {% endfor %}



</body>
</html>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值