我的 Django 项目里的用户可以发图片。 我想实现一个收藏功能,就是用户可以收藏其他用户发布的图片。 粗略想了下,model应该这样写:
代码语言:javascript复制class FavoritePicture(models.Model):
user = models.ForeignKey(User)
picture = models.ForeignKey(Pictures)
created_on = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return "%s likes picture %s" % (self.user, self.picture)
收藏的过程可以考虑用Ajax实现
代码语言:javascript复制def add_favorite(request):
user = request.user
picture = request.POST['picture_id']
picture = Pictures.objests.get(id=picture)
created_on = datetime.datetime.now()
FavoritePicture.objects.update_or_create(user=user,picture=picture,created_on=created_on)
update_or_create 这个是Django1.7 新功能, 然后你可以考虑下是不是该用外键,我我按照外键的搞法写查询函数
代码语言:javascript复制def get_favourite_list(request):
user = request.GET['username']
user = User.objects.get(username=user)
fav_pics = user.favoritepicture_set #这个名字是Django自动确定的
return render_to_response('xxxx',{fav_pics=fav_pics})
Django2.0.8 xadmin2实现在线学习网站,课程、讲师、机构、用户收藏功能。GitHub地址:https://github.com/xyliurui/OnlineLearningPlatform ;Django版本:2.0.8
更多内容请点击 我的博客 查看,欢迎来访。 机构收藏功能 机构模型增加收藏数更新函数
# 课程机构信息 class CourseOrg(models.Model): ORG_CHOICES = ( ("pxjg", "培训机构"), ("gx", "高校"), ("gr", "个人"), )
name = models.CharField(max_length=50, verbose_name='机构名称') desc = models.TextField(verbose_name='机构描述') category = models.CharField(choices=ORG_CHOICES, max_length=10, default='pxjg', verbose_name='机构类别') click_nums = models.IntegerField(default=0, verbose_name='点击数') fav_nums = models.IntegerField(default=0, verbose_name='收藏数') students = models.IntegerField(default=0, verbose_name='学习人数') course_nums = models.IntegerField(default=0, verbose_name='课程数') image = models.ImageField(upload_to='org/%Y/%m', max_length=100, blank=True, null=True, verbose_name='封面图') address = models.CharField(max_length=150, verbose_name='机构地址') city = models.ForeignKey(CityDict, on_delete=models.CASCADE, verbose_name='所在城市') add_time = models.DateTimeField(default=datetime.now, verbose_name='添加时间')
class Meta: verbose_name_plural = verbose_name = '课程机构'
def change_fav_nums(self, add=1): self.fav_nums = add self.save(update_fields=['fav_nums'])
def __str__(self): return self.name
用于收藏和取消收藏时值加减 机构收藏ajax视图AddFavView(View)
# 机构收藏或取消收藏 class AddFavView(View): def post(self, request): # 收藏的不管是课程,讲师,还是机构,都是记录他们的id,如果没取到把它设置未0,避免查询时异常 fav_id = request.POST.get('fav_id', 0) # 表明收藏的类别 fav_type = request.POST.get('fav_type', 0)
# 收藏与已收藏取消收藏 # 判断用户是否登录:即使没登录会有一个匿名的user if not request.user.is_authenticated: # 未登录时返回json提示未登录,跳转到登录页面是在ajax中做的 return HttpResponse('{"fav_status":"fail", "fav_msg":"用户未登录"}', content_type='application/json')
exist_records = UserFavorite.objects.filter(user=request.user, fav_id=fav_id, fav_type=fav_type)
if exist_records: # 如果已经存在,表明用户取消收藏 exist_records.delete() # 机构模型中存储的收藏数减1 CourseOrg.objects.get(id=fav_id).change_fav_nums(add=-1) return HttpResponse('{"fav_status":"success", "fav_msg":"添加收藏"}', content_type='application/json') else: user_fav = UserFavorite() # 如果取到了id值才进行收藏 if int(fav_id) > 0 and int(fav_type) > 0: user_fav.fav_id = fav_id user_fav.fav_type = fav_type user_fav.user = request.user user_fav.save() # 机构模型中存储的收藏数加1 CourseOrg.objects.get(id=fav_id).change_fav_nums(add=1) return HttpResponse('{"fav_status":"success", "fav_msg":"取消收藏"}', content_type='application/json') else: return HttpResponse('{"fav_status":"fail", "fav_msg":"收藏出错"}', content_type='application/json')
收藏功能url
from organization.views import OrgListView, AddUserAskView, OrgHomeView, OrgCourseView, OrgDescView, OrgTeacherView, AddFavView
app_name = 'organization'
urlpatterns = [ # 课程机构列表url path('list/', OrgListView.as_view(), name="org_list"), path('add_ask/', AddUserAskView.as_view(), name='add_ask'), re_path('home/(?P<org_id>d )/', OrgHomeView.as_view(), name='org_home'), # 机构详情首页 re_path('id/(?P<org_id>d )/courses/', OrgCourseView.as_view(), name='org_course'), # 机构课程列表 re_path('id/(?P<org_id>d )/desc/', OrgDescView.as_view(), name='org_desc'), # 机构介绍 re_path('id/(?P<org_id>d )/teacher/', OrgTeacherView.as_view(), name='org_teacher'), # 机构讲师 path('add_fav/', AddFavView.as_view(), name="add_fav"), # 添加机构收藏 ]
机构收藏模板按钮
监听按钮点击动作,post提交,改变按钮的样式和文字
<p> {% if has_fav %} <button id="add_fav_org_button" class="btn-round btn-light" style="background: #FFA042">取消收藏</button> {% else %} <button id="add_fav_org_button" class="btn-round btn-light" style="background: #02DF82">添加收藏</button> {% endif %} </p>
<script type="text/javascript">
//添加或取消收藏 function add_fav_org(current_elem, fav_id, fav_type){ $.ajax({ cache: false, type: "POST", url:"{% url 'org:add_fav' %}", data:{'fav_id':fav_id, 'fav_type':fav_type}, async: true, beforeSend:function(xhr, settings){ xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token }}"); }, success: function(data) { if(data.fav_status === 'fail'){ if(data.fav_msg === '用户未登录'){ window.location.href="/login/?next={{ request.path }}"; }else{ alert(data.fav_msg) }
}else if(data.fav_status === 'success'){ current_elem.text(data.fav_msg); // 修改按钮的颜色 if (data.fav_msg === '取消收藏') { document.getElementById('add_fav_org_button').style.background = '#FFA042'; } else if (data.fav_msg === '添加收藏') { document.getElementById('add_fav_org_button').style.background = '#02DF82'; } } }, }); }
('#add_fav_org_button').on('click', function(){ add_fav_org((this), {{ course_org.id }}, 2); });
</script>
BLOG_20190604_140507_46 机构信息页面视图添加收藏状态
例如机构首页,添加has_fav来检测是否已收藏,且需要用户登录的,同事还需要将课程页面、讲师页面、介绍页面都添加上
has_fav = False if request.user.is_authenticated: if UserFavorite.objects.filter(user=request.user, fav_id=course_org.id, fav_type=2): has_fav = True
例如
# 机构首页 class OrgHomeView(View): def get(self, request, org_id): # 通过id找到机构 course_org = CourseOrg.objects.get(id=org_id)
# 通过机构找到这个机构的课程和教师,并按一些数据进行排序 all_course = course_org.courses.all().order_by('-students', '-fav_nums', 'click_nums')[:4] all_teacher = course_org.teachers.all().order_by('-fav_nums', '-click_nums')[:4]
# TYPE_CHOICES = ( # (1, "课程"), # (2, "课程机构"), # (3, "讲师") # ) has_fav = False if request.user.is_authenticated: if UserFavorite.objects.filter(user=request.user, fav_id=course_org.id, fav_type=2): has_fav = True
return render(request, 'org-detail-homepage.html', locals())
标记访问页面
可以在org中每个视图添加一个参数,用于选中激活
# 标记当前页,用于页面选中active current_access_url = 'org'
然后前端判断