Django+xadmin to build an online education platform (Chapter 6 of various pit notes is attached from 0-1 whole process manual tutorial)

Keywords: JSON Django Database github


Create these folders first, and the files in them can be downloaded under my github.

  1. And then create these two files
    Note that CaptchaField will not take effect until a specific package is installed. The interpreter cannot install CaptchaField automatically here: from captcha.fields import CaptchaField
    (pip install django-simple-captcha==0.4.6
    )
    What is the function of creating one more urls in APPS? Because if only one urls is created in the project and many APPS are created in the future, it will be very difficult to manage the URL address. Therefore, in order to manage the respective APPS more conveniently, we create urls files in each folder of the app. The URL in the project needs to be configured with a namespace, so the role of this namespace is to configure the subsequent html When the template language is embedded, you can point to the URL address in the app through the project namespace, such as project: URL ('^ org /', include('organization.urls', namespace = 'org'),
    App: URL (R '^ list / $', org view. As_view(), name = 'org_list'). When HTML wants to call a class method or address, it can be called in a format like org:org_list.

First, let's create a class in organization.views to do a process of loading and rendering templates: ` from django.db.models import Q
from django.http import HttpResponse
from django.shortcuts import render

from django.views.generic.base import View

from organization.forms import UserAskForm
from operation.models import UserFavorite
from courses.models import CourseOrg, Course
from pure_pagination import Paginator, PageNotAnInteger

from organization.models import CityDict, Teacher

class OrgView(View):
#List of course institutions
def get(self, request):
#Access to all course organization data in the database
all_orgs = CourseOrg.objects.all()
#Get the first three data in descending order
hot_orgs = all_orgs.order_by('-click_nums')[:3]
all_citys = CityDict.objects.all()

    # Take out filter City
    #Get the city value of the data after the request, and the following '' is to avoid the error of the obtained value, which leads to system error and system crash. Specifically, add the null value. If the obtained value is null, you know that the value is not obtained;
    city_id = request.GET.get('city', '')
    if city_id:
    #The filter here is a filter. The function of the filter is similar to the get function above, except that the value obtained by the filter can be multiple and the type is dictionary. If the value obtained is wrong, the null value will be displayed automatically, while the get can only get one value and the type is list;
        all_orgs = all_orgs.filter(city_id=int(city_id))

    # Mechanism search
    search_keywords = request.GET.get('keywords', '')
    if search_keywords:
    #Q is used to refer to the character "|" and its meaning, "|icons" is to change all the data queried by the database into lowercase;
        all_orgs = all_orgs.filter(Q(name__icontains=search_keywords) |
                                         Q(desc__icontains=search_keywords))

    # Class selection
    category = request.GET.get('ct', '')
    if category:
        all_orgs = all_orgs.filter(category=category)

    sort = request.GET.get('sort', '')
    if sort:
        if sort == 'students':
            all_orgs = all_orgs.order_by('-students')
        elif sort == 'course':
            all_orgs = all_orgs.order_by('-course_nums')

    org_nums = all_orgs.count()
    # Pagination of course institutions
    #The paging function can import the paging package, and the specific principle can go to the usage of Baidu package. In order to use the function quickly, we only need to configure the necessary parameters
    try:
    #The following 1 represents one page
        page = request.GET.get('page', 1)
    except PageNotAnInteger:
        page = 1
    #The following three represent three data displayed on one page, but not much is said on the "all" orgs
    p = Paginator(all_orgs, 3, request=request)

    orgs = p.page(page)

#After that, we use the shortcut function render to import and render templates
return render(request, 'org-list.html', {
'all_orgs': orgs,
'all_citys': all_citys,
'org_nums': org_nums,
'city_id': city_id,
'category': category,
'hot_orgs': hot_orgs,
'sort': sort,
})

class AddUserAskView(View):
"""
User add consultation
"""

def post(self, request):
#The UserAskForm model here inherits from the UserAsk model class. In order to avoid repeated code typing, django has built-in ModelForm method, which is specially used to inherit the model class.
    userask_form = UserAskForm(request.POST) #Instantiate validation object
    #First of all, the function of is_valid() is to check whether the value in self.errors is a value. As long as there is a value, it is a flag. Then analyze the errors. It is determined that all errors are empty. If it is empty, return self.full_clean(). Otherwise, return self. ;
    if userask_form.is_valid():

#True means to submit directly to the database. If it is not true, it will be submitted to the database but not saved
user_ask = userask_form.save(commit=True)
#Return to JSON format
return HttpResponse('{"status":"success"}', content_type='application/json')
else:
return HttpResponse('{"status": "fail", "msg": "add error"}', content_type = 'application/json')

class OrgHomeView(View):
"""
Home page of organization
"""

def get(self, request, org_id):	
#The org ID here is passed from the matching org ID in urls. The purpose is to add / 1 / 2 to each organization address in multiple organization addresses /The number of 3... Is to avoid address duplication and better manage each organization's address (if you are interested, you can debug this get request yourself, and you can roughly understand the whole process. I have also studied this for an hour, confessing...)
#home here is mainly for the effect of the selected module. html will talk about it later
    current_page = 'home'

#Instantiation model class (the org ID is 1, which matches the default ID of database table = 1)
course_org = CourseOrg.objects.get(id=int(org_id))
Has ﹐ fav = false ﹐ judgment label of HTML favorite button
if request.user.is_authenticated:
if UserFavorite.objects.filter(user=request.user,fav_id=course_org.id,fav_type=2):
has_fav = True
#The data of both foreign keys can be used - the use of course set
all_courses = course_org.course_set.all()[:4]
all_teachers = course_org.teacher_set.all()[:2]
return render(request, 'org-detail-homepage.html', {
'course_org': course_org,
'all_courses': all_courses,
'all_teachers': all_teachers,
'current_page': current_page,
'has_fav': has_fav,
})

class OrgCourseView(View):
"""
List page of institutional courses
"""

def get(self, request, org_id):
    current_page = 'course'
    # Get to the course institution according to id
    course_org = CourseOrg.objects.get(id=int(org_id))
    # Find the course through the course institution. Built in variable, find the foreign key reference to this field
    all_courses = course_org.course_set.all()
    # Judge collection status
    has_fav = False
    if request.user.is_authenticated:
        if UserFavorite.objects.filter(user=request.user, fav_id=course_org.id, fav_type=2):
            has_fav = True

    return render(request, 'org-detail-course.html', {
        'all_courses': all_courses,
        'course_org': course_org,
        'current_page': current_page,
        'has_fav': has_fav,
    })

class OrgDescView(View):
"Organization introduction page"

def get(self, request, org_id):
    current_page = 'desc'
    # Get to the course institution according to id
    course_org = CourseOrg.objects.get(id=int(org_id))
    # Judge collection status
    has_fav = False
    if request.user.is_authenticated:
        if UserFavorite.objects.filter(user=request.user, fav_id=course_org.id, fav_type=2):
            has_fav = True
    return render(request, 'org-detail-desc.html', {
        'course_org': course_org,
        'current_page': current_page,
        'has_fav': has_fav,
    })

class OrgTeacherView(View):
"""
Institutional teachers page
"""

def get(self, request, org_id):
    current_page = 'teacher'
    course_org = CourseOrg.objects.get(id=int(org_id))
    all_teacher = course_org.teacher_set.all()
    #Judge collection status
    has_fav = False
    if request.user.is_authenticated:
        if UserFavorite.objects.filter(user=request.user, fav_id=course_org.id, fav_type=2):
            has_fav = True

    return render(request, 'org-detail-teachers.html', {
        'all_teacher': all_teacher,
        'course_org': course_org,
        'current_page': current_page,
        'has_fav': has_fav,
    })

class AddFavView(View):

# User collection, user cancel collection

def post(self, request):
    fav_id = request.POST.get('fav_id', '')
    fav_type = request.POST.get('fav_type', '')

    if not request.user.is_authenticated:
        # Judge user login status
        return HttpResponse('{"status":"fail","msg":"User not logged in"}', content_type='application/json')
    exist_records = UserFavorite.objects.filter(user=request.user, fav_id=int(fav_id), fav_type=int(fav_type))
    if exist_records:
        #If the record already exists, the user cancels the collection
        exist_records.delete()
        if int(type) == 1:
            course = Course.objects.get(id=int(id))
            course.fav_nums -= 1
            if course.fav_nums < 0:
                course.fav_nums = 0
            course.save()
        elif int(type) == 2:
            org = CourseOrg.objects.get(id=int(id))
            org.fav_nums -= 1
            if org.fav_nums < 0:
                org.fav_nums = 0
            org.save()
        elif int(type) == 3:
            teacher = Teacher.objects.get(id=int(id))
            teacher.fav_nums -= 1
            if teacher.fav_nums < 0:
                teacher.fav_nums = 0
            teacher.save()
        return HttpResponse('{"status":"success","msg":"Collection"}', content_type='application/json')
    else:
        user_fav = UserFavorite()
        if int(fav_id) > 0 and int(fav_type) > 0:
            user_fav.fav_id = int(fav_id)
            user_fav.fav_type = int(fav_type)
            user_fav.user = request.user
            user_fav.save()

            if int(type) == 1:
                course = Course.objects.get(id=int(id))
                course.fav_nums += 1
                course.save()
            elif int(type) == 2:
                org = CourseOrg.objects.get(id=int(id))
                org.fav_nums += 1
                org.save()
            elif int(type) == 3:
                teacher = Teacher.objects.get(id=int(id))
                teacher.fav_nums += 1
                teacher.save()
            return HttpResponse('{"status":"success","msg":"Have been collected"}', content_type='application/json')

        else:
            return HttpResponse('{"status":"fail","msg":"Collection error"}', content_type='application/json')

class TeacherListView(View):
"""
Course instructor list page
"""

def get(self,request):
    all_teachers = Teacher.objects.all()

    sort = request.GET.get('sort', '')
    if sort:
        if sort == 'hot':
            all_teachers = all_teachers.order_by('-click_nums')
    sorted_teacher = Teacher.objects.all().order_by('-click_nums')[:3]

    # Mechanism search
    search_keywords = request.GET.get('keywords', '')
    if search_keywords:
        all_teachers = all_teachers.filter(Q(name__icontains=search_keywords) |
                                   Q(work_company__icontains=search_keywords) |
                                   Q(work_position__icontains=search_keywords))

    # Paginate lecturers
    try:
        page = request.GET.get('page', 1)
    except PageNotAnInteger:
        page = 1

    p = Paginator(all_teachers, 1, request=request)

    teachers = p.page(page)
    return render(request,'teachers-list.html',{
        'all_teachers':teachers,
        'sorted_teacher':sorted_teacher,
        'sort':sort,
    })

class TeacherDetailView(View):
def get(self,request,teacher_id):
teacher = Teacher.objects.get(id = int(teacher_id))
teacher.click_nums +=1
teacher.save()
all_courses = Course.objects.filter(teacher=teacher)

    has_teacher_faved = False
    if UserFavorite.objects.filter(user = request.user,fav_type= 3,fav_id=teacher.id):
        has_teacher_faved =True

    has_org_faved = False
    if UserFavorite.objects.filter(user=request.user, fav_type=2, fav_id=teacher.org.id):
        has_org_faved = True
    #Lecturer rank
    sorted_teacher = Teacher.objects.all().order_by('-click_nums')[:3]
    return render(request,'teacher-detail.html',{
        'teacher':teacher,
        'sorted_teacher':sorted_teacher,
        'all_courses':all_courses,
        'has_teacher_faved':has_teacher_faved,
        'has_org_faved':has_org_faved,
    })`

The above is the code of the back-end course organization. The next chapter is how to configure the template engine in the front end so that the back-end code logic can render our front end.

Published 8 original articles · praised 4 · visited 974
Private letter follow

Posted by SlimSlyk on Thu, 05 Mar 2020 01:59:18 -0800