Python-100-Days/Day41-55/code/hellodjango/demo/views.py

74 lines
2.4 KiB
Python
Raw Normal View History

2018-07-04 16:47:48 +08:00
import json
from django.http import HttpResponse
2018-07-05 16:54:15 +08:00
from django.shortcuts import render, redirect
2018-07-03 16:09:38 +08:00
2018-07-05 16:54:15 +08:00
from demo.forms import UserForm
from demo.models import Subject, Teacher, User, proto
2018-07-04 16:47:48 +08:00
2018-07-05 16:54:15 +08:00
def login(request):
if request.method.lower() == 'get':
return render(request, 'demo/login.html', {})
else:
username = request.POST['username']
try:
user = User.objects.get(username__exact=username)
password = request.POST['password']
hasher = proto.copy()
hasher.update(password.encode('utf-8'))
if hasher.hexdigest() == user.password:
return redirect('sub')
except User.DoesNotExist:
pass
return render(request, 'demo/login.html',
{'hint': '用户名或密码错误'})
def register(request):
if request.method.lower() == 'get':
return render(request, 'demo/register.html',
{'f': UserForm()})
else:
try:
form = UserForm(request.POST)
if form.is_valid():
form.save(commit=True)
return render(request, 'demo/login.html',
{'hint': '注册成功请登录!'})
else:
return render(request, 'demo/register.html',
{'hint': '请输入有效的注册信息', 'f': form})
except:
return render(request, 'demo/register.html',
{'hint': '注册失败, 请尝试其他的用户名!'})
def show_subjects(request):
2018-07-04 16:47:48 +08:00
ctx = {'subjects_list': Subject.objects.all()}
2018-07-05 16:54:15 +08:00
return render(request, 'demo/subject.html', ctx)
2018-07-04 16:47:48 +08:00
def show_teachers(request, no):
teachers = Teacher.objects.filter(subject__no=no)
ctx = {'teachers_list': teachers}
return render(request, 'demo/teacher.html', ctx)
2018-07-05 16:54:15 +08:00
def make_comment(request, no):
ctx = {'code': 200}
try:
teacher = Teacher.objects.get(pk=no)
if request.path.startswith('/good'):
teacher.good_count += 1
ctx['result'] = f'好评({teacher.gcount})'
else:
teacher.bad_count += 1
ctx['result'] = f'差评({teacher.bcount})'
teacher.save()
except Teacher.DoesNotExist:
ctx['code'] = 404
2018-07-04 16:47:48 +08:00
return HttpResponse(json.dumps(ctx),
content_type='application/json; charset=utf-8')