Django_day3_note

Django 命令

    check
    compilemessages
    createcachetable
    dbshell
    diffsettings
    dumpdata
    flush
    inspectdb
    loaddata
    makemessages
    makemigrations      //生成迁移
    migrate             // 迁移
    runserver           // 启动服务
    sendtestemail
    shell           //django 自带shell
    showmigrations
    sqlflush
    sqlmigrate
    sqlsequencereset
    squashmigrations
    startapp                //创建应用app
    startproject            //创建django项目
    test
    testserver

课堂练习

1.添加vote应用

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'vote',
]

2.创建模型

class Subject(models.Model):
    """学科"""
    no = models.AutoField(primary_key=True)
    name = models.CharField(max_length=31)
    intro = models.CharField(max_length=511)

    class Meta:
        db_table = 'tb_subject'
        
    def __str__(self):
        return self.name    

3.生成迁移数据库

python manage.py makemigrations
python manage.py migrate

4.使用django进行sql操作

// 进入django 的shell
python manage.py shell
//  从模型中导入tb对象
>>> from vote.models import Subject
//  创建并保存对象(会同步更新数据库)
>>> sub = Subject()
>>> sub.name = 'Python全栈+人工智能'
>>> sub.intro = '最牛学科'
>>> sub.save()

>>> sub = Subject()
>>> sub.name = 'JavaEE+分布式云服务'
>>> sub.intro = '快要过期的学科'
>>> sub.save()

//  删除对象(同步删除数据库数据)
>>> sub.delete()
(1, {'vote.Subject': 1})

//  查询no =1的数据并修改intro属性
>>> Subject.objects.get(no=1)
<Subject: Subject object (1)>
>>> a =  Subject.objects.get(no=1)
>>> a.name
'Python全栈+人工智能'
>>> a.intro = '超级牛逼的牛逼的学科'
>>> a.save()

5. 网页显示学科(调用数据库)

5.1 vote/views.py 添加

from vote.models import Subject

def show_subjects(request):
    subjects = Subject.objects.all()
    return render(request, 'subject.html', {'subjects': subjects})

5.2 urls.py 添加

from vote import views  // 添加项

urlpatterns = [
    path('admin/', admin.site.urls),
    path('home/', views.home),
    path('', views.show_subject)   // 添加项 (设为主页)
]

5.3 新建subject.html

  • body 内容如下
<body>
    <h1>学科列表</h1>
    <ul>
        {% for subject in subjects %}
        <li>{{ subject.name }}</li>
        {% endfor %}
    </ul>
</body>

6.实现点击学科名字跳转到学科老师列表页面

1.subject.html 修改

<body>
    <h1>学科列表</h1>
    <ul>
        {% for subject in subjects %}
        <li>{{ subject.no }}. <a href="/teachers?no={{ subject.no }}">{{ subject.name }}</a>
            <br>
            <span>{{ subject.intro }}</span> </li>
        {% endfor %}
    </ul>
</body>

2.urls.py 添加

path('teachers/', views.show_teachers)

3.views.py 添加

def show_teachers(request):
    print('=' * 60)
    no = request.GET['no']
    subject = Subject.objects.filter(no=no).first()
    return render(request, 'teachers.html', {'subject': subject})

4.新建teachers.html

<body>
    <h1>{{ subject }}</h1>
</body>

7.添加老师模型

1.添加老师模型(models.py 添加)

class Teacher(models.Model):
    """老师"""
    no = models.AutoField(primary_key=True, db_column='tno')
    name = models.CharField(max_length=15)
    birth = models.DateField(null=True)
    tel = models.CharField(max_length=15,null=True)
    intro = models.CharField(max_length=511,default='')
    good_count = models.IntegerField(default=0)
    bad_count = models.IntegerField(default=0)
    photo = models.CharField(max_length=255)
    subject = models.ForeignKey(to=Subject,on_delete=models.PROTECT,db_column='sno')

    class Meta:
        db_table = 'tb_teacher'

2 . 生成迁移数据库

python manage.py makemigrations
python manage.py migrate

8.利用django自带的后台录入老师信息

3.1 admin.py 添加

from django.contrib import admin
from django.contrib.admin import ModelAdmin
from vote.models import Subject, Teacher


class SubjetModelAdmin(ModelAdmin):
    list_display = ('no', 'name', 'intro')
    ordering = ('no',)


class TeacherModelAdmin(ModelAdmin):
    list_display = ('no', 'name', 'birth', 'good_conut', 'bad_count', 'intro')
    ordering = ('no',)
    search_fields = ('name',)


admin.site.register(Subject, SubjetModelAdmin)
admin.site.register(Teacher, TeacherModelAdmin)

然后登录admin后台添加老师信息

http://127.0.0.1:8000/admin

9.网页显示老师信息

1.修改teachers.html

<body>
    <h1>{{ subject }}的老师信息</h1>
    <hr>
    <div>
        {% for teacher in teachers %}
        <div>          
                <div>
                    <span><strong>{{ teacher.name }}</strong></span>
                    <span>{{ teacher.birth }}</span>
                    <span>{{ teacher.tel }}</span>
                </div>
                <div>{{ teacher.intro }}</div>
                <div>
                    <a href="">好评({{ teacher.good_count }})</a>
                    <a href="">差评({{ teacher.bad_count }})</a>
                </div>
        </div>
        {% endfor %}
    </div>
</body>

2.修改views.py

def show_teachers(request):
    no = request.GET['no']
    subject = Subject.objects.filter(no=no).first()
    teachers = Teacher.objects.filter(subject_id=no)
    return render(request, 'teachers.html', {'subject': subject, 'teachers': teachers})

10.使用静态资源显示老师头像

1.创建静态资源目录

static
    |-css
    |-imges
    |-js

2.settings.py 添加静态资源路径(文件末尾添加就行)

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
]

3.修改teachers.html

<body>
<!-- 使用静态资源-->
{% load static %}
    <h1>{{ subject}}的老师信息</h1>
    <hr>
    <div>
        {% for teacher in teachers %}
        <div>
            <!-- 使用静态资源-->
            <img src="{% static teacher.photo %}" alt="">
            <div>
                <span><strong>{{ teacher.name }}</strong></span>
                <span>{{ teacher.birth }}</span>
                <span>{{ teacher.tel }}</span>
            </div>
            <div>{{ teacher.intro }}</div>
            <div>
                <a href="">好评({{ teacher.good_conut }})</a>
                <a href="">差评({{ teacher.bad_conut }})</a>
            </div>
        </div>
        {% endfor %}
    </div>
</body>
  • 记得录入的信息要对上哈,并提前把准备好的图片放在imges目录下,例如:  
    teacher.photo= imges/luohao.png

11.使用自己的错误页面

1.改views.py

def show_teachers(request):
    try:
    # 此处是重点request.GET('no') 正确写法是request.GET['no']
    # 注意:正确的是方括号
        no = request.GET('no')
        subject = Subject.objects.filter(no=no).first()
        teachers = Teacher.objects.filter(subject_id=no)
        return render(request, 'teachers.html', {'subject': subject, 'teachers': teachers})
    except:
        return redirect('/myerror')


def show_myerror(request):
    return render(request, 'myerror.html', {})

2.新建myerror.html

<body>
    <h1>恭喜恭喜,BUG来了,快去抓虫把!</h1>
</body>

3.urls.py添加

path('myerror/', views.show_myerror)
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容