Ejemplo n.º 1
0
def remove_news(request):
    news_id = request.POST.get('news')
    try:
        News.objects.get(pk=news_id).delete()
        return restfuls.success()
    except News.DoesNotExist:
        return restfuls.bad_request(msg="该新闻已不存在")
Ejemplo n.º 2
0
def add_news_category(request):
    name = request.POST.get('name')
    exists = NewsCategory.objects.filter(name=name).exists()
    if not exists:
        NewsCategory.objects.create(name=name)
        return restfuls.success(msg="添加成功")
    return restfuls.bad_request(msg="该分类已经存在")
Ejemplo n.º 3
0
def upload_file(request):
    # 上传文件到本地
    file = request.FILES.get('file')
    name = file.name
    with open(os.path.join(settings.MEDIA_ROOT, name), 'wb') as fp:
        for chunk in file.chunks():
            fp.write(chunk)
    url = request.build_absolute_uri(settings.MEDIA_URL + name)
    return restfuls.success(data={'url': url})
Ejemplo n.º 4
0
def edit_news_category(request):
    form = EditNewsCategoryForm(request.POST)
    if form.is_valid():
        pk = form.cleaned_data.get('pk')
        name = form.cleaned_data.get('name')
        try:
            NewsCategory.objects.filter(pk=pk).update(name=name)
            return restfuls.success()
        except ValueError:
            return restfuls.bad_request(msg="该分类已不存在")
    return restfuls.bad_request(form.get_errors())
Ejemplo n.º 5
0
def remove_staff(request):
    """移除员工"""
    uid = request.GET.get("uid")
    try:
        u = User.objects.get(pk=uid)
        u.is_staff = False
        u.groups.remove(*list(u.groups.all()))
        u.save()
        return restfuls.success()
    except User.DoesNotExist:
        return restfuls.bad_request('该用户已不存在')
Ejemplo n.º 6
0
def add_banner(request):
    # 添加轮播图
    form = AddBannerForm(request.POST)
    if form.is_valid():
        priority = form.cleaned_data.get('priority')
        image_url = form.cleaned_data.get('image_url')
        link_to = form.cleaned_data.get('link_to')
        banner = Banner.objects.create(priority=priority,
                                       image_url=image_url,
                                       link_to=link_to)
        return restfuls.success(data={"banner_id": banner.pk})
    return restfuls.bad_request(form.get_errors())
Ejemplo n.º 7
0
def register_view(request):
    # 用户注册
    form = RegisterForm(request.POST)
    if form.is_valid():
        telephone = form.cleaned_data.get('telephone')
        username = form.cleaned_data.get('username')
        password = form.cleaned_data.get('password1')
        user = User.objects.create_user(telephone=telephone,
                                        username=username,
                                        password=password)
        login(request, user)  # 用户注册成功, 将会自动登录
        return restfuls.success()
    return restfuls.bad_request(msg=form.get_errors())
Ejemplo n.º 8
0
def sms_captcha(request):
    # 短信验证码视图函数
    telephone = request.GET.get("telephone")
    exists = User.objects.filter(telephone=telephone).exists()
    if exists:
        return restfuls.bad_request(msg="该手机号已被注册!")

    captcha = Captcha.gene_text()
    cache.set(telephone, captcha.lower(), 5 * 60)
    print(f"""
    手机号码: {telephone}
    验证码: {captcha}
    """)
    return restfuls.success()
Ejemplo n.º 9
0
 def post(self, request):
     telephone = request.POST.get("telephone")
     group_ids = request.POST.getlist('group[]', [])
     if group_ids is None:
         return restfuls.bad_request('请选择用户分组')
     try:
         u = User.objects.get(telephone=telephone)
         u.groups.remove(*list(u.groups.all()))
         groups = Group.objects.filter(pk__in=group_ids)
         u.groups.set(groups)
         u.save()
         return restfuls.success()
     except User.DoesNotExist:
         return restfuls.bad_request('该用户已不存在')
Ejemplo n.º 10
0
def edit_banner(request):
    # 修改轮播图
    form = EditBannerForm(request.POST)
    if form.is_valid():
        banner_id = form.cleaned_data.get('pk')
        image_url = form.cleaned_data.get('image_url')
        link_to = form.cleaned_data.get('link_to')
        priority = form.cleaned_data.get('priority')
        try:
            Banner.objects.filter(pk=banner_id).update(image_url=image_url,
                                                       link_to=link_to,
                                                       priority=priority)
            return restfuls.success()
        except Banner.DoesNotExist:
            return restfuls.bad_request(msg="当前轮播图已不存在")
    return restfuls.bad_request(msg=form.get_errors())
Ejemplo n.º 11
0
def course_token(request):
    """百度云播放视频"""
    file = request.GET.get('video')

    expiration_time = int(time.time()) + 2 * 60 * 60
    USER_ID = settings.BAIDU_CLOUD_USER_ID
    USER_KEY = settings.BAIDU_CLOUD_USER_KEY

    extension = os.path.splitext(file)[1]  # 获取扩展名
    media_id = file.split('/')[-1].replace(extension, '')

    key = USER_KEY.encode('utf-8')
    message = f"/{media_id}/{expiration_time}".encode('utf-8')
    signature = hmac.new(key, message, digestmod=hashlib.sha256).hexdigest()
    token = f"{signature}_{USER_ID}_{expiration_time}"
    return restfuls.success(data={"token": token})
Ejemplo n.º 12
0
    def post(self, request):
        group_ids = request.POST.getlist(
            'group[]', [])  # 通过ajax 获取的group key值为 "group[]"? 待解决原因
        if group_ids is None:
            return restfuls.bad_request('请选择员工分组')

        form = AddStaffForm(request.POST)
        if form.is_valid():
            telephone = form.cleaned_data.get('telephone')
            try:
                user = User.objects.get(telephone=telephone)
                user.is_staff = True
                groups = Group.objects.filter(pk__in=group_ids)
                user.groups.set(groups)
                user.save()
                return restfuls.success()
            except User.DoesNotExist:
                return restfuls.bad_request("请用户先完成注册")
        return restfuls.bad_request(form.get_errors())
Ejemplo n.º 13
0
    def post(self, request):
        form = PublishNewsForm(request.POST, request.FILES)
        if form.is_valid():
            title = form.cleaned_data.get('title')
            desc = form.cleaned_data.get('desc')
            thumbnail = form.cleaned_data.get('thumbnail')
            content = form.cleaned_data.get('content')
            cid = form.cleaned_data.get('category')
            category = NewsCategory.objects.get(pk=cid)

            news_id = form.cleaned_data.get('news_id') or None
            News.objects.update_or_create(id=news_id,
                                          defaults={
                                              "title": title,
                                              "desc": desc,
                                              "thumbnail": thumbnail,
                                              "content": content,
                                              "category": category,
                                              "author": request.user
                                          })
            return restfuls.success()
        return restfuls.bad_request(msg=form.get_errors())
Ejemplo n.º 14
0
def login_view(request):
    # 用户登录
    form = LoginForm(request.POST)
    if form.is_valid():
        telephone = form.cleaned_data.get("telephone")
        password = form.cleaned_data.get("password")
        remember = form.cleaned_data.get("remember")

        user = authenticate(request, username=telephone, password=password)
        if user and user.is_active:
            if remember:
                request.session.set_expiry(None)  # 不记住密码
            else:
                request.session.set_expiry(0)

            login(request, user)
            return restfuls.success()  # 登录成功
        else:
            return restfuls.forbidden(msg="账号或密码错误")  # 登录失败
    else:
        return restfuls.bad_request(msg=form.get_errors(),
                                    data=form.get_errors())  # 表单验证失败
Ejemplo n.º 15
0
 def post(self, request):
     form = PublishCourseForm(request.POST)
     if form.is_valid():
         # name = form.cleaned_data.get("name")
         # category_id = form.cleaned_data.get("category_id")
         # teacher_id = form.cleaned_data.get("teacher_id")
         # video_link = form.cleaned_data.get("video_link")
         # cover_link = form.cleaned_data.get("cover_link")
         # price = form.cleaned_data.get("price")
         # duration = form.cleaned_data.get("duration")
         #
         # Course.objects.create(name=name, category_id=category_id,
         #                       teacher_id=teacher_id, video_link=video_link,
         #                       cover_link=cover_link, price=price,
         #                       duration=duration)
         for k, v in form.cleaned_data.items():
             print(f"{k}: {v}")
         course = Course()
         course.set_attr(form.cleaned_data)
         course.save()
         return restfuls.success()
     return restfuls.bad_request(form.get_errors())
Ejemplo n.º 16
0
def load_banner(request):
    # ajax 加载轮播图
    banners = Banner.objects.all()
    serializer = BannerSerializer(banners, many=True)
    return restfuls.success(data=serializer.data)
Ejemplo n.º 17
0
def remove_banner(request):
    bid = request.GET.get('bid')
    banner = get_object_or_404(Banner, pk=bid)
    banner.delete()
    return restfuls.success()
Ejemplo n.º 18
0
def delete_category_category(request):
    pk = request.POST.get("pk")
    if pk:
        NewsCategory.objects.filter(pk=pk).delete()
        return restfuls.success()
    return restfuls.bad_request(msg="当前分类已不存在")