虽然django的MTV模式简化了编码,但在很多情况下,不能简单使用MTV模式解决问题。
这就用到例外两种模式CBV(class base views)与FBV(function base views)
一. FBV
url.py
from django.conf.urls import url
from mytest import views
urlpatterns = [
url(r'^auth', views.auth),
]
view.py
from django.shortcuts import render
def auth(req):
if req.method == 'POST':
def get(self, request, *args, **kwargs):
result = {
'status': True,
'data': 'response data'
}
return JsonResponse(result, status=200)
elif req.method == 'GET':
result = {
'status': True,
'data': 'response data'
}
return render(req, 'auth.html')
auth.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>auth</title>
</head>
<body>
<form action="" method="post">
<input type="text" name="username" />
<input type="text" name="password" />
<input type="submit" name="submit" value="提交" />
</form>
</body>
</html>
二. CBV
url.py
from mytest import views
urlpatterns = [
url(r'^auth', views.Auth.as_view()),
]
view.py
from django.views import View
class Auth(View):
def get(self, request, *args, **kwargs):
result = {
'status': True,
'data': 'response data'
}
return JsonResponse(result, status=200)
def post(self, request, *args, **kwargs):
result = {
'status': True,
'data': 'response data'
}
return JsonResponse(result, status=200)