全局搜索,用户中心
标签: django
导航功能条的选中状态
根据其中request.path 并结合模板中的slice 函数进行匹配连接中的内容进行导航栏的选中状态确定。
<nav>
<div class="nav">
<div class="wp">
<ul>
<li {% if request.path == '/' %}class="active"{% endif %}><a href="{% url 'index' %}">首页</a></li>
<li {% if request.path|slice:'7' == '/course' %}class="active"{% endif %}>
<a href="{% url 'course:course_list' %}">
公开课<img class="hot" src="/static/images/nav_hot.png">
</a>
</li>
<li {% if request.path|slice:'12' == '/org/teacher' %}class="active"{% endif %}>
<a href="{% url 'org:teacher_list' %}">授课教师</a>
</li>
<li {% if request.path|slice:'9' == '/org/list' %}class="active"{% endif %} ><a href="{% url 'org:org_list' %}">授课机构</a></li>
</ul>
</div>
</div>
</nav>
搜索功能的实现
通过js进行连接的变更,并通过django中orm的__icontains进行like字段的匹配。
keywords = request.GET.get('keywords', '')
if keywords:
all_teachers = all_teachers.filter(Q(name__icontains=keywords) | Q(points__icontains=keywords) | Q(work_company__icontains=keywords))
用户个人中心
修改界面,找到界面的公共部分,作为一个基准界面。
{% extends 'common/usercenter_base.html' %}
{% block title %}个人中心{% endblock %}
{% load staticfiles %}
{% block custom_content %}
<div class="right">
<div class="personal_des ">
<div class="head" style="border:1px solid #eaeaea;">
<h1>个人信息</h1>
</div>
<div class="inforcon">
<div class="left" style="width:242px;">
<iframe id='frameFile' name='frameFile' style='display: none;'></iframe>
<form class="clearfix" id="jsAvatarForm" enctype="multipart/form-data" autocomplete="off" method="post" action="{% url 'user: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>
<div style="border-top:1px solid #eaeaea;margin-top:30px;">
<a class="button btn-green btn-w100" id="jsUserResetPwd" style="margin:80px auto;width:100px;">修改密码</a>
</div>
</div>
<form class="perinform" id="jsEditUserForm" autocomplete="off">
<ul class="right">
<li>昵 称:
<input type="text" name="nick_name" id="nick_name" value="{{ request.user.nick_name }}" maxlength="10">
<i class="error-tips"></i>
</li>
<li>生 日:
<input type="text" id="birth_day" name="birday" value="{{ request.user.birthday }}" readonly="readonly"/>
<i class="error-tips"></i>
</li>
<li>性 别:
<label> <input type="radio" name="gender" value="male" {% if request.user.gender == 'male' %}checked="checked"{% endif %}>男</label>
<label> <input type="radio" name="gender" value="female" {% if request.user.gender == 'female' %}checked="checked"{% endif %}>女</label>
</li>
<li class="p_infor_city">地 址:
<input type="text" name="address" id="address" placeholder="请输入你的地址" value="{{ request.user.address }}" maxlength="10">
<i class="error-tips"></i>
</li>
<li>手 机 号:
<input type="text" name="mobile" id="mobile" placeholder="请输入你的手机号码" value="{{ request.user.mobile }}" maxlength="10">
</li>
<li>邮 箱:
<input class="borderno" type="text" name="email" readonly="readonly" value="{{ request.user.email }}"/>
<span class="green changeemai_btn">[修改]</span>
</li>
<li class="button heibtn">
<input type="button" id="jsEditUserBtn" value="保存">
</li>
</ul>
<input type='hidden' name='csrfmiddlewaretoken' value='799Y6iPeEDNSGvrTu3noBrO4MBLv6enY' />
</form>
</div>
</div>
</div>
{% endblock %}
- 修改图片
根据用户的model进行照片的变更
class UploadImageForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ['image']
class UserUploadImageView(LoginRequireMixin, 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')
- 修改密码
修改base界面相应的弹出以及js提交界面的js文件。
<div class="resetpwdbox dialogbox" id="jsResetDialog">
<h1>修改密码</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" >新 密 码</span>
<input type="password" id="pwd" name="password1" placeholder="6-20位非中文字符"/>
</div>
<div class="box">
<span class="word2" >确定密码</span>
<input type="password" id="repwd" name="password2" placeholder="6-20位非中文字符"/>
</div>
<div class="error btns" id="jsResetPwdTips"></div>
<div class="button">
<input id="jsResetPwdBtn" type="button" value="提交" />
</div>
{% csrf_token %}
</form>
</div>
</div>
$('#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);
}
}
});
});
class UpdatePwdView(View):
"""
用户修改密码
"""
def post(self, request):
modify_pwd = ModifyForm(request.POST)
if modify_pwd.is_valid():
pwd1 = request.POST.get('password1', '')
pwd2 = request.POST.get('password2', '')
if pwd1 == pwd2:
user = request.user
user.password = make_password(pwd2)
user.save()
return HttpResponse('{"status": "success", "msg":"密码修改成功"}', content_type='application/json')
else:
return HttpResponse('{"status": "fail", "msg": "密码不一致"}', content_type='application/json')
else:
return HttpResponse(json.dumps(modify_pwd.errors), content_type='application/json')
- 所有主菜单栏的用户信息的回显。
{% if request.user.is_authenticated %}
<div class="personal">
<dl class="user fr">
<dd>{{ request.user.nike_name }}<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>
<p>{{ request.user.nike_name }}</p>
</dd>
</dl>
<div class="btn">
<a class="personcenter fl" href="{% url 'user:user_center' %}">进入个人中心</a>
<a class="fr" href="/logout/">退出</a>
</div>
</div>
</div>
{% else %}
<a style="color:white" class="fr registerbtn" href="{% url 'register' %}">注册</a>
<a style="color:white" class="fr loginbtn" href="/login/">登录</a>
{% endif %}
个人邮箱的修改
修改个人邮箱,需要编写两个接口,其中一个是邮箱发送接口,另一个是邮箱修改接口
- 邮箱验证码发送接口
class SendEmailView(LoginRequireMixin, View):
"""
用户修改邮箱验证码发送
"""
def get(self, request):
email = request.GET.get('email', '')
if UserProfile.objects.filter(email=email):
return HttpResponse('{"email":"邮箱已经存在"}',content_type='application/json')
send_email(email, 'update_email')
return HttpResponse('{"status": "success", "msg":"邮箱发送成功"}', content_type='application/json')
- 邮箱修改验证
class UpdateEmailView(LoginRequireMixin, View):
"""
用户邮箱变更
"""
def post(self, request):
email = request.POST.get('email', '')
code = request.POST.get('code', '')
if EmailVerifyRecord.objects.filter(email=email, code=code, send_type='update_email'):
user = request.user
user.email = email
user.save()
return HttpResponse('{"status": "success"}', content_type='application/json')
else:
return HttpResponse('{"email":"验证码错误"}', content_type='application/json')
- 个人信息修改内容提交
class UserCenterHomeView(LoginRequireMixin, View):
"""
进入用户中心
"""
def get(self, request):
return render(request, 'usercenter-info.html', {})
# 用户信息的更改
def post(self, request):
existed_record = UpdateInfoForm(request.POST, instance=request.user)
if existed_record.is_valid():
existed_record.save()
return HttpResponse('{"status": "success"}', content_type='application/json')
else:
return HttpResponse(json.dumps(existed_record.errors), content_type='application/json')
//修改个人中心邮箱验证码
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/send_emial/",
data:$('#jsChangeEmailForm').serialize(),
async: true,
beforeSend:function(XMLHttpRequest){
$btn.val("发送中...");
$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'), "邮箱验证码已发送");
}else if(data.status == 'failure'){
Dml.fun.showValidateError($('#jsChangeEmail'), "邮箱验证码发送失败");
}else if(data.status == 'success'){
}
},
complete: function(XMLHttpRequest){
$btn.val("获取验证码");
$btn.removeAttr("disabled");
}
});
}
//个人资料邮箱修改
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_emial/ ",
data:$('#jsChangeEmailForm').serialize(),
async: true,
beforeSend:function(XMLHttpRequest){
$btn.val("发送中...");
$btn.attr('disabled',true);
$("#jsChangeEmailTips").html("验证中...").show(500);
},
success: function(data) {
if(data.email){
Dml.fun.showValidateError($('#jsChangeEmail'), data.email);
}else if(data.status == "success"){
Dml.fun.showErrorTips($('#jsChangePhoneTips'), "邮箱信息更新成功");
setTimeout(function(){location.reload();},1000);
}else{
Dml.fun.showValidateError($('#jsChangeEmail'), "邮箱信息更新失败");
}
},
complete: function(XMLHttpRequest){
$btn.val("完成");
$btn.removeAttr("disabled");
}
});
}
$(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));
});
//input获得焦点样式
$('.perinform input[type=text]').focus(function(){
$(this).parent('li').addClass('focus');
});
$('.perinform input[type=text]').blur(function(){
$(this).parent('li').removeClass('focus');
});
laydate({
elem: '#birth_day',
format: 'YYYY-MM-DD',
max: laydate.now()
});
verify(
[
{id: '#nick_name', tips: Dml.Msg.epNickName, require: true}
]
);
//保存个人资料
$('#jsEditUserBtn').on('click', function(){
var _self = $(this),
$jsEditUserForm = $('#jsEditUserForm')
verify = verifySubmit(
[
{id: '#nick_name', tips: Dml.Msg.epNickName, require: true}
]
);
if(!verify){
return;
}
$.ajax({
cache: false,
type: 'post',
dataType:'json',
url:"/users/info/",
data:$jsEditUserForm.serialize(),
async: true,
beforeSend:function(XMLHttpRequest){
_self.val("保存中...");
_self.attr('disabled',true);
},
success: function(data) {
if(data.nike_name){
_showValidateError($('#nick_name'), data.nike_name);
}else if(data.birthday){
_showValidateError($('#birth_day'), data.birthday);
}else if(data.address){
_showValidateError($('#address'), data.address);
}else if(data.status == "failure"){
Dml.fun.showTipsDialog({
title: '保存失败',
h2: data.msg
});
}else if(data.status == "success"){
Dml.fun.showTipsDialog({
title: '保存成功',
h2: '个人信息修改成功!'
});
setTimeout(function(){window.location.href = window.location.href;},1500);
}
},
complete: function(XMLHttpRequest){
_self.val("保存");
_self.removeAttr("disabled");
}
});
});
});
用户收藏界面
其中用户三个界面都是一样的逻辑,以一个为例讲解,其中,用户的机构收藏,通过查找用户收藏表,找到所有收藏的机构的id,在获得所有机构的信息放入集合中,在做前端展示。
class MyFavOrgView(LoginRequireMixin, View):
"""
用户收藏的机构
"""
def get(self, request):
current_nav = 'user_fav'
org_list = []
fav_orgs = UserFavorite.objects.filter(user=request.user, fav_type=2)
for fav_org in fav_orgs:
org_id = fav_org.fav_id
org = CourseOrg.objects.get(id=org_id)
org_list.append(org)
return render(request, 'usercenter-fav-org.html', {
'org_list': org_list,
'current_nav': current_nav
})
{% extends 'common/usercenter_base.html' %}
{% block title %}个人中心{% endblock %}
{% load staticfiles %}
{% block custom_bread %}
<section>
<div class="wp">
<ul class="crumbs">
<li><a href="index.html">首页</a>></li>
<li><a href="/user/home/">个人中心</a>></li>
<li>我的收藏</li>
</ul>
</div>
</section>
{% endblock %}
{% block custom_content %}
<div class="right" >
<div class="personal_des Releasecont">
<div class="head">
<h1>我的收藏</h1>
</div>
</div>
<div class="personal_des permessage">
<div class="head">
<ul class="tab_header messagehead">
<li class="active"><a href="{% url 'user:fav_org' %}">课程机构</a> </li>
<li><a href="{% url 'user:fav_teacher' %}">授课教师 </a></li>
<li><a href="{% url 'user:fav_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="{% url 'org:org_home' org.id %}">{{ 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 %}
消息导航栏提示
在usermodel下添加一个方法,获取用户消息总数,并进行显示
class UserProfile(AbstractUser):
nike_name = models.CharField(max_length=64, verbose_name=u'用户别名', default='')
birthday = models.DateField(verbose_name=u'生日', null=True, blank=True)
gender = models.CharField(max_length=32, choices=(('male', u'男'), ('female', u'女')), default='')
address = models.CharField(max_length=128, verbose_name=u'地址', null=True, blank=True, default='')
mobile = models.CharField(max_length=11, verbose_name=u'手机号', null=True, blank=True, default='')
image = models.ImageField(upload_to='image/%Y/%m', default='image/default.png', max_length=128)
class Meta:
verbose_name = u'用户基本信息表'
verbose_name_plural = verbose_name
def __unicode__(self):
return self.username
def get_message_count(self):
# 获取用户未读消息数量
from operation.models import UserMessage
return UserMessage.objects.filter(user=self.id, has_read=0).count()
<a href="usercenter-message.html">
<div class="msg-num"><span id="MsgNum">{{ request.user.get_message_count }}</span></div>
</a>
- 本篇博客原视频博主[慕课在线教育平台]
- 本篇博客撰写人: XiaoJinZi 转载请注明出处
- 学生能力有限 附上邮箱: 986209501@qq.com 不足以及误处请大佬指责