(十)Django 在线平台(用户修改头像, 修改密码功能)

用户修改头像功能

配置url

# !/usr/bin/env python 
# -*- coding:utf-8 -*-
__author__ = '_X.xx_'
__date__ = '2018/6/13 18:26'

from django.conf.urls import url
from .views import UserinfoView, UploadImageView

urlpatterns = [
    # 用户信息
    url(r'^info/$', UserinfoView.as_view(), name='user_info'),
    # 用户头像上传
    url(r'^image_upload/$', UploadImageView.as_view(), name='image_upload'),

]

编写usersApp下的forms

class UploadImageForm(forms.ModelForm):
    """
        处理用户上传头像
    """
    class Meta:
        model = UserProfile
        fields = ['image']

编写View视图函数

class UploadImageView(LoginRequiredMixin, View):
    """
        用户修改头像
    """

    def post(self, request):
        image_form = UploadImageForm(request.POST, request.FILES,
                                     instance=request.user)
        if image_form.is_valid():
            image_form.save()
            return HttpResponse('{"status":"success"}',
                                content_type='application/json')
        else:
            return HttpResponse('{"status":"fail"}',
                                content_type='application/json')

配置前端页面

iframe id='frameFile' name='frameFile' style='display: none;'>iframe>
<form class="clearfix" id="jsAvatarForm" enctype="multipart/form-data" autocomplete="off" method="post" action="{% url 'users:image_upload' %}" target='frameFile'>
    <label class="changearea" for="avatarUp">
        <span id="avatardiv" class="pic">
            <img width="100" height="100" class="js-img-show" id="avatarShow" src="{{ MEDIA_URL }}{{ request.user.image }}"/>
        span>
        <span class="fl upload-inp-box" style="margin-left:70px;">
            <span class="button btn-green btn-w100" id="jsAvatarBtn">修改头像span>
            <input type="file" name="image" id="avatarUp" class="js-img-up"/>
        span>
    label>
    {% csrf_token %}
form>
(十)Django 在线平台(用户修改头像, 修改密码功能)_第1张图片

用户个人中心修改密码

1.配置urls

# !/usr/bin/env python 
# -*- coding:utf-8 -*-
__author__ = '_X.xx_'
__date__ = '2018/6/13 18:26'

from django.conf.urls import url
from .views import UserinfoView, UploadImageView, UpdatePwdView

urlpatterns = [
    # 用户信息
    url(r'^info/$', UserinfoView.as_view(), name='user_info'),
    # 用户头像上传
    url(r'^image/upload/$', UploadImageView.as_view(), name='image_upload'),
    # 用户个人中心修改密码
    url(r'^update/pwd/$', UpdatePwdView.as_view(), name='update_pwd'),
]

2.编写view视图函数

class UpdatePwdView(View):
    """
        个人中心修改用户密码
    """

    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": "密码不一致"}',
                                    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.js代码

$(function(){
    //个人资料修改密码
    $('#jsUserResetPwd').on('click', function(){
        Dml.fun.showDialog('#jsResetDialog', '#jsResetPwdTips');
    });

    $('#jsResetPwdBtn').click(function(){
        $.ajax({
            cache: false,
            type: "POST",
            dataType:'json',
            url:"/users/update/pwd/",
            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:'提交成功',
                        h2:'修改密码成功,请重新登录!',
                    });
                    Dml.fun.winReload();
                }else if(data.msg){
                    Dml.fun.showValidateError($("#pwd"), data.msg);
                    Dml.fun.showValidateError($("#repwd"), data.msg);
                }
            }
        });
    });
//个人资料头像
$('.js-img-up').uploadPreview({ Img: ".js-img-show", Width: 94, Height: 94 ,Callback:function(){
    $('#jsAvatarForm').submit();
}});


$('.changeemai_btn').click(function(){
    Dml.fun.showDialog('#jsChangeEmailDialog', '#jsChangePhoneTips' ,'jsChangeEmailTips');
});
$('#jsChangeEmailCodeBtn').on('click', function(){
    sendCodeChangeEmail($(this));
});
$('#jsChangeEmailBtn').on('click', function(){
    changeEmailSubmit($(this));
});
(十)Django 在线平台(用户修改头像, 修改密码功能)_第2张图片

配置前端页面登录后显示登录状态 (把3个base页面替换

<div class="top">
   <div class="wp">
      <div class="fl"><p>服务电话:<b>33333333b>p>div>
      
                     {% if request.user.is_authenticated %}
                     <div class="personal">
                         <dl class="user fr">
                             <dd>{{ user.username }}<img class="down fr" src="{% static "/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' %}">进入个人中心a>
                              <a class="fr" href="#">退出a>
                             div>
                         div>
                     div>
                     <a href="#">
                         <div class="msg-num"> <span id="MsgNum">{{ request.user.unread_nums }}span>div>
                     a>
                      {% else %}
                     <a style="color:white" class="fr registerbtn" href="{% url 'register' %}">注册a>
                     <a style="color:white" class="fr loginbtn" href="{% url 'login' %}">登录a>
                     {% endif %}


   div>
div>
(十)Django 在线平台(用户修改头像, 修改密码功能)_第3张图片

你可能感兴趣的:(Django)