Django+xadmin to build an online education platform (9)

Django+xadmin to build an online education platform (9)


github download

12. Home page and global 404, 500 configuration

12.1. Home page function

Course add a field

is_banner = models.BooleanField('Whether to carousel', default=False)

CourseOrg add a field

tag = models.CharField('institution tag',max_length=10,default='nationally well-known')

 (1) view

class IndexView(View):
    def get(self,request):
        all_banners = Banner.objects.all().order_by('index')
        courses = Course.objects.filter(is_banner=False)[:6]
        # Carousel course
        banner_courses = Course.objects.filter(is_banner=True)[:3]
        #Course organization
        course_orgs = Course.objects.all()[:15]
        return render(request,'index.html',{
            'courses': courses,
            'banner_courses': banner_courses,

(2) index.html

{% extends'base.html' %}
{% load staticfiles %}
{% block title %}List of course institutions{% endblock %}

{% block custom_bread %}
{% endblock %}

{% block content %}
    <div class="banner">
            <div class="wp">
                <div class="fl">
                    <div class="imgslide">
                        <ul class="imgs">
                            {% for banner in all_banners %}
                                    <a href="{{ banner.url }}">
                                        <img width="1200" height="478" src="{{ MEDIA_URL }}{{ banner.image }}"/>
                            {% endfor %}
                    <div class="unslider-arrow prev"></div>
                    <div class="unslider-arrow next"></div>

<!--banner end-->
<!--feature start-->
        <div class="wp">
            <ul class="feature">
                <li class="feature1">
                    <img class="pic" src="/static/images/feature1.png"/>
                    <p class="center">Professional authority</p>
                <li class="feature2">
                    <img class="pic" src="/static/images/feature2.png"/>
                    <p class="center">The latest course</p>
                <li class="feature3">
                    <img class="pic" src="/static/images/feature3.png"/>
                    <p class="center">Lectures by famous teachers</p>
                <li class="feature4">
                    <img class="pic" src="/static/images/feature4.png"/>
                    <p class="center">The data is true</p>
<!--feature end-->
<!--module1 start-->
        <div class="module">
            <div class="wp">
                <h1>Open course</h1>
                <div class="module1 eachmod">
                    <div class="module1_1 left">
                        <img width="228" height="614" src="/static/images/module1_1.jpg"/>
                        <p class="fisrt_word">Lectures by famous teachers<br/>Professional authority</p>
                        <a class="more" href="{% url'course:course_list' %}">View more courses></a>
                    <div class="right group_list">
                        <div class="module1_2 box">
                            <div class="imgslide2">
                                <ul class="imgs">
                                    {% for banner_course in banner_courses %}
                                        <a href="{% url'course:course_detail' %}">
                                            <img width="470" height="300" src="{{ MEDIA_URL }}{{ banner_course.image }}"/>
                                    {% endfor %}
                            <div class="unslider-arrow2 prev"></div>
                            <div class="unslider-arrow2 next"></div>
                            {% for course in courses %}
                            <div class="module1_{{ forloop.counter|add:2 }} box">
                                <a href="{% url'course:course_detail' %}">
                                    <img width="233" height="190" src="{{ MEDIA_URL }}{{ course.image }}"/>
                                <div class="des">
                                    <a href="{% url'course:course_detail' %}">
                                        <h2 title="Introduction to django">{{ }}</h2>
                                    <span class="fl">Difficulty: <i class="key">{{ course.get_degree_display }}</i></span>
                                    <span class="fr">Number of students: {{ course.students }}</span>
                                <div class="bottom">
                                    <span class="fl" title="慕课网">{{ }}</span>
                                    <span class="star fr">{{ course.fav_nums }}</span>
                            {% endfor %}
        <div class="module greybg">
            <div class="wp">
                <h1>Course institution</h1>
                <div class="module3 eachmod">
                    <div class="module3_1 left">
                        <img width="228" height="463" src="/static/images/module3_1.jpg"/>
                        <p class="fisrt_word">The prestigious school strikes<br/>Authentication certification</p>
                        <a class="more" href="{% url'org:org_list' %}">See more organizations></a>
                    <div class="right">
                                {% for org in course_orgs %}
                                 <li class="{% if forloop.counter|divisibleby:5 %}five{% endif %}">
                                    <a href="{% url'org:org_home' %}">
                                        <div class="company">
                                            <img width="184" height="100" src="{{ MEDIA_URL }}{{ org.image }}"/>
                                            <div class="score">
                                                <div class="circle">
                                                    <h2>{{ org.tag }}</h2>
                                        <p><span class="key" title="{{ }}">{{ }}</span></p>
                                {% endfor %}
{% endblock %}
{% block custom_js %}
<script type="text/javascript" src="{% static'js/index.js' %}"></script>
{% endblock %}

Description 1: Course

  • The courses are divided into is_banner=False and is_banner=True, the class attributes of the two courses are different
  • The class of is_banner=True is class="module1_2 box"
  • The class of is_banner=True is class="module1_3 box", so class="module1_{{ forloop.counter|add:2 }}

Note 2: Course institution

  • The class of the course institution is divided into class="" and class="five"
  • To make a judgment here, class="{% if forloop.counter|divisibleby:5 %}five{% endif %}
  • divisibleby filter: can it be divisible

Description 3: lolgin

  • When logging out and logging in, I found that the settings just now did not take effect, and I can’t see the picture. You need to change the login view
  • After the previous login, use render to'index.html' to return HttpResponseRedirect(reverse('index'))
class LoginView(View):
    '''User login'''

    def get(self,request):
        return render(request,'login.html')

    def post(self,request):
        # Instantiation
        login_form = LoginForm(request.POST)
        if login_form.is_valid():
            # Get the username and password submitted by the user
            user_name = request.POST.get('username', None)
            pass_word = request.POST.get('password', None)
            # Return the user object successfully, None on failure
            user = authenticate(username=user_name, password=pass_word)
            # If it is not null, the verification is successful
            if user is not None:
                if user.is_active:
                    # Only register and activate to log in
                    login(request, user)
                    return HttpResponseRedirect(reverse('index'))
                    return render(request,'login.html', {'msg':'User name or password is wrong','login_form': login_form})
            # Only when the user name or password does not exist, the error message will be returned to the front end
                return render(request,'login.html', {'msg':'Username or password is wrong','login_form':login_form})

        # form.is_valid() has been judged to be illegal, so there is no need to return an error message to the front end here
            return render(request,'login.html',{'login_form':login_form})

12.2. Global configuration 404 and 500


from MxOnline.settings import STATIC_ROOT

urlpatterns = [
#Static files
    re_path(r'^static/(?P<path>.*)', serve, {"document_root": STATIC_ROOT }),

# Global 404 page configuration
handler404 ='users.views.pag_not_found'


DEBUG = False


#Static files
STATIC_ROOT = os.path.join(BASE_DIR,'static')


from django.shortcuts import render_to_response
def pag_not_found(request):
    # Global 404 processing function
    response = render_to_response('404.html', {})
    response.status_code = 404
    return response

def page_error(request):
    # Global 500 processing function
    from django.shortcuts import render_to_response
    response = render_to_response('500.html', {})
    response.status_code = 500
    return response


  • 404 and 500, generate environment summary, debug = False must be set
  • Once debug is changed to false, django will not host your static files, so here you need to set a url to handle static files

13. Common web attacks and prevention

13.1. sql injection attack and prevention

The harm of sql injection

  • Illegal read, tamper, and delete data in the database
  • Steal all kinds of sensitive information of users to obtain benefits
  • Modify the content on the webpage by modifying the database
  • Inject Trojans, etc.

sql injection test code

class LoginUnsafeView(View):
    def get(self, request):
        return render(request, "login.html", {})
    def post(self, request):
        user_name = request.POST.get("username", "")
        pass_word = request.POST.get("password", "")

        import MySQLdb
        conn = MySQLdb.connect(host='', user='root', passwd='root', db='mxonline', charset='utf8')
        cursor = conn.cursor()
        sql_select = "select * from users_userprofile where email='{0}' and password='{1}'".format(user_name, pass_word)

        result = cursor.execute(sql_select)
        for row in cursor.fetchall():
            # Query to the user
from users.views import LoginUnsafeView

urlpatterns = [
    url('^login/', LoginUnsafeView.as_view(), name='login'),

Enter the user name in the login interface: 'OR 1=1# Password: 123

Found that the user name and password in our database can be obtained.

13.2.xss attack

The harm of xss cross site scripting (Cross Site Scripting)

  • Steal various user accounts, such as user online banking accounts and various administrator accounts
  • Theft of important data of business value from the company
  • Illegal transfer
  • Control the victim's machine to launch attacks on other websites, inject Trojan horses, etc.

xss attack process

xss attack protection

  • First of all, the user input places and variables in the code need to carefully check the length and filter the characters such as <>;'
  • Avoid directly leaking user privacy in cookies, such as email, password, etc.
  • Reduce the risk of cookie leakage by binding the cookie to the system ip
  • Try to use POST instead of GET to submit the form

13.3.csrf attack

 The harm of csrf cross-site request forgery (Cross-site request forgery)

  • Send mail on your behalf
  • Steal your account
  • Buy goods
  • Virtual currency transfer

 CSRF attack process:

 CSRF attack prevention:

  Add {{csrf_token}} in each form

Reference: Django+xadmin to build an online education platform (9)-Cloud + Community-Tencent Cloud