Beispiel #1
0
def newslis_view(request):
    """
    新闻列表。每点击"加载更多"按钮加载ONE_PAGE_NEWS_COUNT条新闻
    """

    page = int(request.GET.get('page',1))
    print(page)
    tag_id = int(request.GET.get('tag_id',0))

    start_page = settings.ONE_PAGE_NEWS_COUNT * (page-1)
    end_page = start_page + settings.ONE_PAGE_NEWS_COUNT

    print("=================")
    print(page,tag_id)
    print("=================")
    if tag_id:
        nlist = NewsPub.objects.select_related('tag','auth').defer('content').filter(is_delete=True,tag_id=tag_id)[start_page:end_page]

        seralizer = NewsPubSerailizer(nlist,many=True)
        return json_status.result(data={"newses":seralizer.data})
    else:
        nlist = NewsPub.objects.select_related('tag', 'auth').defer('content').filter(is_delete=True)[
                start_page:end_page]

        seralizer = NewsPubSerailizer(nlist, many=True)
        return json_status.result(data={"newses": seralizer.data})
Beispiel #2
0
 def put(self, request):
     p = QueryDict(request.body)
     banner_id = p.get("banner_id")
     image_url = p.get("image_url")
     priority = p.get("priority")
     link_to = p.get("link_to")
     if banner_id:
         banner = NewsBanner.objects.filter(id=banner_id)
         if banner:
             banner.update(image_url=image_url,
                           priority=priority,
                           link_to=link_to)
             return json_status.result()
         return json_status.result().params_error(message='轮播图找不到')
     return json_status.result().params_error(message="bannerId不存在")
Beispiel #3
0
 def post(self, request):
     # 验证数据 form request.POST传进去
     form = NewsPubForm(request.POST)
     # cleaned_data 写在验证前面 是获取不到值
     if form.is_valid():
         # title  经过Form验证 如果说没通用验证
         # title1 = request.POST.get("title")
         title = form.cleaned_data.get('title')
         desc = form.cleaned_data.get('desc')
         tag_id = form.cleaned_data.get('tag_id')
         thumbnail_url = form.cleaned_data.get('thumbnail_url')
         content = form.cleaned_data.get('content')
         # 去查出来 tag
         tag = NewsTag.objects.filter(id=tag_id).first()
         # print(title)
         # print(desc)
         # print(tag)
         # print(thumbnail_url)
         # print(content)
         # 当前用户 request.user  user.xxx
         if tag:
             News.objects.create(title=title,
                                 desc=desc,
                                 tag=tag,
                                 thumbnail_url=thumbnail_url,
                                 content=content,
                                 author=request.user)
             return json_status.result()
         return json_status.params_error(message="标签不存在")
     # form 没有这个 get_error
     print(form.errors)
     return json_status.params_error(message=form.get_error())
Beispiel #4
0
def upload_file(request):
    # request.FILES (任何文件都会存在这里面 ) request.POST body(请求体)
    file = request.FILES.get('upload_file')
    # <class 'django.core.files.uploadedfile.InMemoryUploadedFile'>
    # <class 'django.core.files.uploadedfile.TemporaryUploadedFile'>
    # django 对于你上传图片大小 会选择对应的 对象来  图形小于 2.5m
    # print('==========')
    # print(file)  # 2018.png
    # print(file.name)  # 2018.png
    # print(type(file))
    # print(type(file.name))
    # print('==========')
    # 文件名
    file_name = file.name
    # file_path 文件保存
    # x/media/加密字符串.png
    file_path = os.path.join(settings.MEDIA_ROOT, file_name)
    with open(file_path, 'wb') as f:
        # file.chunks() 返回的是一个生成器 能被生成器 不会一次全部使用
        for chunk in file.chunks():
            f.write(chunk)
    # 返回地址  http://192.168.31.200:8000 /media/xxx + settings.MEDIA_URL+file_name
    file_url = request.build_absolute_uri(settings.MEDIA_URL + file_name)
    # http://192.168.31.200:8000/admin/upload-file/ 当前视图对应的绝对路径
    print(request.build_absolute_uri())
    # return JsonResponse({"file_url": file_url})
    return json_status.result(data={"file_url": file_url})
Beispiel #5
0
 def post(self, request):
     form = CoursePubForm(request.POST)
     if form.is_valid():
         title = form.cleaned_data.get("title")
         video_url = form.cleaned_data.get("video_url")
         cover_url = form.cleaned_data.get("cover_url")
         teacher_id = form.cleaned_data.get("teacher_id")
         # name=teacher_name
         teacher = Teacher.objects.filter(id=teacher_id).first()
         duration = form.cleaned_data.get('duration')
         profile = form.cleaned_data.get("profile")
         outline = form.cleaned_data.get("outline")
         category_id = form.cleaned_data.get('category_id')
         # category 分类
         category = CourseCategory.objects.filter(id=category_id).first()
         course = Course.objects.create(title=title,
                                        video_url=video_url,
                                        cover_url=cover_url,
                                        teacher=teacher,
                                        duration=duration,
                                        profile=profile,
                                        outline=outline,
                                        category=category)
         return json_status.result(data={"course_id": course.id})
     print(form.errors)
     return json_status.params_error(message=form.get_error())
Beispiel #6
0
 def put(self, request):
     """
     # 接收前端 put 请求的值  post
     # request.PUI 没有
     # request.POST
     # <QueryDict: {'tag_name': ['技']}>
     # 所有的参数 全部是存在body POST/GET b'tag_name=%E6%8A%80'
     # 我是采用id来判断
     # 在前端向后台提供了只有两个tag_id(标签id) tag_name  (标签name)
     :param request:
     :return:
     """
     res = QueryDict(request.body)
     tag_name = res.get("tag_name", None)
     tag_id = res.get("tag_id", None)
     if tag_id and tag_name:
         tag = NewsTag.objects.filter(id=tag_id)
         if tag:
             news_tag_exists = NewsTag.objects.filter(
                 name=tag_name).exists()
             if news_tag_exists:
                 return json_status.params_error(message="该标签已经存在,请不要重复输入")
             tag.update(name=tag_name)
             return json_status.result()
         return json_status.params_error(message="标签不存在")
     return json_status.params_error(message="标签不存在")
Beispiel #7
0
 def post(self, request):
     # if request.user.is_authenticated:
     form = AddNewsCommentFrom(request.POST)
     if form.is_valid():
         news_id = form.cleaned_data.get('news_id')
         content = form.cleaned_data.get('content')
         # print(news_id, content)
         news = News.objects.filter(id=news_id).first()
         if news:
             # request.user 匿名用户 必须要登录才能访问这个视图 ajax 方式
             comment = NewsComment.objects.create(content=content,
                                                  author=request.user,
                                                  news=news)
             # create 会返回一个对象
             # [Query Set  NewsComment object (8), NewsComment object (7),NewsComment object (6)]
             print(comment)
             print(type(comment))
             # 序列化 不需要加 many=True
             serializer = NewsCommentSerializer(comment)
             print('=======')
             # {'content': '123213123123123321', 'create_time': '2018-10-22T21:43:15.601645+08:00', 'author': OrderedDict([('id', 1), ('username', 'Admin')])}
             print(serializer.data)
             print('=======')
             return json_status.result(data=serializer.data)
         return json_status.params_error(message="新闻不存在")
     return json_status.params_error(message=form.get_error())
Beispiel #8
0
def comment_list_with_news(request):
    # 100条 不可能说全部返回 根据新闻id 返回对应的评论
    news_id = request.GET.get("news_id")
    news = News.objects.filter(id=news_id).first()
    if news:
        # 获取当前新闻下的所有 news_comments 是什么类型  QuerySet
        news_comments = news.comments.all()
        # <QuerySet [<NewsComment: NewsComment object (1)>, <NewsComment: NewsComment object (2)>]>
        # {"id": 1,}   [{}, {}, {}]
        # print(news_comments)
        # <QuerySet [{'id': 1, 'content': '这是新闻id为3的 第一条评论', 'create_time': datetime.datetime(2018, 10, 22, 12, 57, 48, 745035, tzinfo=<UTC>), 'author_id': 1, 'news_id': 3}, {'id': 2, 'content': 'news_id=3 第二条评论', 'create_time': datetime.datetime(2018, 10, 22, 12, 59, 17, 857235, tzinfo=<UTC>), 'author_id': 1, 'news_id': 3}]>
        # [{id:1}, {id:2}]
        # .values() 确实可以序列化 一般适合单表
        # {'id': 1, 'content': '这是新闻id为3的 第一条评论', 'create_time': datetime.datetime(2018, 10, 22, 12, 57, 48, 745035, tzinfo=<UTC>), 'author_id': {id:1, username:"******"}, 'news_id': 3} 返回合适的json数据
        # comments = list(news_comments.values())  # QuerySet
        # for comment in comments:
        #     # author_id = comment["author_id"]
        #     # User.objects.filter(id=author_id) # 全部查出来 但是返回的全部字段
        #     print(comment)
        # 两个及以上 必须加参数 many=True xxx 没有属性  filter many=True / get()/ first()/create()
        serializer = NewsCommentSerializer(news_comments, many=True)
        print(serializer)
        print(type(serializer))
        print(dir(serializer))
        return json_status.result(data=serializer.data)
    return json_status.params_error(message="新闻找不到")
Beispiel #9
0
    def post(self, request):
        """
        更新新闻
        """
        form = forms.NewsEditForm(request.POST)
        if form.is_valid():
            news_id = form.cleaned_data.get('news_id')
            print(news_id)
            title = form.cleaned_data.get('title')
            desc = form.cleaned_data.get('desc')
            thumbnail_url = form.cleaned_data.get('thumbnail_url')
            content = form.cleaned_data.get("content")

            tag_id = form.cleaned_data.get('tag_id')
            newstag = NewsTag.objects.filter(id=tag_id).first()  #查询新闻所属的新闻类

            if newstag:
                new = NewsPub.objects.filter(id=news_id)
                print(new[0].id)

                new.update(id=news_id,
                           title=title,
                           desc=desc,
                           thumbnail=thumbnail_url,
                           auth=request.user,
                           content=content,
                           tag=newstag)

                # print(newstag)
                return json_status.result(message='更新成功!')
            else:
                return json_status.params_error(message='新闻标签不存在!')
        else:
            return json_status.params_error(message=self.get_error(form))
Beispiel #10
0
    def post(self, request):
        form = forms.PubNewsForm(request.POST)
        if form.is_valid():

            title = form.cleaned_data.get('title')
            desc = form.cleaned_data.get('desc')
            thumbnail_url = form.cleaned_data.get('thumbnail_url')
            content = form.cleaned_data.get("content")

            tag_id = form.cleaned_data.get('tag_id')
            newstag = NewsTag.objects.filter(id=tag_id).all()
            if newstag:
                new = NewsPub(title=title,
                              desc=desc,
                              thumbnail=thumbnail_url,
                              content=content,
                              tag=newstag[0],
                              auth=request.user)
                new.save()
                # print(newstag)
                return json_status.result(message='发布成功!')
            else:
                return json_status.params_error(message='新闻标签不存在!')
        else:
            return json_status.params_error(message=self.get_error(form))
Beispiel #11
0
def comment_list_with_news(request):
    news_id = request.GET.get('news_id')
    news = News.objects.filter(id=news_id).first()
    if news:
        news_comments = news.comments.all()
        serializer = NewsCommentSerializers(news_comments, many=True)
        return json_status.result(data=serializer.data)
    return json_status.params_error(message='新闻找不到')
Beispiel #12
0
def news_banner_list(request):
    """返回banner的列表 """
    # 获取所有的banner
    banners = NewsBanner.objects.filter(is_delete=False)
    # banner 序列化
    serializer = NewsBannerSerializer(banners, many=True)
    # 返回结果 data = {"banners": [{}, {}]}
    return json_status.result(data={"banners": serializer.data})
Beispiel #13
0
def news_banner_list(request):
    """
    返回banner的列表
    serializer=[{key:value},{key:value},.....]
    """
    banners = NewsBanner.objects.filter(is_delete=True)
    serializer = NewsBannerSerializer(banners, many=True)
    return json_status.result(data={"banners": serializer.data})
Beispiel #14
0
 def delete(self, request):
     res = QueryDict(request.body)
     tag_id = res.get('tag_id', None)
     tag = NewsTag.objects.filter(id=tag_id)
     if tag_id and tag:
         tag.update(is_delete=False)
         return json_status.result()
     return json_status.params_error(message='标签不存在')
Beispiel #15
0
 def delete(self, request):
     ret = QueryDict(request.body)
     hot_news_id = int(ret.get('hot_news_id', 0))
     hot_news = NewsHot.objects.filter(id=hot_news_id)
     if hot_news:
         hot_news.update(is_detele=False)
         return json_status.result()
     return json_status.params_error(message='热门新闻不存在')
Beispiel #16
0
def news_tag_list(request):
    """
    新闻标签列表
    """
    tags = NewsTag.objects.all()
    # print(tags[0])
    serializer = NewsTagSerailizer(tags,many=True)
    # print(serializer.data)
    return json_status.result(data={'tags':serializer.data})
Beispiel #17
0
    def delete(self, request):

        tagid_dict = QueryDict(request.body)
        tagid = tagid_dict.get('tag_id')
        news = NewsTag.objects.filter(id=tagid)
        if tagid and news:
            news.update(is_delete=False)
            return json_status.result(message="删除成功!")
        return json_status.params_error(message='删除失败!请联系管理员。')
Beispiel #18
0
def news_hot_list(request):
    """
    热点新闻列表
    """
    hot_news = NewsHotAddModle.objects.all()
    if hot_news:
        serailizer = NewsHotSerailizer(hot_news,many=True)
        return json_status.result(data=serailizer.data)
    return json_status.params_error(message='没有设置优先级的新闻!')
Beispiel #19
0
 def delete(self, request):
     d = QueryDict(request.body)
     banner_id = d.get("banner_id")
     if banner_id:
         banner = NewsBanner.objects.filter(id=banner_id)
         if banner:
             banner.update(is_delete=True)
             return json_status.result()
         return json_status.params_error(message="轮播图不存在")
     return json_status.params_error(message="轮播图id不存在")
Beispiel #20
0
 def post(self, request):
     name = request.POST.get('name')
     if name and bool(name.strip()):
         # exists() 是否存在
         news_tag_exists = NewsTag.objects.filter(name=name).exists()
         if news_tag_exists:
             return json_status.params_error(message='该标签已存在,请不要重复输入')
         NewsTag.objects.create(name=name)
         return json_status.result(message='成功')
     return json_status.params_error(message='标签名不能为空')
Beispiel #21
0
def upload_file(request):
    file = request.FILES.get('upload_file')
    file_name = file.name
    file_path = os.path.join(settings.MEDIA_ROOT, file_name)
    with open(file_path, 'wb') as f:
        for chunk in file.chunks():
            f.write(chunk)
    #         返回当前视图对应的绝对路径
    file_url = request.build_absolute_uri(settings.MEDIA_URL + file_name)
    return json_status.result(data={'file_url': file_url})
Beispiel #22
0
 def delete(self, request):
     res = QueryDict(request.body)
     # 前端只传了 tag_id  (tagId 错误的)
     tag_id = res.get("tag_id", None)
     tag = NewsTag.objects.filter(id=tag_id)
     # 防止有的人 绕过浏览器
     if tag_id and tag:
         tag.update(is_delete=True)
         return json_status.result()
     return json_status.params_error(message="标签不存在")
Beispiel #23
0
def news_with_tag(request):
    tag_id = int(request.GET.get('tag_id', 0))
    if tag_id:
        newses = News.objects.filter(tag=tag_id, is_delete=True).all()
        if not tag_id:
            return json_status.params_error(message='该分类下无新闻')
    else:
        newses = News.objects.filter(is_delete=True).all()
    serialzier = NewsSerializer(newses, many=True)
    return json_status.result(data={'newses':serialzier.data})
Beispiel #24
0
 def put(self, request):
     ret = QueryDict(request.body)
     priority = int(ret.get('priority', 0))
     if priority:
         hot_news_id = int(ret.get('hot_news_id', 0))
         hot_news = NewsHot.objects.filter(id=hot_news_id)
         if hot_news:
             hot_news.update(priority=priority)
             return json_status.result()
         return json_status.params_error(message='热门新闻不存在')
     return json_status.params_error(message='优先级错误')
Beispiel #25
0
    def get(self,request):
        news_id = request.GET.get('news_id')
        news = NewsPub.objects.filter(id = news_id,is_delete=True).first()
        if news:
            new_contents = news.newsconten_set.all()   #通过新闻反向查询评论
            print(type(new_contents))

            contents =NewsContentSerailizer(new_contents,many=True)   #序列化结果
            return json_status.result(data=contents.data)
        else:
            return json_status.params_error(message='没有这条新闻!')
Beispiel #26
0
def send_sms_captcha_view(request):

    captch = captcha_check.Captcha.gene_text()
    telephone = request.GET.get('telephone')
    print(telephone, captch)
    # mesg = sms_send.send_sms(telephone,captch)

    # 短信验证码写入缓存
    mcache.set_key(captch.lower(), captch.lower())
    # return JsonResponse(str(mesg,encoding='utf-8'),safe=False)
    # return  JsonResponse({"code":2,"msg":"ok"})
    return json_status.result(message="ok")
Beispiel #27
0
    def post(self, request):
        filepath = settings.DOC_ROOT
        f = request.FILES.get('upload_file')
        filename = os.path.join(filepath, f.name).encode('utf-8')

        with open(filename, 'wb') as file:
            for chunk in f.chunks():
                file.write(chunk)
        fileurl = request.build_absolute_uri(settings.DOC_URL +
                                             f.name)  # 生成一个可访问的url地址

        return json_status.result(message="sucess", data={"file_url": fileurl})
Beispiel #28
0
    def delete(self, request):
        # priority = int(QueryDict(request.body).get('priority'))
        hot_news_id = int(QueryDict(request.body).get('hot_news_id'))

        news = NewsHotAddModle.objects.filter(id=hot_news_id)
        if news:
            # print(news)
            # news[0].priority=priority
            # news[0].save()
            news.update(is_delete=False)
            return json_status.result(message="删除成功!")
        return json_status.params_error("新闻不存在!")
Beispiel #29
0
 def post(self, request):
     # 取值 name 已经在表存在了 再次输入 提示已经存在
     name = request.POST.get("name")
     # print(name) python 怎么去字符串空格 给空格会被过滤掉 后台的最后一道验证
     if name and bool(name.strip()):
         # exists 是否存  True / False  平时都是一些逻辑
         news_tag_exists = NewsTag.objects.filter(name=name).exists()
         if news_tag_exists:
             return json_status.params_error(message="该标签已经存在,请不要重复输入")
         # 创建数据 成功的标准(怎么样确保成功)
         NewsTag.objects.create(name=name)
         return json_status.result(message="成功")
     return json_status.params_error(message="标签名不能为空")
Beispiel #30
0
 def post(self, request):
     form = DocUploadForm(request.POST)
     if form.is_valid():
         title = form.cleaned_data.get("title")
         desc = form.cleaned_data.get("desc")
         file_path = form.cleaned_data.get("file_path")
         Doc.objects.create(title=title,
                            desc=desc,
                            file_path=file_path,
                            author=request.user)
         return json_status.result()
     print(form.errors)
     return json_status.params_error(message=form.get_error())