django提供了两种对应关系。
FBV: function base view
CBV:class base view
views.py中就是使用的FBV。
def index(request):
return HttpResponse("Index")
def login(request):
if request.method == 'GET':
return render(request, 'login.html')
elif request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('pwd')
gender = request.POST.getlist('gender')
intrest = request.POST.getlist('intrest')
img1 = request.FILES.get('img1')
print img1
if username == 'a' and password == 'a':
return render(request, 'index.html')
else:
return render(request, 'login.html')
else:
return redirect('index/')
urls.py中使用:
from app01 import views as app01_v
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^index/', app01_v.index),
url(r'^login/', app01_v.login),
]
CBV的方式:
urls.py中:
调用类as_view() 方法(因为About是继承与View类的)。
from app01 import views as app01_v
urlpatterns = [
url(r'^about/', app01_v.About.as_view()),
]
views.py中:
class About(View):
def dispatch(self, request, *args, **kwargs):
#调用父类dispatch super这里调用的就是下面的get或者post
result = super(About, self).dispatch(request, *args, **kwargs)
return result
def get(self, request):
return render(request, 'about.html')
def post(self, request):
return render(request, 'about.html')