学习django过程杂记

这里记的都是django学习过程中容易犯的错误以及随手敲的代码

2019年11月05日

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#views.py
from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse,JsonResponse
from django.shortcuts import render
from django.db import connection


def index(request):
try:
with connection.cursor() as cursor:
cursor.execute("select id,name,stick from info1")
rows = cursor.fetchall()
except Exception as e:
print(e)
return JsonResponse({
'data': []
})

# 遍历查询到的数据
if not rows:
return JsonResponse({
'data': []
})
data = []
for row in rows:
data.append({
'id': row[0],
'name': row[1],
'isstick': row[2]
})
print(data)

return JsonResponse({
'data': data
})

2019年11月06日

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# views.py
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from .models import Student
from teacher.models import Teacher


def student_list(request):
students = list(Student.objects.all().values())
print(students)
students1 = Student.objects.filter(name='张三').first() # [0] # .first()
print(students1)
return JsonResponse('success', safe=False)


def add_student(request):
students = Student.objects.create(name='三德子', number=1,teacher=Teacher.objects.get(id=1))
print(students)
return JsonResponse({
'result': students.id
})


def delete_student(request):
students = Student.objects.filter(pk=1)
result = students.delete()
print(result)
return JsonResponse({})

2019年11月07日

1
2
3
4
5
6
7
8
9
10
11
12
#student.urls
__author__ = 'bbsh4'

from django.urls import path
from student import views as student_views

urlpatterns = [
path('student_list/', student_views.student_list, name='student'),
path('add_student/', student_views.add_student, name='add_student'),
path('delete_student/', student_views.delete_student, name='delete_student'),
]

类视图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#urls.py
from django.urls import path, include
from . import views
from management import views as management_views
from django.views.generic import TemplateView

urlpatterns = [
path('chunjingtai_page/', TemplateView.as_view(template_name='chunjingtai_page.html')), # 纯静态模板
path('', management_views.to_redirect), # 重定向
path('index/', management_views.HomePageView.as_view(), name='home_page'), # 模板视图
path('login/', management_views.LoginPageView.as_view()),
path('signup/', management_views.SignupPageView.as_view()),
path('upload/', management_views.UploadFiles.as_view()),

path('api/login/', management_views.LoginView.as_view()), # 登录接口
path('api/signup/', management_views.SignupView.as_view()), # 注册接口
]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from django.views import View
from django.core.files.storage import default_storage
from django.shortcuts import reverse, redirect
from django.views.generic import TemplateView
from .models import User
from django.contrib.auth import authenticate,login
from django.contrib.auth.decorators import login_required # 装饰器
from django.utils.decorators import method_decorator # 给类视图添加装饰器

class HomePageView(TemplateView): # 首页
template_name = "index.html"

def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['param'] = 'param'
users = User.objects.all()
context['users'] = users
return context


class SignupPageView(TemplateView): # 注册
template_name = "signup.html"


class LoginPageView(TemplateView): # 登录
template_name = "login.html"


def to_redirect(request): # 重定向
return redirect(reverse('home_page'))


class UploadFiles(View): # 上传文件
def post(self, request):
file = request.FILES.get('img')
path = default_storage.save("/static/photo/{}/".format(file.name), file)
print(path)
return JsonResponse({
"status_code": 200,
'path': path
})


class LoginView(View):

def get(self, request):
return HttpResponse('login-get')

def post(self, request):
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username=username, password=password)
print(user)
if user:
login(request, user)
return JsonResponse({
"status_code": 200,
"msg": "登陆成功"
})
else:
return JsonResponse({
"status_code": 201,
"msg": "登陆失败"
})


class SignupView(View):

def post(self, request):
username = request.POST.get('username')
password = request.POST.get('password')
if not username:
return JsonResponse({
"status_code": 201,
"msg": "username不能为空"
})
if not password:
return JsonResponse({
"status_code": 201,
"msg": "password不能为空"
})
try:
user = User.objects.create_user(username=username, password=password)
if user:
print(user)
return JsonResponse({
"status_code": 200,
"msg": "注册成功"
})
except Exception as e:
return JsonResponse({
"status_code": 200,
"msg": str(e)
})