diff --git a/Day41-55/code/hellodjango/demo/admin.py b/Day41-55/code/hellodjango/demo/admin.py index 1f563533474cb15de26b5c7aceac43f43956ec7f..9284e00a1d9ee2a379957c466b6412a2da2c2d75 100644 --- a/Day41-55/code/hellodjango/demo/admin.py +++ b/Day41-55/code/hellodjango/demo/admin.py @@ -1,6 +1,11 @@ from django.contrib import admin -from demo.models import Teacher, Subject +from demo.models import Teacher, Subject, User + + +class UserAdmin(admin.ModelAdmin): + list_display = ('no', 'username', 'email', 'counter') + ordering = ('no', ) class SubjectAdmin(admin.ModelAdmin): @@ -16,4 +21,5 @@ class TeacherAdmin(admin.ModelAdmin): admin.site.register(Subject, SubjectAdmin) admin.site.register(Teacher, TeacherAdmin) +admin.site.register(User, UserAdmin) diff --git a/Day41-55/code/hellodjango/demo/apps.py b/Day41-55/code/hellodjango/demo/apps.py index 57920c332b6e27a518c8aecf58c770f868328449..047ccb12ff1dabc7f753ad46b3caf265de80cb2f 100644 --- a/Day41-55/code/hellodjango/demo/apps.py +++ b/Day41-55/code/hellodjango/demo/apps.py @@ -2,4 +2,4 @@ from django.apps import AppConfig class DemoConfig(AppConfig): - name = 'demo' + name = '投票' diff --git a/Day41-55/code/hellodjango/demo/forms.py b/Day41-55/code/hellodjango/demo/forms.py index 6f47a65ea0e463dcc6b782ac6bec3a339495f635..024740b0bc2f37da40bb3333b18f209647a7f99d 100644 --- a/Day41-55/code/hellodjango/demo/forms.py +++ b/Day41-55/code/hellodjango/demo/forms.py @@ -4,9 +4,9 @@ from demo.models import User class UserForm(forms.ModelForm): - username = forms.CharField(widget=forms.TextInput, min_length=6, max_length=20, help_text='请输入用户名') - password = forms.CharField(widget=forms.PasswordInput, min_length=8, max_length=20, help_text='请输入密码') - email = forms.CharField(widget=forms.EmailInput, max_length=255, help_text='请输入邮箱') + username = forms.CharField(widget=forms.TextInput, min_length=6, max_length=20) + password = forms.CharField(widget=forms.PasswordInput, min_length=8, max_length=20) + email = forms.CharField(widget=forms.EmailInput, max_length=255) class Meta(object): model = User diff --git a/Day41-55/code/hellodjango/demo/hello.py b/Day41-55/code/hellodjango/demo/hello.py new file mode 100644 index 0000000000000000000000000000000000000000..7a149432cb5b7a9eca38c8e786a1c1ad615561aa --- /dev/null +++ b/Day41-55/code/hellodjango/demo/hello.py @@ -0,0 +1,25 @@ +# 序列化 - 把对象写入数据流 - 串行化 / 归档 / 腌咸菜 +# 反序列化 - 从数据流中恢复出对象 - 反串行化 / 解归档 +# Python有三个支持序列化的模块 +# json - JSON / pickle - 二进制 / shelve +import json +import pickle + + +class Student(object): + + def __init__(self, name, age): + self.name = name + self.age = age + + +if __name__ == '__main__': + list1 = [10, 'hello', 99.9, 'goodbye'] + print(json.dumps(list1)) + print(pickle.dumps(list1)) + dict1 = {'name': '骆昊', 'age': 38} + print(json.dumps(dict1)) + print(pickle.dumps(dict1)) + stu = Student('骆昊', 38) + print(pickle.dumps(stu)) + diff --git a/Day41-55/code/hellodjango/demo/migrations/0005_auto_20180706_1458.py b/Day41-55/code/hellodjango/demo/migrations/0005_auto_20180706_1458.py new file mode 100644 index 0000000000000000000000000000000000000000..4626e6acd9c9b00b3526ac9c480a99a310a634d4 --- /dev/null +++ b/Day41-55/code/hellodjango/demo/migrations/0005_auto_20180706_1458.py @@ -0,0 +1,22 @@ +# Generated by Django 2.0.6 on 2018-07-06 06:58 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('demo', '0004_auto_20180705_1017'), + ] + + operations = [ + migrations.AlterModelOptions( + name='teacher', + options={'ordering': ('no',), 'verbose_name': '讲师', 'verbose_name_plural': '讲师'}, + ), + migrations.AddField( + model_name='user', + name='counter', + field=models.IntegerField(default=3, verbose_name='票数'), + ), + ] diff --git a/Day41-55/code/hellodjango/demo/models.py b/Day41-55/code/hellodjango/demo/models.py index ac69017a56429cfb332fb33e6d9c763dd89bd586..d3471a9358ec2986b12869bcffff36074c368fda 100644 --- a/Day41-55/code/hellodjango/demo/models.py +++ b/Day41-55/code/hellodjango/demo/models.py @@ -3,11 +3,6 @@ from hashlib import sha1 from django.db import models from django.db.models import PROTECT -# 高内聚 低耦合 -# 面向对象七个设计原则 -# 单一职责原则 / 开闭原则 / 依赖倒转原则 / 里氏替换原则 / 接口隔离原则 / 合成聚合复用原则 / 迪米特法则 -# 1995年 - GoF - 23个设计模式 -# 创建型模式中的原型模式 proto = sha1() @@ -16,6 +11,7 @@ class User(models.Model): username = models.CharField(max_length=20, unique=True, verbose_name='用户名') password = models.CharField(max_length=40, verbose_name='口令') email = models.CharField(max_length=255, verbose_name='邮箱') + counter = models.IntegerField(default=3, verbose_name='票数') def save(self, force_insert=False, force_update=False, using=None, update_fields=None): hasher = proto.copy() @@ -68,4 +64,4 @@ class Teacher(models.Model): db_table = 'tb_teacher' verbose_name = '讲师' verbose_name_plural = '讲师' - ordering = ('name', ) + ordering = ('no', ) diff --git a/Day41-55/code/hellodjango/demo/views.py b/Day41-55/code/hellodjango/demo/views.py index e1cbf011555489165df9bf5a4666ad648672b6ec..ad627e2f8e8caa1b7d7617e8e25bdf8c6e8f7923 100644 --- a/Day41-55/code/hellodjango/demo/views.py +++ b/Day41-55/code/hellodjango/demo/views.py @@ -18,6 +18,7 @@ def login(request): hasher = proto.copy() hasher.update(password.encode('utf-8')) if hasher.hexdigest() == user.password: + request.session['user'] = user return redirect('sub') except User.DoesNotExist: pass @@ -25,7 +26,6 @@ def login(request): {'hint': '用户名或密码错误'}) - def register(request): form = UserForm() if request.method.lower() == 'get': @@ -44,29 +44,64 @@ def register(request): return render(request, 'demo/register.html', ctx) +def check_username(request): + ctx = {} + if 'username' in request.GET: + username = request.GET['username'] + try: + User.objects.get(username__exact=username) + ctx['valid'] = False + except User.DoesNotExist: + ctx['valid'] = True + return HttpResponse(json.dumps(ctx), + content_type='application/json; charset=utf-8') + + def show_subjects(request): - ctx = {'subjects_list': Subject.objects.all()} - return render(request, 'demo/subject.html', ctx) + if 'user' in request.session and request.session['user']: + ctx = {'subjects_list': Subject.objects.all()} + return render(request, 'demo/subject.html', ctx) + else: + return render(request, 'demo/login.html', + {'hint': '请先登录!'}) def show_teachers(request, no): - teachers = Teacher.objects.filter(subject__no=no) - ctx = {'teachers_list': teachers} - return render(request, 'demo/teacher.html', ctx) + if 'user' in request.session and request.session['user']: + teachers = Teacher.objects.filter(subject__no=no)\ + .select_related('subject') + ctx = {'teachers_list': teachers} + return render(request, 'demo/teacher.html', ctx) + else: + return render(request, 'demo/login.html', + {'hint': '请先登录!'}) 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})' + if 'user' in request.session and request.session['user']: + user = request.session['user'] + if user.counter > 0: + 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() + user.counter -= 1 + User.objects.filter(username__exact=user.username)\ + .update(counter=user.counter) + request.session['user'] = user + except Teacher.DoesNotExist: + ctx['code'] = 404 else: - teacher.bad_count += 1 - ctx['result'] = f'差评({teacher.bcount})' - teacher.save() - except Teacher.DoesNotExist: - ctx['code'] = 404 + ctx['code'] = 403 + ctx['result'] = '票数不足' + else: + ctx['code'] = 302 + ctx['result'] = '请先登录' return HttpResponse(json.dumps(ctx), content_type='application/json; charset=utf-8') diff --git a/Day41-55/code/hellodjango/hellodjango/settings.py b/Day41-55/code/hellodjango/hellodjango/settings.py index 8cfa2a75984edb28d762ef83b689093e7c967914..4b118d84f9307e1b8cc4a0981e9ebded157af586 100644 --- a/Day41-55/code/hellodjango/hellodjango/settings.py +++ b/Day41-55/code/hellodjango/hellodjango/settings.py @@ -27,9 +27,10 @@ DEBUG = True ALLOWED_HOSTS = [] +SESSION_EXPIRE_AT_BROWSER_CLOSE = False +SESSION_COOKIE_AGE = 1800 # Application definition - INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', @@ -73,7 +74,6 @@ WSGI_APPLICATION = 'hellodjango.wsgi.application' # Database # https://docs.djangoproject.com/en/2.0/ref/settings/#databases - DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', @@ -88,7 +88,6 @@ DATABASES = { # Password validation # https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators - AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', @@ -107,7 +106,6 @@ AUTH_PASSWORD_VALIDATORS = [ # Internationalization # https://docs.djangoproject.com/en/2.0/topics/i18n/ - LANGUAGE_CODE = 'zh-hans' TIME_ZONE = 'Asia/Chongqing' @@ -120,6 +118,7 @@ USE_L10N = True USE_TZ = True +SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer' # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.0/howto/static-files/ @@ -127,3 +126,20 @@ STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'),] STATIC_URL = '/static/' # APPEND_SLASH = False + +# DEBUG < INFO < WARNING < ERROR < CRITICAL +LOGGING = { + 'version': 1, + 'disable_existing_loggers': False, + 'handlers': { + 'console': { + 'class': 'logging.StreamHandler', + }, + }, + 'loggers': { + 'django': { + 'handlers': ['console'], + 'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'), + }, + }, +} diff --git a/Day41-55/code/hellodjango/hellodjango/urls.py b/Day41-55/code/hellodjango/hellodjango/urls.py index dc4b8f2443cb1a8a41adbf099b1714b9848322c3..5c0e1fb7edb1f1b63d526bf817ba6515c5154e1d 100644 --- a/Day41-55/code/hellodjango/hellodjango/urls.py +++ b/Day41-55/code/hellodjango/hellodjango/urls.py @@ -22,6 +22,7 @@ urlpatterns = [ path('', views.login), path('login/', views.login), path('register/', views.register), + path('check/', views.check_username), path('subjects/', views.show_subjects, name='sub'), path('subjects//', views.show_teachers), path('good//', views.make_comment), diff --git a/Day41-55/code/hellodjango/static/images/icon-no.svg b/Day41-55/code/hellodjango/static/images/icon-no.svg new file mode 100644 index 0000000000000000000000000000000000000000..2e0d3832c9299c3994f627cd64ed0341a5da7b14 --- /dev/null +++ b/Day41-55/code/hellodjango/static/images/icon-no.svg @@ -0,0 +1,3 @@ + + + diff --git a/Day41-55/code/hellodjango/static/images/icon-yes.svg b/Day41-55/code/hellodjango/static/images/icon-yes.svg new file mode 100644 index 0000000000000000000000000000000000000000..5883d877e89b89d42fa121725ae7b726dbfa5f50 --- /dev/null +++ b/Day41-55/code/hellodjango/static/images/icon-yes.svg @@ -0,0 +1,3 @@ + + + diff --git a/Day41-55/code/hellodjango/templates/demo/login.html b/Day41-55/code/hellodjango/templates/demo/login.html index e975023d20603743b575da8906fcff5487ab60c1..e6e2bbb28b55d42d67672de91eee53cd0dca0dc0 100644 --- a/Day41-55/code/hellodjango/templates/demo/login.html +++ b/Day41-55/code/hellodjango/templates/demo/login.html @@ -5,7 +5,7 @@ 用户登录

学科信息


- + {% for subject in subjects_list %} +
+
{{ subject.name }}
+
{{ subject.intro }}
+
+ {% endfor %} \ No newline at end of file diff --git a/Day41-55/code/hellodjango/templates/demo/teacher.html b/Day41-55/code/hellodjango/templates/demo/teacher.html index f20fe4837411f1f3d5071f63b387b1039fecfa0e..1572bfdf8d7a8c238ca1543a57dac9fd3c0dc148 100644 --- a/Day41-55/code/hellodjango/templates/demo/teacher.html +++ b/Day41-55/code/hellodjango/templates/demo/teacher.html @@ -16,6 +16,7 @@ .potrait { width: 40%; float: left; + text-align: right; } hr { clear: both; @@ -37,7 +38,7 @@ {% for x in teachers_list %}
-

{{ x.name }}老师

+

{{ x.name }}老师 - {{ x.subject.name }}

讲师简介

{{ x.intro }}

教学理念

@@ -68,6 +69,8 @@ 'success': function(json) { if (json.code == 200) { $a.text(json.result); + } else if (json.code == 403) { + alert(json.result); } }, 'error': function() {}