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

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

Code

github download

11. User Information

11.1. Personal information display

 (1) Create a new'usercenter-bae.html' as the motherboard

{% load staticfiles %}

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
    <title>{% block title %}
    Personal Information-Muxue Online
    {% endblock %}</title>
    <link rel="stylesheet" type="text/css" href="{% static'css/reset.css' %}">
    <link rel="stylesheet" type="text/css" href="{% static'css/animate.css' %}">
    <link rel="stylesheet" type="text/css" href="{% static'css/style.css' %}">
    <link rel="stylesheet" type="text/css" href="{% static'js/plugins/queryCity/css/cityLayout.css' %}">
    {% block custom_css %}
    
    {% endblock %}
    <link rel="stylesheet" type="text/css" href="{% static'css/lq.datetimepick.css' %}"/>

    <script src="{% static'js/jquery.min.js' %}" type="text/javascript"></script>
    <script src="{% static'js/jquery-migrate-1.2.1.min.js' %}" type="text/javascript"></script>

</head>
<body>
<section class="headerwrap headerwrap2">
    <header>
        <div class="header2 header">
             <div class="top">
                <div class="wp">
                    <div class="fl"><p>Service call: <b>33333333</b></p></div>
                    <!--Jump after login-->


                        <div class="personal">
                            <dl class="user fr">
                                <dd>bobby<img class="down fr" src="{% static'js/jquery-migrate-1.2.1.min.js' %}"/></dd>
                                <dt><img width="20" height="20" src="{% static'media/image/2016/12/default_big_14.png' %}"/></dt>
                            </dl>
                            <div class="userdetail">
                                <dl>
                                    <dt><img width="80" height="80" src="{% static'media/image/2016/12/default_big_14.png' %}"/></dt>
                                    <dd>
                                        <h2>django</h2>
                                        <p>bobby</p>
                                    </dd>
                                </dl>
                                <div class="btn">
                                    <a class="personcenter fl" href="usercenter-info.html">Enter the personal center</a>
                                    <a class="fr" href="/logout/">Sign out</a>
                                </div>
                            </div>
                        </div>
                        <a href="usercenter-message.html">
                            <div class="msg-num"><span id="MsgNum">0</span></div>
                        </a>


                </div>
            </div>

    <div class="middle">
        <div class="wp">
            <a href="index.html"><img class="fl" src="{% static'images/logo2.png' %}"/></a>
            <h1>My Muxuenet</h1>
        </div>
    </div>
            </div>
    </header>
</section>
<!--crumbs start-->
    {% block custom_bread %}
    {% endblock %}

<section>
    <div class="wp list personal_list">
    <div class="left">
        <ul>
            <li class="active2"><a href="usercenter-info.html">Personal Information</a></li>
            <li ><a href="usercenter-mycourse.html">My Courses</a></li>
            <li ><a href="usercenter-fav-course.html">My Favorites</a></li>
            <li>
                <a href="usercenter-message.html" style="position: relative;">
                    My message
                </a>
            </li>
        </ul>
    </div>

    {% block custom_right_content %}
    {% endblock %}
    </div>
</section>



<script src="{% static'js/selectUi.js' %}" type='text/javascript'></script>
<script type="text/javascript" src="{% static'js/plugins/laydate/laydate.js' %}"></script>
<script src="{% static'js/plugins/layer/layer.js' %}"></script>
<script src="{% static'js/plugins/queryCity/js/public.js' %}" type="text/javascript"></script>
<script src="{% static'js/unslider.js' %}" type="text/javascript"></script>
<script src="{% static'js/plugins/jquery.scrollLoading.js' %}" type="text/javascript"></script>
<script src="{% static'js/validateDialog.js' %}" type="text/javascript"></script>
<script src="{% static'js/deco-common.js' %}" type="text/javascript"></script>

<script src="{% static'js/plugins/jquery.upload.js' %}" type='text/javascript'></script>
<script src="{% static'js/validate.js' %}" type="text/javascript"></script>
<script src="{% static'js/deco-user.js' %}"></script>

<script type="text/javascript">
    $('.jsDeleteFav_course').on('click', function(){
        var _this = $(this),
            favid = _this.attr('data-favid');
        alrt(favid)
        $.ajax({
                cache: false,
                type: "POST",
                url: "/org/add_fav/",
                data: {
                    fav_type: 1,
                    fav_id: favid,
                    csrfmiddlewaretoken: '799Y6iPeEDNSGvrTu3noBrO4MBLv6enY'
                },
                async: true,
                success: function(data) {
                    Dml.fun.winReload();
                }
            });
    });

    $('.jsDeleteFav_teacher').on('click', function(){
            var _this = $(this),
                favid = _this.attr('data-favid');
            $.ajax({
                    cache: false,
                    type: "POST",
                    url: "/org/add_fav/",
                    data: {
                        fav_type: 3,
                        fav_id: favid,
                        csrfmiddlewaretoken: '799Y6iPeEDNSGvrTu3noBrO4MBLv6enY'
                    },
                    async: true,
                    success: function(data) {
                        Dml.fun.winReload();
                    }
                });
        });


    $('.jsDeleteFav_org').on('click', function(){
            var _this = $(this),
                favid = _this.attr('data-favid');
            $.ajax({
                    cache: false,
                    type: "POST",
                    url: "/org/add_fav/",
                    data: {
                        fav_type: 2,
                        fav_id: favid,
                        csrfmiddlewaretoken: '799Y6iPeEDNSGvrTu3noBrO4MBLv6enY'
                    },
                    async: true,
                    success: function(data) {
                        Dml.fun.winReload();
                    }
                });
        });
</script>

{% block custom_js %}

{% endblock %}k %}

<script>
        var shareUrl ='',
            shareText ='',
            shareDesc ='',
            shareComment ='';
        $(function () {
            $(".bdsharebuttonbox a").mouseover(function () {
                var type = $(this).attr('data-cmd'),
                    $parent = $(this).parent('.bdsharebuttonbox'),
                    fxurl = $parent.attr('data-url'),
                    fxtext = $parent.attr('data-text'),
                    fxdesc = $parent.attr('data-desc'),
                    fxcomment = $parent.attr('data-comment');
                switch (type){
                    case'tsina':
                    case'tqq':
                    case'renren':
                            shareUrl = fxurl;
                            shareText = fxdesc;
                            shareDesc ='';
                            shareComment ='';
                        break;
                    default:
                            shareUrl = fxurl;
                            shareText = fxtext;
                            shareDesc = fxdesc;
                            shareComment = fxcomment;
                        break;
                }
            });
        });
        function SetShareUrl(cmd, config) {
            if (shareUrl) {
                config.bdUrl = "" + shareUrl;
            }
            if(shareText){
                config.bdText = shareText;
            }
            if(shareDesc){
                config.bdDesc = shareDesc;
            }
            if(shareComment){
                config.bdComment = shareComment;
            }

            return config;
        }
        window._bd_share_config = {
            "common": {
                "onBeforeClick":SetShareUrl,
                "bdPic":"",
                "bdMini":"2",
                "searchPic":"1",
                "bdMiniList":false
            },
            "share": {
                "bdSize":"16"
            }
        };
    with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='http://bdimg.share.baidu.com../api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];
</script>

</body>
</html>

(2) Modify'usercenter-info.html' to inherit usercenter-bae.html

{% load staticfiles %}

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
    <title>{% block title %}
    Personal Information-Muxue Online
    {% endblock %}</title>
    <link rel="stylesheet" type="text/css" href="{% static'css/reset.css' %}">
    <link rel="stylesheet" type="text/css" href="{% static'css/animate.css' %}">
    <link rel="stylesheet" type="text/css" href="{% static'css/style.css' %}">
    <link rel="stylesheet" type="text/css" href="{% static'js/plugins/queryCity/css/cityLayout.css' %}">
    {% block custom_css %}
    
    {% endblock %}
    <link rel="stylesheet" type="text/css" href="{% static'css/lq.datetimepick.css' %}"/>

    <script src="{% static'js/jquery.min.js' %}" type="text/javascript"></script>
    <script src="{% static'js/jquery-migrate-1.2.1.min.js' %}" type="text/javascript"></script>

</head>
<body>
<section class="headerwrap headerwrap2">
    <header>
        <div class="header2 header">
             <div class="top">
                <div class="wp">
                    <div class="fl"><p>Service call: <b>33333333</b></p></div>
                    <!--Jump after login-->


                        <div class="personal">
                            <dl class="user fr">
                                <dd>bobby<img class="down fr" src="{% static'js/jquery-migrate-1.2.1.min.js' %}"/></dd>
                                <dt><img width="20" height="20" src="{% static'media/image/2016/12/default_big_14.png' %}"/></dt>
                            </dl>
                            <div class="userdetail">
                                <dl>
                                    <dt><img width="80" height="80" src="{% static'media/image/2016/12/default_big_14.png' %}"/></dt>
                                    <dd>
                                        <h2>django</h2>
                                        <p>bobby</p>
                                    </dd>
                                </dl>
                                <div class="btn">
                                    <a class="personcenter fl" href="usercenter-info.html">Enter the personal center</a>
                                    <a class="fr" href="/logout/">Sign out</a>
                                </div>
                            </div>
                        </div>
                        <a href="usercenter-message.html">
                            <div class="msg-num"><span id="MsgNum">0</span></div>
                        </a>


                </div>
            </div>

    <div class="middle">
        <div class="wp">
            <a href="index.html"><img class="fl" src="{% static'images/logo2.png' %}"/></a>
            <h1>My Muxuenet</h1>
        </div>
    </div>
            </div>
    </header>
</section>
<!--crumbs start-->
    {% block custom_bread %}
    {% endblock %}

<section>
    <div class="wp list personal_list">
    <div class="left">
        <ul>
            <li class="active2"><a href="usercenter-info.html">Personal Information</a></li>
            <li ><a href="usercenter-mycourse.html">My Courses</a></li>
            <li ><a href="usercenter-fav-course.html">My Favorites</a></li>
            <li>
                <a href="usercenter-message.html" style="position: relative;">
                    My message
                </a>
            </li>
        </ul>
    </div>

    {% block custom_right_content %}
    {% endblock %}
    </div>
</section>
<!--sidebar start-->
<section>
    <ul class="sidebar">
        <li class="qq">
            <a target="_blank" href="http://wpa.qq.com/msgrd?v=3&uin=2023525077&site=qq&menu=yes"></a>
        </li>
        <li class="totop"></li>
    </ul>
</section>
<!--sidebar end-->
<!--header start-->

<div class="dialog" id="jsDialog">
    <div class="successbox dialogbox" id="jsSuccessTips">
        <h1>Submitted successfully</h1>
        <div class="close jsCloseDialog"><img src="{% static'' %}images/dig_close.png"/></div>
        <div class="cont">
            <h2>Your requirement is submitted successfully! </h2>
            <p></p>
        </div>
    </div>
    <!--Prompt pop-up box-->
    <div class="bidtips dialogbox promptbox" id="jsComfirmDialig">
        <h1>Confirm submission</h1>
        <div class="close jsCloseDialog"><img src="{% static'images/dig_close.png' %}"/></div>
        <div class="cont">
            <h2>Are you sure to submit? </h2>
            <dd class="autoTxtCount">
                <div class="button">
                    <input type="button" class="fl half-btn" value="OK" id="jsComfirmBtn"/>
                    <span class="fr half-btn jsCloseDialog">Cancel</span>
                </div>
            </dd>
        </div>
    </div>
    <div class="resetpwdbox dialogbox" id="jsResetDialog">
        <h1>Change password</h1>
        <div class="close jsCloseDialog"><img src="{% static'images/dig_close.png' %}"/></div>
        <div class="cont">
            <form id="jsResetPwdForm" autocomplete="off">
                <div class="box">
                    <span class="word2" >New  secret  code</span>
                    <input type="password" id="pwd" name="password1" placeholder="6-20 non-Chinese characters"/>
                </div>
                <div class="box">
                    <span class="word2" >Confirm password</span>
                    <input type="password" id="repwd" name="password2" placeholder="6-20 non-Chinese characters"/>
                </div>
                <div class="error btns" id="jsResetPwdTips"></div>
                <div class="button">
                    <input id="jsResetPwdBtn" type="button" value="Submit"/>
                </div>
                                   {% csrf_token %}
            </form>
        </div>
    </div>
    <div class="dialogbox changeemai1 changephone" id="jsChangeEmailDialog">
        <h1>Modify mailbox</h1>
        <div class="close jsCloseDialog"><img src="{% static'images/dig_close.png' %}"/></div>
        <p>Please enter a new email address</p>
        <form id="jsChangeEmailForm" autocomplete="off">
            <div class="box">
                <input class="fl change_email" name="email" id="jsChangeEmail" type="text" placeholder="Enter the re-bind email address">
            </div>
            <div class="box">
                <input class="fl email_code" type="text" id="jsChangeEmailCode" name="code" placeholder="input email verification code">
                <input class="getcode getting" type="button" id="jsChangeEmailCodeBtn" value="Get verification code">
            </div>
            <div class="error btns change_email_tips" id="jsChangeEmailTips" >Please enter...</div>
            <div class="button">
                <input class="changeemai_btn" id="jsChangeEmailBtn" type="button" value="Done"/>
            </div>
            {% csrf_token %}
        </form>
    </div>

    <div class="noactivebox dialogbox" id="jsUnactiveForm">
        <h1>Email verification prompt</h1>
        <div class="close jsCloseDialog"><img src="{% static'images/dig_close.png' %}"/></div>
        <div class="center">
            <img src="{% static'images/send.png' %}"/>
            <p>We have sent an email to your mailbox <span class="green" id="jsEmailToActive">12@13.com</span>,<br/>in order to ensure the security of your account, please verify your email in time </p>
            <p class="a"><a class="btn" id="jsGoToEmail" target="_blank" href="http://mail.qq.com">Go to email verification</a></p>
            <p class="zy_success upmove"></p>
            <p style="display: none;" class="sendE2">Not received, you can check your spam and filtered emails, or you can send the verification email again (<span class="c5c">60s</span >)</p>
            <p class="sendE">Not received, you can check your spam and filtered emails,<br/>you can also <span class="c5c green" id="jsSenEmailAgin" style="cursor: pointer;" >Send verification email again</span></p>
        </div>
    </div>
    <div class="resetpassbox dialogbox" id="jsSetNewPwd">
        <h1>Reset password</h1>
        <div class="close jsCloseDialog"><img src="{% static'images/dig_close.png' %}"/></div>
        <p class="green">Please enter a new password</p>
        <form id="jsSetNewPwdForm">
            <div class="box">
                <span class="word2">Password      code</span>
                <input type="password" name="password" id="jsResetPwd" placeholder="Please enter a new password"/>
            </div>
            <div class="box">
                <span class="word2">Accept recognize secret code</span>
                <input type="password" name="password2" id="jsResetPwd2" placeholder="Please enter the new password again"/>
            </div>
            <div class="box">
                <span class="word2">Check  Certificate  Code</span>
                <input type="text" name="code" id="jsResetCode" placeholder="Please enter the mobile phone verification code"/>
            </div>
            <div class="error btns" id="jsSetNewPwdTips"></div>
            <div class="button">
                <input type="hidden" name="mobile" id="jsInpResetMobil"/>
                <input id="jsSetNewPwdBtn" type="button" value="Submit"/>
            </div>
        </form>
    </div>
    <div class="forgetbox dialogbox">
        <h1>Forgot password</h1>
        <div class="close jsCloseDialog"><img src="{% static'images/dig_close.png' %}"/></div>
        <div class="cont">
            <form id="jsFindPwdForm" autocomplete="off">
                <div class="box">
                    <span class="word2" >Account      number</span>
                    <input type="text" id="account" name="account" placeholder="Mobile/Email"/>
                </div>
                <div class="box">
                    <span class="word3">Verification code</span>
                    <input autocomplete="off" class="form-control-captcha find-password-captcha" id="find-password-captcha_1" name="captcha_f_1" placeholder="Please enter the verification code" type="text"/> <input class="form-control-captcha find-password-captcha" id="find-password-captcha_0" name="captcha_f_0" placeholder="Please enter the verification code" type="hidden" value="5f3c00e47fb1be12d2fd15b9a860711597721b3f"/>  <img src="/captcha/image/5f3c00e47fb1be12d2fd15b9a860711597721b3f/" alt="captcha" class="captcha"/>
                </div>
                <div class="error btns" id="jsForgetTips"></div><!--Forgot password error-->
                <div class="button">
                    <input type="hidden" name="sms_type" value="1">
                    <input id="jsFindPwdBtn" type="button" value="Submit"/>
                </div>
            </form>
        </div>
    </div>
</div>
<div class="bg" id="dialogBg"></div>


<script src="{% static'js/selectUi.js' %}" type='text/javascript'></script>
<script type="text/javascript" src="{% static'js/plugins/laydate/laydate.js' %}"></script>
<script src="{% static'js/plugins/layer/layer.js' %}"></script>
<script src="{% static'js/plugins/queryCity/js/public.js' %}" type="text/javascript"></script>
<script src="{% static'js/unslider.js' %}" type="text/javascript"></script>
<script src="{% static'js/plugins/jquery.scrollLoading.js' %}" type="text/javascript"></script>
<script src="{% static'js/validateDialog.js' %}" type="text/javascript"></script>
<script src="{% static'js/deco-common.js' %}" type="text/javascript"></script>

<script src="{% static'js/plugins/jquery.upload.js' %}" type='text/javascript'></script>
<script src="{% static'js/validate.js' %}" type="text/javascript"></script>
<script src="{% static'js/deco-user.js' %}"></script>

<script type="text/javascript">
    $('.jsDeleteFav_course').on('click', function(){
        var _this = $(this),
            favid = _this.attr('data-favid');
        alrt(favid)
        $.ajax({
                cache: false,
                type: "POST",
                url: "/org/add_fav/",
                data: {
                    fav_type: 1,
                    fav_id: favid,
                    csrfmiddlewaretoken: '799Y6iPeEDNSGvrTu3noBrO4MBLv6enY'
                },
                async: true,
                success: function(data) {
                    Dml.fun.winReload();
                }
            });
    });

    $('.jsDeleteFav_teacher').on('click', function(){
            var _this = $(this),
                favid = _this.attr('data-favid');
            $.ajax({
                    cache: false,
                    type: "POST",
                    url: "/org/add_fav/",
                    data: {
                        fav_type: 3,
                        fav_id: favid,
                        csrfmiddlewaretoken: '799Y6iPeEDNSGvrTu3noBrO4MBLv6enY'
                    },
                    async: true,
                    success: function(data) {
                        Dml.fun.winReload();
                    }
                });
        });


    $('.jsDeleteFav_org').on('click', function(){
            var _this = $(this),
                favid = _this.attr('data-favid');
            $.ajax({
                    cache: false,
                    type: "POST",
                    url: "/org/add_fav/",
                    data: {
                        fav_type: 2,
                        fav_id: favid,
                        csrfmiddlewaretoken: '799Y6iPeEDNSGvrTu3noBrO4MBLv6enY'
                    },
                    async: true,
                    success: function(data) {
                        Dml.fun.winReload();
                    }
                });
        });
</script>

{% block custom_js %}

{% endblock %}k %}

<script>
        var shareUrl ='',
            shareText ='',
            shareDesc ='',
            shareComment ='';
        $(function () {
            $(".bdsharebuttonbox a").mouseover(function () {
                var type = $(this).attr('data-cmd'),
                    $parent = $(this).parent('.bdsharebuttonbox'),
                    fxurl = $parent.attr('data-url'),
                    fxtext = $parent.attr('data-text'),
                    fxdesc = $parent.attr('data-desc'),
                    fxcomment = $parent.attr('data-comment');
                switch (type){
                    case'tsina':
                    case'tqq':
                    case'renren':
                            shareUrl = fxurl;
                            shareText = fxdesc;
                            shareDesc ='';
                            shareComment ='';
                        break;
                    default:
                            shareUrl = fxurl;
                            shareText = fxtext;
                            shareDesc = fxdesc;
                            shareComment = fxcomment;
                        break;
                }
            });
        });
        function SetShareUrl(cmd, config) {
            if (shareUrl) {
                config.bdUrl = "" + shareUrl;
            }
            if(shareText){
                config.bdText = shareText;
            }
            if(shareDesc){
                config.bdDesc = shareDesc;
            }
            if(shareComment){
                config.bdComment = shareComment;
            }

            return config;
        }
        window._bd_share_config = {
            "common": {
                "onBeforeClick":SetShareUrl,
                "bdPic":"",
                "bdMini":"2",
                "searchPic":"1",
                "bdMiniList":false
            },
            "share": {
                "bdSize":"16"
            }
        };
    with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='http://bdimg.share.baidu.com../api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];
</script>

</body>
</html>

(3) Configure urls

MxOnline/urls.py

  #personal information
    path("users/", include('users.urls', namespace="users")),

users/urls.py

from django.urls import path,include,re_path
from .views import UserinfoView

app_name ='users'

urlpatterns = [
    #User Info
    path("info/", UserinfoView.as_view(),name='user_info'),
]

users/views.py

class UserinfoView(LoginRequiredMixin,View):
    '''User Personal Information'''
    def get(self,request):
        return render(request,'usercenter-info.html',{})

Then visit http://127.0.0.1:8000/users/info/to see if it can be displayed normally

(4) Display personal information

<ul class="right">
                        <li>nick       name:
                           <input type="text" name="nick_name" id="nick_name" value="{{ request.user.nick_name }}" maxlength="10">
                            <i class="error-tips"></i>
                        </li>
                        <li>Health       Day:
                           <input type="text" id="birth_day" name="birday" value="{{ request.user.birthday }}" readonly="readonly"/>
                            <i class="error-tips"></i>
                        </li>
                        <li>Sex       Don't:
                            <label>     <input type="radio" name="gender" value="male" {% if request.user.gender =='male' %}checked="checked" {% endif %}>Male</label>
                            <label>      <input type="radio" name="gender" value="female" {% if request.user.gender =='female' %}checked=" checked"{% endif %}">Female</label>
                        </li>
                        <li class="p_infor_city">Place       Address:
                            <input type="text" name="address" id="address" placeholder="Please enter your address" value="{{ request.user.adress }}" maxlength="10">
                            <i class="error-tips"></i>
                        </li>
                        <li>Hand  machine  number:
                            <input type="text" name="mobile" id="mobile" placeholder="Please enter your mobile phone number" value="{{ request.user.mobile|default_if_none:'' }}" maxlength="10" >
                        </li>
                        <li>Mail       Box:
                            <input class="borderno" type="text" name="email" readonly="readonly" value="{{ request.user.email }}"/>
                            <span class="green changeemai_btn">[edit]</span>
                        </li>
                        <li class="button heibtn">
                            <input type="button" id="jsEditUserBtn" value="Save">
                        </li>
                    </ul>
Description:
  {{ request.user.mobile|default_if_none:'' }} If the field has no value, the value defaults to an empty string

11.2. Modify user image

 (1)url

#User image upload
    path("image/upload", UploadImageView.as_view(),name='image_upload'),

(2)urers/forms.py

class UploadImageForm(forms.ModelForm):
    '''User changes image'''
    class Meta:
        model = UserProfile
        fields = ['image']

(3)views.py

class UploadImageView(LoginRequiredMixin,View):
    '''User image modification'''
    def post(self,request):
        #Uploaded files are all obtained in request.FILES, so here we need to pass one more parameter
        image_form = UploadImageForm(request.POST,request.FILES)
        if image_form.is_valid():
            image = image_form.cleaned_data['image']
            request.user.image = image
            request.user.save()
            return HttpResponse('{"status":"success"}', content_type='application/json')
        else:
            return HttpResponse('{"status":"fail"}', content_type='application/json')

(4) Front-end page

11.3. Modify password

 (1)urls

#User Personal Center Modify Password
    path("update/pwd/", UpdatePwdView.as_view(),name='update_pwd'),

(2) Background processing

class UpdatePwdView(View):
    """
    Change user password in personal center
    """
    def post(self, request):
        modify_form = ModifyPwdForm(request.POST)
        if modify_form.is_valid():
            pwd1 = request.POST.get("password1", "")
            pwd2 = request.POST.get("password2", "")
            if pwd1 != pwd2:
                return HttpResponse('{"status":"fail","msg":"Passwords are inconsistent"}', content_type='application/json')
            user = request.user
            user.password = make_password(pwd2)
            user.save()

            return HttpResponse('{"status":"success"}', content_type='application/json')
        else:
            return HttpResponse(json.dumps(modify_form.errors), content_type='application/json')

(3) The Ajxa code is placed in deco-user.js

$(function(){
   //Personal information change password
    $('#jsUserResetPwd').on('click', function(){
        Dml.fun.showDialog('#jsResetDialog','#jsResetPwdTips');
    });

    $('#jsResetPwdBtn').click(function(){
        $.ajax({
            cache: false,
            type: "POST",
            dataType:'json',
            url:"",
            data:$('#jsResetPwdForm').serialize(),
            async: true,
            success: function(data) {
                if(data.password1){
                    Dml.fun.showValidateError($("#pwd"), data.password1);
                }else if(data.password2){
                    Dml.fun.showValidateError($("#repwd"), data.password2);
                }else if(data.status == "success"){
                    Dml.fun.showTipsDialog({
                        title:'Submitted successfully',
                        h2:'Modify the password successfully, please log in again!',
                    });
                    Dml.fun.winReload();
                }else if(data.msg){
                    Dml.fun.showValidateError($("#pwd"), data.msg);
                    Dml.fun.showValidateError($("#repwd"), data.msg);
                }
            }
        });
    });

(4) Modify the login personal status in the upper right corner

 base.html

  <header>
        <div class=" header">
            <div class="top">
                <div class="wp">
                    <div class="fl"><p>Service call: <b>33333333</b></p></div>
                    <!--Jump after login-->

                    {% if request.user.is_authenticated %}
                        <div class="personal">
                            <dl class="user fr">
                                <dd>{{ user.username }}<img class="down fr"
                                                            src="{% static "images/top_down.png" %}"/></dd>
                                <dt><img width="20" height="20" src="{{ MEDIA_URL }}{{ request.user.image }}"/></dt>
                            </dl>
                            <div class="userdetail">
                                <dl>
                                    <dt><img width="80" height="80" src="{{ MEDIA_URL }}{{ request.user.image }}"/></dt>
                                    <dd>
                                        <h2>{{ request.user.nick_name }}</h2>
                                        <p>{{ request.user.username }}</p>
                                    </dd>
                                </dl>
                                <div class="btn">
                                    <a class="personcenter fl" href="{% url'users:user_info' %}">Enter the personal center</a>
                                    <a class="fr" href="{% url'logout' %}">Logout</a>
                                </div>
                            </div>
                        </div>
                    {% else %}
                        <a style="color:white" class="fr registerbtn" href="{% url'register' %}">Register</a>
                        <a style="color:white" class="fr loginbtn" href="{% url'login' %}">Login</a>
                    {% endif %}


                </div>
            </div>

Also modify org_base.html and user-center.html

11.4. Send email verification code

(1) EmailVerifyRecord Models

  • Add a choices
  • Change the max_length of send_type to 30
send_choices = (
        ('register','register'),
        ('forget','recover password'),
        ('update_email','modify email')
    )
class EmailVerifyRecord(models.Model):
    send_choices = (
        ('register','register'),
        ('forget','recover password'),
        ('update_email','modify email')
    )

    code = models.CharField('Verification Code',max_length=20)
    email = models.EmailField('Mailbox',max_length=50)
    send_type = models.CharField(choices=send_choices,max_length=30)
    send_time = models.DateTimeField(default=datetime.now)

    class Meta:
        verbose_name ='E-mail verification code'
        verbose_name_plural = verbose_name

(2)url

#Send Email Verification Code
    path("sendemail_code/", SendEmailCodeView.as_view(),name='sendemail_code'),

(3)view

class SendEmailCodeView(LoginRequiredMixin, View):
    '''Send email to modify verification code'''
    def get(self,request):
        email = request.GET.get('email','')

        if UserProfile.objects.filter(email=email):
            return HttpResponse('{"email":"Email already exists"}', content_type='application/json')

        send_register_eamil(email,'update_email')
        return HttpResponse('{"status":"success"}', content_type='application/json')

(4) urils/email_send.py

  • Add a send_type update_email
  • The length of the verification code for update_email is 4
# apps/utils/email_send.py

from random import Random
from django.core.mail import send_mail

from users.models import EmailVerifyRecord
from MxOnline.settings import EMAIL_FROM

# Generate random string
def random_str(random_length=8):
    str =''
    # Optional string to generate string
    chars ='AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789'
    length = len(chars)-1
    random = Random()
    for i in range(random_length):
        str += chars[random.randint(0, length)]
    return str

# Send registration email
def send_register_eamil(email, send_type="register"):
    # Save to the database before sending, then check if the link exists
    # Instantiate an EmailVerifyRecord object
    email_record = EmailVerifyRecord()
    # Generate random code into the link
    if send_type =='update_email':
        code = random_str(4)
    else:
        code = random_str(16)
    email_record.code = code
    email_record.email = email
    email_record.send_type = send_type

    email_record.save()

    # Define the email content:
    email_title = ""
    email_body = ""

    if send_type == "register":
        email_title = "NBA registration activation link"
        email_body = "Please click the link below to activate your account: http://127.0.0.1:8000/active/{0}".format(code)

        # Use Django built-in functions to complete email sending. 4.parameters: subject, email content, where to send, recipient list
        send_status = send_mail(email_title, email_body, EMAIL_FROM, [email])
        # If the sending is successful
        if send_status:
            pass

    elif send_type == "forget":
        email_title = "NBA Retrieve Password Link"
        email_body = "Please click the link below to retrieve your password: http://127.0.0.1:8000/reset/{0}".format(code)

        # Use Django built-in functions to complete email sending. 4.parameters: subject, email content, where to send, recipient list
        send_status = send_mail(email_title, email_body, EMAIL_FROM, [email])
        # If the sending is successful
        if send_status:
            pass

    elif send_type == "update_email":
        email_title = "NBA Email Modification Verification Code"
        email_body = "Your email verification code is {0}".format(code)

        # Use Django built-in functions to complete email sending. 4.parameters: subject, email content, where to send, recipient list
        send_status = send_mail(email_title, email_body, EMAIL_FROM, [email])
        # If the sending is successful
        if send_status:
            pass

(4) Ajax

The Ajax code is in dec-user.js

//Modify personal center email verification code
function sendCodeChangeEmail($btn){
    var verify = verifyDialogSubmit(
        [
          {id:'#jsChangeEmail', tips: Dml.Msg.epMail, errorTips: Dml.Msg.erMail, regName:'email', require: true}
        ]
    );
    if(!verify){
       return;
    }
    $.ajax({
        cache: false,
        type: "get",
        dataType:'json',
        url:"/users/sendemail_code/",
        data:$('#jsChangeEmailForm').serialize(),
        async: true,
        beforeSend:function(XMLHttpRequest){
            $btn.val("Sending...");
            $btn.attr('disabled',true);
        },
        success: function(data){
            if(data.email){
                Dml.fun.showValidateError($('#jsChangeEmail'), data.email);
            }else if(data.status =='success'){
                Dml.fun.showErrorTips($('#jsChangeEmailTips'), "Email verification code has been sent");
            }else if(data.status =='failure'){
                 Dml.fun.showValidateError($('#jsChangeEmail'), "Failed to send email verification code");
            }else if(data.status =='success'){
            }
        },
        complete: function(XMLHttpRequest){
            $btn.val("Get verification code");
            $btn.removeAttr("disabled");
        }
    });

}

test:

11.5. Modify the mailbox

(1) urls

#Modify mailbox
    path("update_email/", UpdateEmailView.as_view(),name='update_email'),

(2)view

class UpdateEmailView(LoginRequiredMixin, View):
    '''Modify mailbox'''
    def post(self, request):
        email = request.POST.get("email", "")
        code = request.POST.get("code", "")

        existed_records = EmailVerifyRecord.objects.filter(email=email, code=code, send_type='update_email')
        if existed_records:
            user = request.user
            user.email = email
            user.save()
            return HttpResponse('{"status":"success"}', content_type='application/json')
        else:
            return HttpResponse('{"email":"The verification code is invalid"}', content_type='application/json')

(3) Ajax

//Personal information email modification
function changeEmailSubmit($btn){
var verify = verifyDialogSubmit(
        [
          {id:'#jsChangeEmail', tips: Dml.Msg.epMail, errorTips: Dml.Msg.erMail, regName:'email', require: true},
        ]
    );
    if(!verify){
       return;
    }
    $.ajax({
        cache: false,
        type:'post',
        dataType:'json',
        url:"/users/update_email/",
        data:$('#jsChangeEmailForm').serialize(),
        async: true,
        beforeSend:function(XMLHttpRequest){
            $btn.val("Sending...");
            $btn.attr('disabled',true);
            $("#jsChangeEmailTips").html("Verifying...").show(500);
        },
        success: function(data) {
            if(data.email){
                Dml.fun.showValidateError($('#jsChangeEmail'), data.email);
            }else if(data.status == "success"){
                Dml.fun.showErrorTips($('#jsChangePhoneTips'), "Email information updated successfully");
                setTimeout(function(){location.reload();},1000);
            }else{
                 Dml.fun.showValidateError($('#jsChangeEmail'), "Email information update failed");
            }
        },
        complete: function(XMLHttpRequest){
            $btn.val("Complete");
            $btn.removeAttr("disabled");
        }
    });
}

11.6. Personal information modification

(1) users/form.py

class UserInfoForm(forms.ModelForm):
    '''Personal Center Information Modification'''
    class Meta:
        model = UserProfile
        fields = ['nick_name','gender','birthday','address','mobile']

(2)view

class UserinfoView(LoginRequiredMixin,View):
    '''User Personal Information'''
    def get(self,request):
        return render(request,'usercenter-info.html')

    def post(self, request):
        user_info_form = UserInfoForm(request.POST, instance=request.user)
        if user_info_form.is_valid():
            user_info_form.save()
            return HttpResponse('{"status":"success"}', content_type='application/json')
        else:
            return HttpResponse(json.dumps(user_info_form.errors), content_type='application/json')

11.7. My Course

(1) url

#My courses
    path("mycourse/", MyCourseView.as_view(),name='mycourse'),

(2)view

class MyCourseView(LoginRequiredMixin, View):
    '''My courses'''
    def get(self, request):
        user_courses = UserCourse.objects.filter(user=request.user)
        return render(request, "usercenter-mycourse.html", {
            "user_courses":user_courses,
        })

(3)usercenter-mucoure.html

{% extends'usercenter-base.html' %}
{% block title %}
    My courses
{% endblock %}
{% block custom_bread %}
    <section>
        <div class="wp">
            <ul class="crumbs">
                <li><a href="{% url'index' %}">Homepage</a>></li>
                <li><a href="/user/home/">Personal Center</a>></li>
                <li>My courses</li>
            </ul>
        </div>
    </section>
    {% endblock %}

{% block custom_right_content %}
    <div class="right">
        <div class="personal_des Releasecont">
            <div class="head">
                <h1>My courses</h1>
            </div>
        </div>
        <div class="personal_des permessage">
            <div class="companycenter">
                <div class="group_list brief">
                    {% for user_course in user_courses %}
                    <div class="module1_5 box">
                            <a href="{% url'course:course_detail' user_course.course.id %}">
                                <img width="214" height="190" class="scrollLoading" src="{{ MEDIA_URL }}{{ user_course.course.image }}"/>
                            </a>
                            <div class="des">
                                <a href="course-detail.html"><h2>{{ user_course.course.name }}</h2></a>
                                <span class="fl">Class hours: <i class="key">{{ user_course.course.learn_times }}</i></span>
                                <span class="fr">Number of students: {{ user_course.course.students }}</span>
                            </div>
                            <div class="bottom">
                                <span class="fl">{{ user_course.course.course_org.name }}</span>
                                <span class="star fr notlogin" data-favid="15">{{ user_course.course.fav_nums }}</span>
                            </div>
                        </div>
                    {% endfor %}
                </div>
            </div>
        </div>
    </div>
{% endblock %}

11.8. My Collection-Course Organization

(1) url

 # My Collection--Course Organization
    path('myfav/org/', MyFavOrgView.as_view(), name="myfav_org"),

(2) view

class MyFavOrgView(LoginRequiredMixin,View):
    '''My favorite course institution'''

    def get(self, request):
        org_list = []
        fav_orgs = UserFavorite.objects.filter(user=request.user, fav_type=2)
        # The fav_orgs above just stores the id. We also need to find institutional objects by id
        for fav_org in fav_orgs:
            # Take out fav_id which is the id of the organization.
            org_id = fav_org.fav_id
            # Get this institution object
            org = CourseOrg.objects.get(id=org_id)
            org_list.append(org)
        return render(request, "usercenter-fav-org.html", {
            "org_list": org_list,
        })

(3) Template usercenter-fav-org.html

{% extends'usercenter-base.html' %}
{% load staticfiles %}
{% block title %}
    my collection
{% endblock %}
{% block custom_bread %}
    <section>
        <div class="wp">
            <ul class="crumbs">
                <li><a href="{% url'index' %}">Homepage</a>></li>
                <li><a href="/user/home/">Personal Center</a>></li>
                <li>My collection</li>
            </ul>
        </div>
    </section>
    {% endblock %}

{% block custom_right_content %}
    <div class="right">
            <div class="personal_des Releasecont">
                <div class="head">
                    <h1>My favorites</h1>
                </div>

            </div>
            <div class="personal_des permessage">
                <div class="head">
                    <ul class="tab_header messagehead">
                        <li class="active"><a href="usercenter-fav-course.html">Course institution</a> </li>
                        <li><a href="usercenter-fav-teacher.html">Teacher</a></li>
                        <li><a href="usercenter-fav-course.html">Open Course</a></li>
                    </ul>
                </div>
                <div class="messagelist">
                    {% for org in org_list %}
                    <div class="messages butler_list company company-fav-box">
                        <dl class="des fr">
                            <dt>
                                <a href="{% url'org:org_home' org.id %}">
                                    <img width="160" height="90" src="{{ MEDIA_URL }}{{ org.image }}"/>
                                </a>
                            </dt>
                            <dd>
                                <h1><a href="org-detail-homepage.html">{{ org.name }}</a></h1>
                                <div class="pic fl" style="width:auto;">

                                    <img src="{% static'images/authentication.png' %}"/>


                                    <img src="{% static'images/gold.png' %}"/>

                                </div>
                                <span class="c8 clear">{{ org.address }}</span>
                                <div class="delete jsDeleteFav_org" data-favid="{{org.id}}"></div>
                            </dd>
                        </dl>
                    </div>
                    {% endfor %}
                </div>
            </div>
        </div>
{% endblock %}

11.9. My Collection-Lecturer

Teacher adds a method

    def get_course_nums(self):
        return self.course_set.all().count()

url, view and template

# My Collection--Lecturer
    path('myfav/teacher/', MyFavTeacherView.as_view(), name="myfav_teacher"),
class MyFavTeacherView(LoginRequiredMixin, View):
    '''My favorite lecturer'''

    def get(self, request):
        teacher_list = []
        fav_teachers = UserFavorite.objects.filter(user=request.user, fav_type=3)
        for fav_teacher in fav_teachers:
            teacher_id = fav_teacher.fav_id
            teacher = Teacher.objects.get(id=teacher_id)
            teacher_list.append(teacher)
        return render(request, "usercenter-fav-teacher.html", {
            "teacher_list": teacher_list,
        })
{% extends'usercenter-base.html' %}
{% load staticfiles %}
{% block title %}
    my collection
{% endblock %}
{% block custom_bread %}
    <section>
        <div class="wp">
            <ul class="crumbs">
                <li><a href="{% url'index' %}">Homepage</a>></li>
                <li><a href="/user/home/">Personal Center</a>></li>
                <li>My collection</li>
            </ul>
        </div>
    </section>
    {% endblock %}

{% block custom_right_content %}
<div class="right">
            <div class="personal_des Releasecont">
                <div class="head">
                    <h1>My favorites</h1>
                </div>
            </div>
            <div class="personal_des permessage">
                <div class="head">
                    <ul class="tab_header messagehead">
                        <li ><a href="{% url'users:myfav_org' %}">Course institution</a> </li>
                        <li class="active"><a href="{% url'users:myfav_teacher' %}">Teacher</a></li>
                        <li><a href="usercenter-fav-course.html">Open Course</a></li>
                    </ul>
                </div>
                <div class="messagelist">
                    {% for teacher in teacher_list %}
                    <div class=" butler_list butler-fav-box">
                        <dl class="des users">
                            <dt>
                                <a href="{% url'org:teacher_detail' teacher.id %}">
                                    <img width="100" height="100" src="{{ MEDIA_URL }}{{ teacher.image }}"/>
                                </a>
                            </dt>
                            <dd>
                                <h1>
                                    <a href="{% url'org:teacher_detail' teacher.id %}">
                                        {{ teacher.name }}<span class="key">certified teacher</span>
                                    </a>
                                </h1>
                                <ul class="cont clearfix">
                                    <li class="time">Working years: <span>{{ teacher.work_years }} years</span></li>
                                    <li class="c7">Number of courses: <span>{{ teacher.get_course_nums }}</span></li>
                                </ul>
                                <ul class="cont clearfix">
                                    <li class="time">Work company: <span>{{ teacher.work_company }}</span></li>
                                    <li class="c7">Company position: <span>{{ teacher.work_position }}</span></li>
                                </ul>
                            </dd>
                            <div class="delete jsDeleteFav_teacher" data-favid="{{teacher.id}}"></div>
                        </dl>
                    </div>
                    {% endfor %}





                </div>
            </div>
        </div>
{% endblock %}

11.10. My Collection-Open Course

 #我的Collection--Course
    path('myfav/course/', MyFavCourseView.as_view(), name="myfav_course"),
class MyFavCourseView(LoginRequiredMixin,View):
    """
    My favorite courses
    """
    def get(self, request):
        course_list = []
        fav_courses = UserFavorite.objects.filter(user=request.user, fav_type=1)
        for fav_course in fav_courses:
            course_id = fav_course.fav_id
            course = Course.objects.get(id=course_id)
            course_list.append(course)

        return render(request,'usercenter-fav-course.html', {
            "course_list":course_list,
        })
{% extends'usercenter-base.html' %}
{% load staticfiles %}
{% block title %}
    my collection
{% endblock %}
{% block custom_bread %}
    <section>
        <div class="wp">
            <ul class="crumbs">
                <li><a href="{% url'index' %}">Homepage</a>></li>
                <li><a href="/user/home/">Personal Center</a>></li>
                <li>My collection</li>
            </ul>
        </div>
    </section>
    {% endblock %}

{% block custom_right_content %}
    <div class="right">
            <div class="personal_des Releasecont">
                <div class="head">
                    <h1>My favorites</h1>
                </div>
            </div>
            <div class="personal_des permessage">
                <div class="head">
                    <ul class="tab_header messagehead">
                        <li ><a href="{% url'users:myfav_org' %}">Course institution</a> </li>
                        <li ><a href="{% url'users:myfav_teacher' %}">Teacher</a></li>
                        <li class="active"><a href="{% url'users:myfav_course' %}">Open course</a></li>
                    </ul>

                </div>
                <div class="companycenter">
                    <div class="group_list brief">
                        {% for fav_course in course_list %}
                        <div class="module1_5 box">
                            <a href="{% url'course:course_detail' fav_course.id %}">
                                <img width="214" height="190" src="{{ MEDIA_URL }}{{ fav_course.image }}"/>
                            </a>
                            <div class="des">
                                <a href="{% url'course:course_detail' fav_course.id %}"><h2>{{ fav_course.name }}</h2></a>
                                <span class="fl">Duration: <i class="key">{{ fav_course.learn_times }}</i></span>
                                <span class="fr">Number of students: {{ fav_course.students }}</span>
                            </div>
                            <div class="bottom">
                                <span class="fl">{{ fav_course.course_org.name }}</span>
                                <span class="delete-group fr jsDeleteFav_course" data-favid="{{fav_course.id}}"></span>
                            </div>
                        </div>
                        {% endfor %}
                    </div>
                </div>
            </div>
        </div>
{% endblock %}

11.11. My message

(1) url

#我的信息
    path('my_message/', MyMessageView.as_view(), name="my_message"),

(2)view

class MyMessageView(LoginRequiredMixin, View):
    '''My message'''

    def get(self, request):
        all_message = UserMessage.objects.filter(user = request.user.id)

        try:
            page = request.GET.get('page', 1)
        except PageNotAnInteger:
            page = 1
        p = Paginator(all_message, 4,request=request)
        messages = p.page(page)
        return render(request, "usercenter-message.html", {
        "messages":messages,
        })

(3) Template usercenter-message.html

{% extends'usercenter-base.html' %}
{% load staticfiles %}
{% block title %}
    My message
{% endblock %}
{% block custom_bread %}
    <section>
        <div class="wp">
            <ul class="crumbs">
                <li><a href="{% url'index' %}">Homepage</a>></li>
                <li><a href="/user/home/">Personal Center</a>></li>
                <li>My message</li>
            </ul>
        </div>
    </section>
    {% endblock %}

{% block custom_right_content %}
    <div class="right">
        <div class="personal_des Releasecont">
            <div class="head">
                <h1>My message</h1>
            </div>

        </div>
        <div class="personal_des permessage">
            <div class="head">
                <ul class="tab_header messagehead">
                    <li class="active"><a href="/user/message/">Personal messages</a> </li>
                </ul>
            </div>
            <div class="messagelist">
                    {% for message in messages.object_list %}
                    <div class="messages">
                        <div class="fr">
                            <div class="top"><span class="fl time">{{ message.add_time }}</span><span class="fr btn foldbtn"></span></div>
                            <p>
                                {{ message.message }}
                            </p>
                        </div>
                    </div>
                    {% endfor %}
            </div>

            <div class="pageturn pagerright">
                <ul class="pagelist">
                            {% if messages.has_previous %}
                                <li class="long"><a href="?{{ messages.previous_page_number.querystring }}">Previous page</a></li>
                            {% endif %}

                            {% for page in messages.pages %}
                                {% if page %}
                                    {% ifequal page messages.number %}
                                        <li class="active"><a href="?{{ page.querystring }}">{{ page }}</a></li>
                                    {% else %}
                                        <li><a href="?{{ page.querystring }}" class="page">{{ page }}</a></li>
                                    {% endifequal %}
                                {% else %}
                                    <li class="none"><a href="">...</a></li>
                                {% endif %}
                            {% endfor %}
                            {% if messages.has_next %}
                                <li class="long"><a href="?{{ messages.next_page_number.querystring }}">Next page</a></li>
                            {% endif %}
                        </ul>
            </div>
        </div>

    </div>
{% endblock %}

11.12.logout

(1)url

path('logout/', LogoutView.as_view(), name="logout"),

(2)view

class LogoutView(View):
    '''User logout'''
    def get(self,request):
        logout(request)
        from django.urls import reverse
        return HttpResponseRedirect(reverse('index'))

(3) Add a link to each base page

<a class="fr" href="{% url'logout' %}">Logout</a>

11.13. Hits

(1) Course CourseInfoView

course.students += 1
course.save()

(2) TeacherDetailView

teacher.click_nums += 1
teacher.save()

(3) OrgHomeView

course_org.click_nums += 1
course_org.save()

11.14. Number of collections

AddFavView in organization/views.py

When subtracting

        exist_record.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()

When adding

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()
class AddFavView(View):
    """
    User favorites and unfavorites
    """
    def post(self, request):
        fav_id = request.POST.get('fav_id', 0) # Prevent errors in the back int(fav_id)
        fav_type = request.POST.get('fav_type', 0) # Prevent int(fav_type) error

        if not request.user.is_authenticated:
            # When you are not logged in, return json to prompt you are not logged in. Jumping to the login page is done in ajax
            return HttpResponse('{"status":"fail", "msg":"User not logged in"}', content_type='application/json')

        exist_record = UserFavorite.objects.filter(user=request.user, fav_id=int(fav_id), fav_type=int(fav_type))
        if exist_record:
            # If the record already exists, it means that the user has cancelled
            exist_record.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":"fail", "msg":"Uncollected"}', content_type='application/json')
        else:
            user_fav = UserFavorite()
            if int(fav_id)> 0 and int(fav_type)> 0:
                user_fav.user = request.user
                user_fav.fav_id = int(fav_id)
                user_fav.fav_type = int(fav_type)
                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":"Collection"}', content_type='application/json')
            else:
                return HttpResponse('{"status":"fail", "msg":"Collection error"}', content_type='application/json')
Reference: https://cloud.tencent.com/developer/article/1091414 Django+xadmin to build an online education platform (8)-Cloud + Community-Tencent Cloud