django获取用户数据方法及FBV和CBV

获取用户数据

FBV:function base views
CBV:class base views
定义类时,获得用户请求时,会自动调用父类View的dispath方法。
所以可以让自定义类继承父类dispath方法,这样可以自我定义一些功能。
url.py

from django.contrib import admin
from django.urls import path
from cmdb import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('index/', views.index),
    path('login/', views.login),
    path('home/', views.Home.as_view()),

]

app下的view.py

from django.shortcuts import render, HttpResponse


# Create your views here.


def index(request):
    return HttpResponse('

index

') def login(request): if request.method == 'GET': return render(request, 'login.html') elif request.method == 'POST': v = request.POST.get('gender') print(v) user = request.POST.get('user') pwd = request.POST.get('pwd') print(user, pwd) love = request.POST.getlist('love') print(love) city = request.POST.getlist('city') print(city) file = request.FILES.get('file') print(file, type(file)) import os file_path = os.path.join('upload', file.name) f = open(file_path, 'wb') # from django.core.files.uploadedfile import InMemoryUploadedFile for content in file.chunks(): f.write(content) f.close() return render(request, 'login.html') else: pass from django.views import View class Home(View): def dispatch(self, request, *args, **kwargs): print('before') result = super(Home, self).dispatch(request, *args, **kwargs) print('after') return result def get(self, request): print('method:', request.method) return HttpResponse('ok') def post(self, request): pass

前端.html




    
    Title


    

男: 女:

篮球: 足球: 棒球:

路由系统

from django.urls import path, re_path
urlpatterns = [
    re_path('index/(\d+)/(\d+)/', views.index, name='index'),
    re_path('detail-(?P\d+)-(?P\d+).html/', views.detail, name='detail'),
]

def index(request, *args, **kwargs):
    print(*args, **kwargs)
    print(request.path_info)
    url = reverse('index', args=(1, 2))
    print('url:', url)
    return render(request, 'index.html', {'user_dict': USER_DICT})

路由分发

在django中创建多个app时,为了有效的分类url
工程名目录下urls.py

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

在app下创建urls.py

from django.conf.urls import url,include
from django.contrib import admin
from app02 import views

urlpatterns = [
                url(r'^login/', views.login),
            ]

你可能感兴趣的:(django获取用户数据方法及FBV和CBV)