def write(request): BASE_DIR = os.path.join(settings.MEDIA_ROOT,'user')#所有用户资料公共路径 if request.user.is_authenticated: if request.method == 'POST': path = os.path.join(BASE_DIR,str(request.user.pk)) #请求的用户路径 myFile = request.FILES.get("faceimg",None) if not myFile: return HttpResponse('无效文件') title = request.POST.get('title',None) content = request.POST.get('content',None) _type = request.POST.get('type',None) article_type = get_object_or_404(models.ArticleType,article_type=_type) article = models.Article(title=title,article_type=article_type,author=request.user) article.save() models.Content(article=article,content=content).save() ext = os.path.splitext(myFile.name)[1] article_path = os.path.join(path,f'{article.pk}') if not os.path.exists(article_path): os.makedirs(article_path) with open(os.path.join(article_path,f'face{ext}'),'wb+') as f: for chunk in myFile.chunks(): f.write(chunk) models.FaceImg(article=article,path=f'user/{request.user.pk}/{article.pk}/face{ext}').save() return redirect(reverse('blog:blog_detail',args=(article.pk,))) _types = models.ArticleType.objects.all() return render(request,'write.html',{'user':request.user,'types':_types}) return HttpResponse('请登录')
def post(self,request): form=cf.CMSAddPostForm(request.POST) form.set_request(request) if not form.is_valid(): return xtjson.json_params_error(message=form.get_error()) else: title=form.cleaned_data.get('title') tags=request.POST.getlist('tags[]') content=form.cleaned_data.get('content') thumbnail=form.cleaned_data.get('thumbnail') data=dict(title=title,content=content) if thumbnail: data.update(thumbnail=thumbnail) else: content='<p><img src="{}" alt=""></p>{}'.format(DEFAULT_THUMBNAIL,content) data['content']=content article=bm.Article(**data) user=request.cms_user article.author=user for tag_id in tags: tag=bm.Tag.objects.filter(id=tag_id).first() if tag: article.tags.append(tag) article.save() tag.articles.append(article) tag.save() user.articles.append(article) user.save() return xtjson.json_result(message='帖子发布成功')
def addblog(request): contents = {} type = {'home': '首页', 'normal': '列表页'} contents['cate'] = models.Cate.objects.all() contents['type'] = type if request.method == 'GET': id = request.GET.get('id') if id: contents['article'] = models.Article.objects.get(id=id) return render(request, 'administrator/addblog.html', contents) if request.method == 'POST': title = request.POST.get('title') logo = '' cate_id = request.POST.get('cid') type = request.POST.get('type') desc = request.POST.get('note') content = request.POST.get('content') operate_time = time.strftime('%Y-%m-%d %H:%I:%S', time.localtime()) create_id = 'administrator' create_time = time.strftime('%Y-%m-%d %H:%I:%S', time.localtime()) img_file = request.FILES.get('logo') # 上传文件 if img_file: filepath = os.path.join(settings.BASE_DIR, 'media', 'blog') if not os.path.exists(filepath): os.makedirs(filepath) filename = os.path.join(filepath, img_file.name) f = open(filename, 'wb') for chunk in img_file.chunks(): f.write(chunk) f.close() logo = filename.replace(settings.BASE_DIR,'') if request.POST.get('id') and models.Article.objects.filter(id=request.POST.get('id')): if logo == '': logo = models.Article.objects.get(id=request.POST.get('id')).logo models.Article.objects.filter(id=request.POST.get('id')).update(title=title, logo=logo,cate_id=cate_id,type=type,desc=desc,content=content,create_id=create_id,operate_time=operate_time) return render(request, 'administrator/tips.html',{'code': 1, 'msg': 'success', 'url': '/administrator/bloglist/', 'waitsecond': 4}) else: blog = models.Article() blog.title = title blog.logo = logo blog.cate_id = cate_id blog.type = type blog.desc = desc blog.content = content blog.create_id = create_id blog.create_time = time.strftime('%Y-%m-%d %H:%I:%S', time.localtime()) blog.operate_time = time.strftime('%Y-%m-%d %H:%I:%S', time.localtime()) blog.save() return render(request, 'administrator/tips.html',{'code': 1, 'msg': 'success', 'url': '/administrator/bloglist/', 'waitsecond': 4})
def add(request): res = {'status': True, 'error_mess': None} try: blog_bid = request.POST.get('bid') title = request.POST.get('title').strip() content = request.POST.get('content').strip() if len(title) == 0 or len(content) == 0: res['status'] = False res['error_mess'] = '请填写文章标题并撰写内容' else: obj_a = models.Article(title=title, author_id=blog_bid) obj_a.save() models.ArticleDetail.objects.create(content=content, article=obj_a) except Exception: res['status'] = False res['error_mess'] = '请求错误' data = json.dumps(res) return HttpResponse(data)
def orm(request): # 第一种方法: # models.Article.objects.create(title='增加标题一', category_id=3, body='增加内容一', user_id=1) # 第二种方法:添加数据,实例化表类,在实例化里传参为字段和值 obj = models.Article(title='增加标题二', category_id=4, body='增加内容二', user_id=1) # 写入数据库 obj.save() # 第三种方法:将要写入的数据组合成字典,键为字段值为数据 dic = { 'title': '增加标题三', 'category_id': '4', 'body': '增加内容三', 'user_id': '1' } # 添加到数据库,注意字典变量名称一定要加** models.Article.objects.create(**dic) """删除""" # models.Article.objects.filter(id=3).delete() """更改""" models.Article.objects.filter(id=6).update(intro='123') return HttpResponse('orm')
def post(request): host = 'http://127.0.0.1:9999/' img = request.POST.get('img') # 上传图片 if img is not None: img = json.loads(img) img_url = img['url'] img_name = img['name'] img_url_list = img_url.split(',') img_data = base64.b64decode(img_url_list[1]) image_name = int(round(time.time() * 1000)) img_url = 'media/img' + '/' + str(image_name) + '-' + img_name with open(img_url, 'wb') as f: f.write(img_data) return Response(host + img_url) # 添加文章 user = request.user article_text = request.POST.get('article_text') article_title = request.POST.get('article_title') article_desc = request.POST.get('article_introduce') article_category = request.POST.get('article_category') article_tag = json.loads(request.POST.get('article_tag')) # print(article_tag) # 存储外键与普通字段 article_category_data = models.Category.objects.get( category=article_category) article_info = models.Article(title=article_title, desc=article_desc, text=article_text, article_user=user, article_category=article_category_data) article_info.save() # 获取多对多关系字段 for tag in article_tag: article_tag_data = models.Tag.objects.get(tag=tag) # 使用add()方法存储多对多关系 article_info.article_tag.add(article_tag_data) article_info.save() return Response('OK')
# 插入数据 from blog import models category_choices = [4, 2, 3] dates = ['2011-12-12', '2012-3-5', '2018-12-5'] blog_lst = [1, 2, 3] lst = [] # 插入5个数据 for i in range(7): random_title = ''.join(random.choices(string.ascii_letters, k=5)) random_category = random.choice(category_choices) random_content = ''.join(random.choices(string.ascii_letters, k=9)) random_date = random.choice(dates) random_blog = random.choice(blog_lst) customer_obj = models.Article(title=random_title, category=random_category, content=random_content, create_at=random_date, blog_id=random_blog) lst.append(customer_obj) models.Article.objects.bulk_create(lst)