1. 程式人生 > 實用技巧 >後臺主頁模組設計

後臺主頁模組設計

一. 建立home模組#

Copy
# 前提:在 luffy 虛擬環境下

# 1.終端從專案根目錄進入apps目錄
cd luffyapi & cd apps

# 2.建立app
python ../../manage.py startapp home

二. 路由分發#

1. 主路由:luffyapi/urls.py#

Copy
from django.urls import path, re_path, include
urlpatterns = [
	# ...
    path('home/', include('home.urls')),
    # ...
]

2. 子路由:home/urls.py#

Copy
from django.urls import path, re_path
urlpatterns = [

]

三. Banner資料表model設計#

1. utils/model.py#

Copy
from django.db import models

class BaseModel(models.Model):
    created_time = models.DateTimeField(auto_now_add=True, verbose_name='建立時間')
    updated_time = models.DateTimeField(auto_now=True
, verbose_npython is_delete = models.BooleanField(default=False, verbose_name='是否刪除') is_show = models.BooleanField(default=True, verbose_name='是否上架') orders = models.IntegerField(verbose_name='優先順序') class Meta: abstract = True

2. home/models.py#

Copy
from django.db import models
from
utils.model import BaseModel class Banner(BaseModel): title = models.CharField(max_length=16, unique=True, verbose_name='名稱') image = models.ImageField(upload_to='banner', verbose_name='圖片') link = models.CharField(max_length=64, verbose_name='跳轉連結') info = models.TextField(verbose_name='詳情') # 也可以用詳情表,寬高出處 class Meta: db_table = 'luffy_banner' verbose_name_plural = '輪播圖表' def __str__(self): return self.title

3. 資料遷移:在大luffyapi路徑下的終端#

Copy
python manage.py makemigrations
python manage.py migrate

三. 註冊home模組:dev.py#

Copy
INSTALLED_APPS = [
    'rest_framework',
    'home',
]

四. 設計Banner資料介面#

1. home/serializers.py#

Copy
from rest_framework import serializers
from . import models
class BannerSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Banner
        fields = ['title', 'image', 'link']

2. home/views.py#

Copy
from rest_framework.viewsets import ModelViewSet
from rest_framework import mixins
from . import models, serializers

class BannerViewSet(ModelViewSet, mixins.ListModelMixin):
    queryset = models.Banner.objects.filter(is_delete=False, is_show=True).all()
    serializer_class = serializers.BannerSerializer

3. home/urls.py#

Copy
from django.urls import path, include
from utils.router import router
from . import views
# 註冊ViewSet的路由
router.register('banners', views.BannerViewSet, 'banner')

urlpatterns = [
    path('', include(router.urls)),
]

4. 介面#

Copy
http://localhost:8000/home/banners/python