'更新了Django示例代码'
parent
24422f4f18
commit
267bd522cd
|
@ -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')
|
|
@ -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='所属学科'),
|
||||
),
|
||||
]
|
|
@ -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 = '讲师'
|
||||
|
|
|
@ -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):
|
||||
def make_comment(request, no):
|
||||
ctx = {'code': 200}
|
||||
try:
|
||||
teacher = Teacher.objects.get(pk=no)
|
||||
if request.path.startswith('/good'):
|
||||
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)
|
||||
ctx['result'] = f'好评({teacher.gcount})'
|
||||
else:
|
||||
teacher.bad_count += 1
|
||||
ctx['result'] = f'差评({teacher.bcount})'
|
||||
teacher.save()
|
||||
ctx = {'code': 200, 'result': f'差评({teacher.bad_count})'}
|
||||
except Teacher.DoesNotExist:
|
||||
ctx['code'] = 404
|
||||
return HttpResponse(json.dumps(ctx),
|
||||
content_type='application/json; charset=utf-8')
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -19,9 +19,12 @@ from django.urls import path
|
|||
from demo import views
|
||||
|
||||
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),
|
||||
]
|
||||
|
|
|
@ -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>
|
|
@ -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>
|
|
@ -42,8 +42,8 @@
|
|||
<p>{{ x.intro }}</p>
|
||||
<p><strong>教学理念</strong></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 class="potrait">
|
||||
{% if x.photo %}
|
||||
|
@ -58,12 +58,19 @@
|
|||
$(function() {
|
||||
$('.basic .button').on('click', function(evt) {
|
||||
evt.preventDefault();
|
||||
var a = $(evt.target);
|
||||
var url = a.attr('href');
|
||||
$.getJSON(url, function(json) {
|
||||
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);
|
||||
$a.text(json.result);
|
||||
}
|
||||
},
|
||||
'error': function() {}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
Loading…
Reference in New Issue