Explorar o código

'更新了Django示例代码'

jackfrued %!s(int64=7) %!d(string=hai) anos
pai
achega
267bd522cd

+ 13 - 0
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')

+ 33 - 0
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='所属学科'),
+        ),
+    ]

+ 37 - 0
Day41-55/code/hellodjango/demo/models.py

@@ -1,6 +1,33 @@
+from hashlib import sha1
+
 from django.db import models
 from django.db import models
 from django.db.models import PROTECT
 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):
 class Subject(models.Model):
     no = models.AutoField(primary_key=True, db_column='sno', verbose_name='编号')
     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='好评数')
     good_count = models.IntegerField(default=0, db_column='tgcount', verbose_name='好评数')
     bad_count = models.IntegerField(default=0, db_column='tbcount', 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):
     class Meta(object):
         db_table = 'tb_teacher'
         db_table = 'tb_teacher'
         verbose_name = '讲师'
         verbose_name = '讲师'

+ 56 - 18
Day41-55/code/hellodjango/demo/views.py

@@ -1,14 +1,53 @@
 import json
 import json
 
 
 from django.http import HttpResponse
 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()}
     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):
 def show_teachers(request, no):
@@ -17,19 +56,18 @@ def show_teachers(request, no):
     return render(request, 'demo/teacher.html', ctx)
     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),
     return HttpResponse(json.dumps(ctx),
                         content_type='application/json; charset=utf-8')
                         content_type='application/json; charset=utf-8')

+ 4 - 2
Day41-55/code/hellodjango/hellodjango/settings.py

@@ -55,7 +55,7 @@ ROOT_URLCONF = 'hellodjango.urls'
 TEMPLATES = [
 TEMPLATES = [
     {
     {
         'BACKEND': 'django.template.backends.django.DjangoTemplates',
         'BACKEND': 'django.template.backends.django.DjangoTemplates',
-        'DIRS': [os.path.join(BASE_DIR, 'templates')],
+        'DIRS': [os.path.join(BASE_DIR, 'templates'),],
         'APP_DIRS': True,
         'APP_DIRS': True,
         'OPTIONS': {
         'OPTIONS': {
             'context_processors': [
             'context_processors': [
@@ -123,5 +123,7 @@ USE_TZ = True
 
 
 # Static files (CSS, JavaScript, Images)
 # Static files (CSS, JavaScript, Images)
 # https://docs.djangoproject.com/en/2.0/howto/static-files/
 # 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/'
 STATIC_URL = '/static/'
+
+# APPEND_SLASH = False

+ 7 - 4
Day41-55/code/hellodjango/hellodjango/urls.py

@@ -19,9 +19,12 @@ from django.urls import path
 from demo import views
 from demo import views
 
 
 urlpatterns = [
 urlpatterns = [
-    path('', views.index, name='index'),
-    path('subjects/<int:no>', views.show_teachers),
-    path('good/<int:no>', views.make_good_comment),
-    path('bad/<int:no>', views.make_bad_comment),
+    path('', views.login),
+    path('login/', views.login),
+    path('register/', views.register),
+    path('subjects/', views.show_subjects, name='sub'),
+    path('subjects/<int:no>/', views.show_teachers),
+    path('good/<int:no>/', views.make_comment),
+    path('bad/<int:no>/', views.make_comment),
     path('admin/', admin.site.urls),
     path('admin/', admin.site.urls),
 ]
 ]

+ 38 - 0
Day41-55/code/hellodjango/templates/demo/login.html

@@ -0,0 +1,38 @@
+<!doctype html>
+<html lang="en">
+<head>
+    <meta charset="UTF-8">
+    <title>用户登录</title>
+    <style>
+        #login {
+            width: 250px;
+            margin: 20px auto;
+        }
+        #login form div {
+            margin: 10px 0;
+        }
+    </style>
+</head>
+<body>
+    <h1>用户登录</h1>
+    <hr>
+    <div id="login">
+        <p style="color: red; font-size: 12px;">{{ hint }}</p>
+        <form action="/login/" method="post">
+            {% csrf_token %}
+            <div>用户名: </div>
+            <div>
+                <input type="text" name="username" required>
+            </div>
+            <div>密码: </div>
+            <div>
+                <input type="password" name="password" required>
+            </div>
+            <div>
+                <input type="submit" value="登录">
+            </div>
+        </form>
+        <a href="/register">注册新用户</a>
+    </div>
+</body>
+</html>

+ 42 - 0
Day41-55/code/hellodjango/templates/demo/register.html

@@ -0,0 +1,42 @@
+<!doctype html>
+<html lang="en">
+<head>
+    <meta charset="UTF-8">
+    <title>用户注册</title>
+    <style>
+        #login {
+            width: 250px;
+            margin: 20px auto;
+        }
+        #login form div {
+            margin: 10px 0;
+        }
+    </style>
+</head>
+<body>
+    <h1>用户注册</h1>
+    <hr>
+    <div id="login">
+        <p style="color: red; font-size: 12px;">{{ hint }}</p>
+        <form action="/register/" method="post">
+            {% csrf_token %}
+            <div>用户名: </div>
+            <div>
+                {{ f.username }}
+            </div>
+            <div>密码: </div>
+            <div>
+                {{ f.password }}
+            </div>
+            <div>邮箱: </div>
+            <div>
+                {{ f.email }}
+            </div>
+            <div>
+                <input type="submit" value="注册">
+            </div>
+        </form>
+        <a href="/">返回登录</a>
+    </div>
+</body>
+</html>

+ 0 - 0
Day41-55/code/hellodjango/templates/demo/index.html → Day41-55/code/hellodjango/templates/demo/subject.html


+ 21 - 14
Day41-55/code/hellodjango/templates/demo/teacher.html

@@ -42,8 +42,8 @@
                 <p>{{ x.intro }}</p>
                 <p>{{ x.intro }}</p>
                 <p><strong>教学理念</strong></p>
                 <p><strong>教学理念</strong></p>
                 <p>{{ x.motto }}</p>
                 <p>{{ x.motto }}</p>
-                <a href="/good/{{ x.no }}" class="button">好评({{ x.good_count }})</a>
-                <a href="/bad/{{ x.no }}" class="button">差评({{ x.bad_count }})</a>
+                <a href="/good/{{ x.no }}" class="button">好评({{ x.gcount }})</a>
+                <a href="/bad/{{ x.no }}" class="button">差评({{ x.bcount }})</a>
             </div>
             </div>
             <div class="potrait">
             <div class="potrait">
                 {% if x.photo %}
                 {% if x.photo %}
@@ -55,18 +55,25 @@
     {% endfor %}
     {% endfor %}
     <script src="{% static 'js/jquery.min.js' %}"></script>
     <script src="{% static 'js/jquery.min.js' %}"></script>
     <script>
     <script>
-        $(function() {
-            $('.basic .button').on('click', function(evt) {
-                evt.preventDefault();
-                var a = $(evt.target);
-                var url = a.attr('href');
-                $.getJSON(url, function(json) {
-                   if (json.code == 200) {
-                       a.text(json.result);
-                   }
-                });
-            });
-        });
+       $(function() {
+           $('.basic .button').on('click', function(evt) {
+               evt.preventDefault();
+               var $a = $(evt.target);
+               var url = $a.attr('href');
+               $.ajax({
+                   'url': url,
+                   'type': 'get',
+                   'data': {},
+                   'dataType': 'json',
+                   'success': function(json) {
+                       if (json.code == 200) {
+                           $a.text(json.result);
+                       }
+                   },
+                   'error': function() {}
+               });
+           });
+       });
     </script>
     </script>
 </body>
 </body>
 </html>
 </html>