【Django】前端界面显示(FBV、CBV两种方式)
在编写页面显示的代码前应当先拆分页面静态文件(css,js,images)放入static,html放入templates之下。
其中静态文件放入static分为以下两种情况:
- 放在对应的app下(不需要配置settings.py的STATICFILES_DIRS )
- 放到全局的templates和static之下(需要配置settings.py的STATICFILES_DIRS)
Django是一个遵循MTV设计模式的框架。MTV是Model、Template、View三个单词的简写,分别代表模型、模版、视图,其中视图层的编写方式分为FBV(基于函数的视图)和CBV(基于类的视图),下面的内容将分为FBV和CBV两个版本:
1 FBV-基于函数的视图版本
-
编写对应app的views逻辑
# <project>/apps/<app>/views.py from django.http import HttpResponse from django.shortcuts import render def message_form(request): return render(request, "message_form.html")
-
app目录下新建一个urls.py,编写当前app视图的路由
# <project>/apps/<app>/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.message_form), # 当前app的专属urls配置文件 ]
-
配置项目同名目录下的urls.py
# <project>/<project>/urls.py from django.contrib import admin from django.urls import include, path urlpatterns = [ path("message_form/", include("apps.message_form.urls")), # 引入新的urls配置文件 path('admin/', admin.site.urls), ]
-
最后访问http://127.0.0.1:8000/message_form/即可查看该网页
2 CBV-基于类的视图版本
-
编写对应app的views逻辑
# <project>/apps/<app>/views.py from django.shortcuts import render from django.views.generic.base import View class LoginView(View): def get(self, request, *args, **kwargs): return render(request, "login.html") def post(self, request, *args, **kwargs): pass
-
app目录下新建一个urls.py,编写当前app视图的路由
# <project>/apps/<app>/urls.py from django.urls import path from . import views urlpatterns = [ path('login/', views.LoginView.as_view(), name="login"), # 当前app的专属urls配置文件 ]
-
配置项目同名目录下的urls.py
# <project>/<project>/urls.py from django.contrib import admin from xadmin.plugins import xversion from django.urls import path, include import xadmin from django.views.generic import TemplateView from apps.users.views import LoginView xversion.register_models() xadmin.autodiscover() urlpatterns = [ # path('admin/', admin.site.urls), path('xadmin/', xadmin.site.urls), path("", include("apps.users.urls")), # 引入新的urls配置文件 ]