Python学习第154天(作业完成)

今天解决了最后的一个问题,总算是完成了学生、老师、班级管理界面所有内容,实现功能大致如下:

1、对班级增删改查,并对班级分配老师,其中分配老师为多选分配

 

 2、对学生对象进行增删改查作用

 

 以上巨额能实现前后端链接,保证数据正常传输,目前所需开设网站内容基本实现,具体内容如下:

 

 具体代码如下:

1.路径分发区域(url.py)

from django.contrib import admin
from django.urls import path,re_path
from app01.views import classes
from app01.views import students

urlpatterns = [
    path('admin/', admin.site.urls),
    re_path('^classes.html$',classes.get_classes),
    re_path('^add_classes.html$',classes.add_classes),
    re_path('^del_classes.html$',classes.del_classes),
    re_path('^edit_classes.html$',classes.edit_classes),

    re_path('^students.html$',students.get_students),
    re_path('^add_students.html$',students.add_studens),
    re_path('^del_students.html$',students.del_students),
    re_path('^edit_students.html$',students.edit_students),

    re_path('^set_teacher.html$',classes.set_teacher),
    # path('a',classes.a_test),
    # path('b',classes.b_test),
]

2.基本属性设置区域(settings.py)

DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app01.apps.App01Config',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'test_for_student.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')]
        ,
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'test_for_student.wsgi.application'


# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'test_for_student',    #你的数据库名称
        'USER': 'root',   #你的数据库用户名
        'PASSWORD': '123456', #你的数据库密码
        'HOST': '', #你的数据库主机,留空默认为localhost
        'PORT': '3306', #你的数据库端口
    }
}


# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/

STATIC_URL = '/static/'
STATICFILES_DIRS = (
    os.path.join(BASE_DIR,'static'),
)

3.数据库表格模拟区域(modles.py)

from django.db import models

class Teachers(models.Model):
    # 老师表
    name = models.CharField(max_length=36)

class Classes(models.Model):
    # 班级表
    titile = models.CharField(max_length=32)
    m = models.ManyToManyField('Teachers')

class Students(models.Model):
    username = models.CharField(max_length=32)
    age = models.IntegerField()
    gender = models.BooleanField()
    cs = models.ForeignKey(Classes, on_delete=None)

4.主要功能识别区

  1.classes.py

from django.shortcuts import render
from django.shortcuts import redirect
from app01 import models

def get_classes(req):
    cls_list = models.Classes.objects.all()
    for item in cls_list:
        print(item.id,item.titile,item.m.all())
    return render(req,'get_classes.html',{'cls_list':cls_list})

def add_classes(req):
    if req.method == 'GET':
        return render(req,'add_classes.html')
    elif req.method == 'POST':
        title = req.POST.get('title')
        models.Classes.objects.create(titile = title)
        return redirect('/classes.html')

def del_classes(req):
    nid = req.GET.get('nid')
    print(nid)
    models.Classes.objects.filter(id=nid).delete()
    return redirect('/classes.html')

def edit_classes(req):
    if req.method == 'GET':
        nid = req.GET.get('nid')
        obj = models.Classes.objects.filter(id=nid).first()
        return render(req,'edit_classes.html',{'obj':obj})
    elif req.method == 'POST':
        nid = req.GET.get('nid')
        title = req.POST.get('xoxo')
        models.Classes.objects.filter(id=nid).update(titile = title)
        return redirect('/classes.html')

def set_teacher(req):
    if req.method == 'GET':
        nid = req.GET.get('nid')
        cls_obj = models.Classes.objects.filter(id=nid).first()
        print('cls_obj是:',type(cls_obj))
        # print('类型是',type(cls_obj.m.all()))
        cls_teacher_list = cls_obj.m.all().values_list('id','name',)
        # 当前班级任课老师的列表
        id_list = list(zip(*cls_teacher_list))[0] if list(zip(*cls_teacher_list)) else []
        all_teacher_list = models.Teachers.objects.all()
        return render(req,
                      'set_teacher.html',
                      {'id_list':id_list ,
                       'all_teacher_list':all_teacher_list,
                       'nid':nid})

    elif req.method == 'POST':
        nid = req.GET.get('nid')
        ids = req.POST.getlist('teacher_ids')
        print('所在班级',nid,'分配老师的ID',ids)
        obj = models.Classes.objects.filter(id=nid).first()
        obj.m.set(ids)
        return redirect('/classes.html')

  2.students.py

from django.shortcuts import render,redirect
from app01 import models

def get_students(req):
    stu_list = models.Students.objects.all()
    return render(req,'get_students.html',{'stu_list':stu_list})

def add_studens(req):
    if req.method == 'GET':
        cs_list = models.Classes.objects.all()
        return render(req,'add_students.html',{'cs_list':cs_list})
    elif req.method == 'POST':
        u = req.POST.get('username')
        a = req.POST.get('age')
        g = req.POST.get('gender')
        c = req.POST.get('cs')
        print(u,a,g,c)
        models.Students.objects.create(
            username=u,
            age=a,
            gender=g,
            cs_id=c
        )
        return redirect('/students.html')

def del_students(req):
    nid = req.GET.get('nid')
    models.Students.objects.filter(id=nid).delete()
    return redirect('/students.html')

def edit_students(req):
    if req.method == 'GET':
        nid = req.GET.get('nid')
        obj = models.Students.objects.filter(id=nid).first()
        cs_list = models.Classes.objects.all()
        return render(req, 'edit_students.html', {'obj': obj,'cs_list':cs_list})
    elif req.method == 'POST':
        nid = req.GET.get('nid')
        cs_list = models.Classes.objects.all()
        # title = req.POST.get('xoxo')
        u = req.POST.get('username')
        a = req.POST.get('age')
        g = req.POST.get('gender')
        c = req.POST.get('c')
        models.Students.objects.filter(id=nid).update(
            username=u,
            age=a,
            gender=g,
            cs_id=c
        )
        return redirect('/students.html')

5.视图区域(这部分内容比较多,选择两个比较有代表的吧)

  edit_students.html

<body>
    <form action="edit_students.html?nid={{ obj.id }}" method="POST">
        {% csrf_token %}
{#        <p style="display: none"> <input type="text" name="id" value="{{ obj.id }}" /></p>#}
        <p> <input type="text" name="username" value="{{ obj.username }}" /></p>
        <p> <input type="text" name="age" value="{{ obj.age }}" /></p>
        <p>
            {% if obj.gender %}
                男:<input type="radio" name="gender" checked="checked" value="1" />
                女:<input type="radio" name="gender" value="0" />
                {% else %}
                男:<input type="radio" name="gender" value="1" />
                女:<input type="radio" name="gender" value="0" checked="checked"  />
            {% endif %}
        </p>
        <p>
            <select name="c">
                {% for row in cs_list %}
                    <option value="{{ row.id }}">{{ row.titile }}</option>
                {% endfor %}
            </select>
        </p>
        <input type="submit" value="提交" />
    </form>
</body>

  set_teacher.html

<body>

<form method="POST" action="/set_teacher.html?nid={{ nid }}">
        {% csrf_token %}
        <select multiple="multiple" size="10" name="teacher_ids">
            {% for item in all_teacher_list %}
                {% if item.id in id_list %}
                    <option value="{{ item.id }}" selected="selected">{{ item.name }}</option>
                {% else %}
                    <option value="{{ item.id }}">{{ item.name }}</option>
                {% endif %}
            {% endfor %}
        </select>
        <input type="submit" value="提交" />
    </form>
</body>

 

总结这几天的错误,主要在于变量书写不仔细,其实内容大多数都是知道的,但是在变量使用上并不仔细,导致前后发生错误。

 

posted @ 2020-08-17 21:05  崆峒山肖大侠  阅读(186)  评论(0编辑  收藏  举报