From 267bd522cd1d81fe7f40bdad84f54357daec61cc Mon Sep 17 00:00:00 2001 From: jackfrued Date: Thu, 5 Jul 2018 16:54:15 +0800 Subject: [PATCH] =?UTF-8?q?'=E6=9B=B4=E6=96=B0=E4=BA=86Django=E7=A4=BA?= =?UTF-8?q?=E4=BE=8B=E4=BB=A3=E7=A0=81'?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Day41-55/code/hellodjango/demo/forms.py | 13 ++++ .../migrations/0004_auto_20180705_1017.py | 33 +++++++++ Day41-55/code/hellodjango/demo/models.py | 37 ++++++++++ Day41-55/code/hellodjango/demo/views.py | 74 ++++++++++++++----- .../code/hellodjango/hellodjango/settings.py | 6 +- Day41-55/code/hellodjango/hellodjango/urls.py | 11 ++- .../hellodjango/templates/demo/login.html | 38 ++++++++++ .../hellodjango/templates/demo/register.html | 42 +++++++++++ .../demo/{index.html => subject.html} | 0 .../hellodjango/templates/demo/teacher.html | 35 +++++---- 10 files changed, 251 insertions(+), 38 deletions(-) create mode 100644 Day41-55/code/hellodjango/demo/forms.py create mode 100644 Day41-55/code/hellodjango/demo/migrations/0004_auto_20180705_1017.py create mode 100644 Day41-55/code/hellodjango/templates/demo/login.html create mode 100644 Day41-55/code/hellodjango/templates/demo/register.html rename Day41-55/code/hellodjango/templates/demo/{index.html => subject.html} (100%) diff --git a/Day41-55/code/hellodjango/demo/forms.py b/Day41-55/code/hellodjango/demo/forms.py new file mode 100644 index 0000000..296f771 --- /dev/null +++ b/Day41-55/code/hellodjango/demo/forms.py @@ -0,0 +1,13 @@ +from django import forms + +from demo.models import User + + +class UserForm(forms.ModelForm): + username = forms.CharField(max_length=20, min_length=6) + password = forms.CharField(widget=forms.PasswordInput, max_length=20, min_length=8) + email = forms.CharField(widget=forms.EmailInput, max_length=255) + + class Meta(object): + model = User + fields = ('username', 'password', 'email') diff --git a/Day41-55/code/hellodjango/demo/migrations/0004_auto_20180705_1017.py b/Day41-55/code/hellodjango/demo/migrations/0004_auto_20180705_1017.py new file mode 100644 index 0000000..20f902f --- /dev/null +++ b/Day41-55/code/hellodjango/demo/migrations/0004_auto_20180705_1017.py @@ -0,0 +1,33 @@ +# Generated by Django 2.0.6 on 2018-07-05 02:17 + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + dependencies = [ + ('demo', '0003_auto_20180704_1118'), + ] + + operations = [ + migrations.CreateModel( + name='User', + fields=[ + ('no', models.AutoField(db_column='uno', primary_key=True, serialize=False, verbose_name='编号')), + ('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='邮箱')), + ], + options={ + 'verbose_name': '用户', + 'verbose_name_plural': '用户', + 'db_table': 'tb_user', + }, + ), + migrations.AlterField( + model_name='teacher', + name='subject', + field=models.ForeignKey(db_column='sno', on_delete=django.db.models.deletion.PROTECT, related_name='+', to='demo.Subject', verbose_name='所属学科'), + ), + ] diff --git a/Day41-55/code/hellodjango/demo/models.py b/Day41-55/code/hellodjango/demo/models.py index 2c712ba..ac69017 100644 --- a/Day41-55/code/hellodjango/demo/models.py +++ b/Day41-55/code/hellodjango/demo/models.py @@ -1,6 +1,33 @@ +from hashlib import sha1 + from django.db import models from django.db.models import PROTECT +# 高内聚 低耦合 +# 面向对象七个设计原则 +# 单一职责原则 / 开闭原则 / 依赖倒转原则 / 里氏替换原则 / 接口隔离原则 / 合成聚合复用原则 / 迪米特法则 +# 1995年 - GoF - 23个设计模式 +# 创建型模式中的原型模式 +proto = sha1() + + +class User(models.Model): + no = models.AutoField(primary_key=True, db_column='uno', verbose_name='编号') + 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='邮箱') + + def save(self, force_insert=False, force_update=False, using=None, update_fields=None): + hasher = proto.copy() + hasher.update(self.password.encode('utf-8')) + self.password = hasher.hexdigest() + super().save(force_insert, force_update, using, update_fields) + + class Meta(object): + db_table = 'tb_user' + verbose_name = '用户' + verbose_name_plural = '用户' + class Subject(models.Model): no = models.AutoField(primary_key=True, db_column='sno', verbose_name='编号') @@ -27,6 +54,16 @@ class Teacher(models.Model): good_count = models.IntegerField(default=0, db_column='tgcount', verbose_name='好评数') bad_count = models.IntegerField(default=0, db_column='tbcount', verbose_name='差评数') + @property + def gcount(self): + return f'{self.good_count}' \ + if self.good_count <= 999 else '999+' + + @property + def bcount(self): + return f'{self.bad_count}' \ + if self.bad_count <= 999 else '999+' + class Meta(object): db_table = 'tb_teacher' verbose_name = '讲师' diff --git a/Day41-55/code/hellodjango/demo/views.py b/Day41-55/code/hellodjango/demo/views.py index a70ad6b..a028055 100644 --- a/Day41-55/code/hellodjango/demo/views.py +++ b/Day41-55/code/hellodjango/demo/views.py @@ -1,14 +1,53 @@ import json from django.http import HttpResponse -from django.shortcuts import render +from django.shortcuts import render, redirect -from demo.models import Subject, Teacher +from demo.forms import UserForm +from demo.models import Subject, Teacher, User, proto -def index(request): +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): ctx = {'subjects_list': Subject.objects.all()} - return render(request, 'demo/index.html', ctx) + return render(request, 'demo/subject.html', ctx) def show_teachers(request, no): @@ -17,19 +56,18 @@ def show_teachers(request, no): return render(request, 'demo/teacher.html', ctx) -def make_good_comment(request, no): - teacher = Teacher.objects.get(pk=no) - teacher.good_count += 1 - teacher.save() - ctx = {'code': 200, 'result': f'好评({teacher.good_count})'} - return HttpResponse(json.dumps(ctx), - content_type='application/json; charset=utf-8') - - -def make_bad_comment(request, no): - teacher = Teacher.objects.get(pk=no) - teacher.bad_count += 1 - teacher.save() - ctx = {'code': 200, 'result': f'差评({teacher.bad_count})'} +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 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 a7385c9..8cfa2a7 100644 --- a/Day41-55/code/hellodjango/hellodjango/settings.py +++ b/Day41-55/code/hellodjango/hellodjango/settings.py @@ -55,7 +55,7 @@ ROOT_URLCONF = 'hellodjango.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', - 'DIRS': [os.path.join(BASE_DIR, 'templates')], + 'DIRS': [os.path.join(BASE_DIR, 'templates'),], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ @@ -123,5 +123,7 @@ USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.0/howto/static-files/ -STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] +STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'),] STATIC_URL = '/static/' + +# APPEND_SLASH = False diff --git a/Day41-55/code/hellodjango/hellodjango/urls.py b/Day41-55/code/hellodjango/hellodjango/urls.py index e46858c..dc4b8f2 100644 --- a/Day41-55/code/hellodjango/hellodjango/urls.py +++ b/Day41-55/code/hellodjango/hellodjango/urls.py @@ -19,9 +19,12 @@ from django.urls import path from demo import views urlpatterns = [ - path('', views.index, name='index'), - path('subjects/', views.show_teachers), - path('good/', views.make_good_comment), - path('bad/', views.make_bad_comment), + path('', views.login), + path('login/', views.login), + path('register/', views.register), + path('subjects/', views.show_subjects, name='sub'), + path('subjects//', views.show_teachers), + path('good//', views.make_comment), + path('bad//', views.make_comment), path('admin/', admin.site.urls), ] diff --git a/Day41-55/code/hellodjango/templates/demo/login.html b/Day41-55/code/hellodjango/templates/demo/login.html new file mode 100644 index 0000000..fa9e7d2 --- /dev/null +++ b/Day41-55/code/hellodjango/templates/demo/login.html @@ -0,0 +1,38 @@ + + + + + 用户登录 + + + +

用户登录

+
+
+

{{ hint }}

+
+ {% csrf_token %} +
用户名:
+
+ +
+
密码:
+
+ +
+
+ +
+
+ 注册新用户 +
+ + \ No newline at end of file diff --git a/Day41-55/code/hellodjango/templates/demo/register.html b/Day41-55/code/hellodjango/templates/demo/register.html new file mode 100644 index 0000000..53e13c0 --- /dev/null +++ b/Day41-55/code/hellodjango/templates/demo/register.html @@ -0,0 +1,42 @@ + + + + + 用户注册 + + + +

用户注册

+
+
+

{{ hint }}

+
+ {% csrf_token %} +
用户名:
+
+ {{ f.username }} +
+
密码:
+
+ {{ f.password }} +
+
邮箱:
+
+ {{ f.email }} +
+
+ +
+
+ 返回登录 +
+ + \ No newline at end of file diff --git a/Day41-55/code/hellodjango/templates/demo/index.html b/Day41-55/code/hellodjango/templates/demo/subject.html similarity index 100% rename from Day41-55/code/hellodjango/templates/demo/index.html rename to Day41-55/code/hellodjango/templates/demo/subject.html diff --git a/Day41-55/code/hellodjango/templates/demo/teacher.html b/Day41-55/code/hellodjango/templates/demo/teacher.html index ed63262..f20fe48 100644 --- a/Day41-55/code/hellodjango/templates/demo/teacher.html +++ b/Day41-55/code/hellodjango/templates/demo/teacher.html @@ -42,8 +42,8 @@

{{ x.intro }}

教学理念

{{ x.motto }}

- 好评({{ x.good_count }}) - 差评({{ x.bad_count }}) + 好评({{ x.gcount }}) + 差评({{ x.bcount }})
{% if x.photo %} @@ -55,18 +55,25 @@ {% endfor %} \ No newline at end of file