def generate_blog_post(): post = BlogPost() post.name = random.choice(long_actions) post.content = user_description post.date = generate_datetime() post.published = True post.save()
def setUp(self): # Create an initial object to test with post = BlogPost(title=u'Hello Wørld', text=u'Hello World, this is dynamicresponse. ÆØÅæøå.') post.save() self.post = post
def post(self, request): subject = request.POST['subject'] content = request.POST['content'] slug = titleToUrl(subject) published = request.POST['published'] == 'published' if not subject: messages.add_message(request, messages.INFO, 'Please add a subject.') if not content: messages.add_message(request, messages.INFO, 'Please add some content.') if not BlogPost.objects.filter(slug=slug).count() == 0: messages.add_message(request, messages.INFO, 'Please rename, you\'ve used that title before.') if messages.get_messages(request): params = {'subject': subject, 'content': content, 'published': published} return render(request, 'blog_create.html', params) else: post = BlogPost(title=subject, body=content, slug=slug, published=published) post.save() messages.add_message(request, messages.SUCCESS, 'Blog post created.') return HttpResponseRedirect(reverse('blog_SinglePost', args=(slug,)))
class StatusTests(TestCase): fixtures = ['devel'] def setUp(self): self.client.login(username='******', password='******') self.user = ActiveUser.objects.filter(username='******')[0] self.post = BlogPost(title='Hello World!', author=self.user, tags='hello world', abstract='Hello World!', text='Hello World!', priority=BlogPost.PRIORITY_NORMAL) self.post.save() self.url = reverse('blog_pending_edit', kwargs={'pk': self.post.pk}) self.form = { 'title': self.post.title, 'abstract': self.post.abstract, 'tags': self.post.tags, 'text': self.post.text, 'priority': self.post.priority } def test_draft(self): self.form['action'] = UserCreatePostForm.ACTION_DRAFT response = self.client.post(self.url, self.form, follow=True) self.post.refresh_from_db() self.assertEqual(response.status_code, 200) self.assertLessEqual((datetime.datetime.now() - self.post.date_modified).total_seconds(), 10) def test_submitted(self): self.post.status = BlogPost.STATUS_DRAFT self.post.save() self.form['action'] = UserCreatePostForm.ACTION_SUBMIT response = self.client.post(self.url, self.form, follow=True) self.assertEqual(response.status_code, 200) def test_approved(self): self.form['action'] = UserCreatePostForm.ACTION_APPROVE response = self.client.post(self.url, self.form, follow=True) self.post.refresh_from_db() self.assertEqual(response.status_code, 200) self.assertLessEqual((datetime.datetime.now() - self.post.date_approved).total_seconds(), 10) def test_published(self): self.form['action'] = UserCreatePostForm.ACTION_PUBLISH response = self.client.post(self.url, self.form, follow=True) self.post.refresh_from_db() self.assertEqual(response.status_code, 200) self.assertLessEqual((datetime.datetime.now() - self.post.date_published).total_seconds(), 10) def test_reject(self): self.form['action'] = UserCreatePostForm.ACTION_DELETE response = self.client.post(self.url, self.form, follow=True) self.assertEqual(response.status_code, 200)
def add_post(request): get_title = request.POST['post_title'] get_post_image = request.FILES.get('post_image', None) get_content = request.POST['post_content'] get_content_preview = content_preview_text_gen(get_content) get_datetime = timezone.now() get_user = request.user p = BlogPost(title=get_title, post_image=get_post_image, content=get_content, content_preview=get_content_preview, datetime=get_datetime, author=get_user) p.save() return HttpResponseRedirect(reverse('blog:index'))
def save(request, url): posts = BlogPost.objects.all() for post in posts: if post.id == int(url): b = BlogPost(body=request.GET.get('body'), title=request.GET.get('title'), id=post.id, timestamp=timezone.now()) b.save() t = loader.get_template("article.html") c = Context({'post': b}) return HttpResponse(t.render(c))
def setUp(self): # Headers for GET requests self.extra_headers = { 'HTTP_ACCEPT': 'application/json' } # Create an initial object to test with post = BlogPost(title=u'Hello Wørld', text=u'Hello World, this is dynamicresponse. ÆØÅæøå.') post.save() self.post = post
def test_wgs84_coords(self): """ latitude is +/- 90 longitude is +- 180 """ mapX = BlogSurface.objects.create(title="theWorld") m1 = BlogPost(blog_surface=mapX, title="legal marker", lat=89.9, lng=179.9) m1.save() m2 = BlogPost(blog_surface=mapX, title="illegal marker", lat=99.9, lng=199.9) with self.assertRaises(ValidationError): m2.save()
def test_save_and_retrieve_blog_posts(self): self.assertEqual(BlogPost.objects.all().count(), 0) blog_post = BlogPost() blog_post.title = "A post" blog_post.date = datetime.datetime(1939, 9, 1, 5, 0, 0) blog_post.body = "Blah blah blah" blog_post.visible = False blog_post.save() self.assertEqual(BlogPost.objects.all().count(), 1) retrieved_post = BlogPost.objects.first() self.assertEqual(retrieved_post, blog_post)
def test_drafedit(self): post = BlogPost(title='Hello World!', author=self.user, tags='hello world', abstract='Hello World!', text='Hello World!', priority=BlogPost.STATUS_DRAFT) post.save() url = reverse('blog_draft_edit', kwargs={'pk': post.pk}) response = self.client.get(url) self.assertEqual(response.status_code, 200)
def test_create_post(self): user = User.objects.get(username='******') post = BlogPost(user=user) post.title = "My test post" post.content = "This is a test post" post.save() all_posts = BlogPost.objects.all() self.assertEquals(len(all_posts), 1) only_post = all_posts[0] self.assertEquals(only_post, post) self.assertEquals(only_post.title, "My test post")
def test_blog(self): blog = Blog(title="test blog") blog.save() self.assertIsInstance(blog, Blog) blog_post = BlogPost(blog=blog, title="test post", content="this is content") blog_post.save() self.assertIsInstance(blog_post, BlogPost) get_by_slug = BlogPost.objects.get_by_slug(blog_post.slug) self.assertIsInstance(get_by_slug, BlogPost) homepage = BlogPost.objects.homepage_posts() self.assertEquals(len(homepage), 1)
class PendingTests(TestCase): fixtures = ['devel'] def setUp(self): self.client.login(username='******', password='******') self.user = ActiveUser.objects.filter(username='******')[0] self.post = BlogPost(title='Hello World!', author=self.user, tags='hello world', abstract='Hello World!', text='Hello World!', priority=BlogPost.STATUS_SUBMITTED) self.post.save() def test_list(self): response = self.client.get(reverse('blog_pending_list')) self.assertEqual(response.status_code, 200) def test_edit(self): url = reverse('blog_pending_edit', kwargs={'pk': self.post.pk}) response = self.client.get(url) self.assertEqual(response.status_code, 200)
def handle(self, *args, **options): """ Visit http://argonemyth.me/blog/api/posts/ to see the returned list """ api = BlogAPI() # Step 1: if nuke is true remove all the categories. if options['nuke']: # This will also delete all the posts that are associated # with the categories. BlogCategory.objects.all().delete() BlogPost.objects.all().delete() Location.objects.all().delete() Photo.objects.all().delete() # Step 2: Add all the locations, categories and posts back # Updating all the locations locations = api.locations() for l_json in locations: loc, created = Location.objects.get_or_create(id=l_json["id"]) loc = Location(**l_json) loc.save() cats = api.categories() for c_json in cats: # print c_json posts = c_json.pop('blogposts') try: category = BlogCategory.objects.get(id=c_json["id"]) except BlogCategory.DoesNotExist: # print "Creating a new category: " category = BlogCategory(**c_json) category.save() else: # Check if the local categories are matching the remote ones. if c_json['slug'] != category.slug: raise Exception('The Category is not synced.') else: current_data = category.__dict__.copy() # We check if there are changes current_data.pop('_state') if current_data == c_json: print "%s is already in sync" % c_json['title'] else: # print "Updating a existing category:" category.__dict__.update(c_json) category.save() # Adding all the posts from the category. for p_url in posts: p_json = api.get_post_by_url(p_url) # p_json['category_id'] = category # p_json['author'] = User.objects.get(username=p_json['author']) tags = p_json.pop('tags') api_url = p_json.pop('api_url') # scan post content and grab all the embeded images try: post = BlogPost.objects.get(id=p_json["id"]) except BlogPost.DoesNotExist: print "Creating a new post: %s" % p_json['title'] post = BlogPost(**p_json) post.save() # Download main image if p_json['main_image']: download_photo('/media/' + p_json['main_image'], False) # Adding tags if tags: print "Adding the following tags to post %s: %s" % (post.title, (', ').join(tags)) for tag in tags: post.tags.add(tag) else: if p_json['slug'] != post.slug: raise Exception('The post is not synced') else: # We compare date_updated value to see the post needs to update remote_update = parse_datetime(p_json['date_updated']) if remote_update > post.date_updated: print "Never version of post %s on the server, updating..." % (post.title) post.__dict__.update(p_json) post.save() # else: # print "No need to update post %s " % post.title # Download all the images in the content - regardless if they already exist or not images = re.findall(r'<img.* src="(?P<img>.*?)"', p_json['content']) if images: for img_src in images: download_photo(img_src) # Adding & upate all the photos in Photo albums photos = api.photos() for photo_json in photos: download = False try: photo = Photo.objects.get(id=photo_json["id"]) except Photo.DoesNotExist: download = True tags = photo_json.pop('tags') photo = Photo(**photo_json) photo.save() if tags: print "Adding the following tags to the photo %s: %s" % (photo.title, (', ').join(tags)) for tag in tags: photo.tags.add(tag) if download is True: photo_url = '/media/' + photo_json['image'] download_photo(photo_url, False)
def load_asset_blogs(): """ Used the old database API to retrieve Asset Building articles and then using cleaned CSV data, turns the appropriate content items into blog posts """ asset_blog_mapping = load_asset_blog_mapping() for post in NAClient().get_asset_blog_posts(): if post['status'] == "published": post_id = str(post['id']) print(post_id) mapped_asset_blog_post = asset_blog_mapping.get(post_id, None) if mapped_asset_blog_post: if mapped_asset_blog_post['initiative']: print("adding asset initiative blog") print(mapped_asset_blog_post['initiative']) post_parent = get_subprogram( 'Asset Building', mapped_asset_blog_post['initiative']) parent_blog_homepage = get_content_homepage( post_parent, ProgramBlogPostsPage, mapped_asset_blog_post['blog'], ) asset_blog_post_slug = post['slug'] new_blog_post = BlogPost.objects.filter( slug=asset_blog_post_slug).first() if not new_blog_post and asset_blog_post_slug: new_blog_post = BlogPost( search_description='', seo_title='', depth=6, show_in_menus=False, slug=asset_blog_post_slug, title=post['title'], date=get_post_date(post['publish_at']), subheading=post['sub_headline'], body=json.dumps([{ 'type': 'paragraph', 'value': post['content'] }]), story_excerpt=get_summary(post['summary']), story_image=download_image( post['cover_image_url'], asset_blog_post_slug + "_image.jpeg"), ) parent_blog_homepage.add_child(instance=new_blog_post) new_blog_post.save() get_post_authors(new_blog_post, post['authors']) else: print("adding asset blog") print(post['id']) post_parent = get_program('15') parent_blog_homepage = get_content_homepage( post_parent, ProgramBlogPostsPage, 'Our Blog', ) asset_blog_post_slug = post['slug'] new_blog_post = BlogPost.objects.filter( slug=asset_blog_post_slug).first() if not new_blog_post and asset_blog_post_slug: new_blog_post = BlogPost( search_description='', seo_title='', depth=5, show_in_menus=False, slug=asset_blog_post_slug, title=post['title'], date=get_post_date(post['publish_at']), subheading=post['sub_headline'], body=json.dumps([{ 'type': 'paragraph', 'value': post['content'] }]), story_excerpt=get_summary(post['summary']), story_image=download_image( post['cover_image_url'], asset_blog_post_slug + "_image.jpeg"), ) parent_blog_homepage.add_child(instance=new_blog_post) new_blog_post.save() get_post_authors(new_blog_post, post['authors'])
def load_general_blogs(): """ Used the old database API to retrieve articles and then using cleaned CSV data, turns the appropriate content items into blog posts """ general_blog_mapping = load_general_blog_mapping() for post, program_id in NAClient().get_general_blogs(): if post['status'] == "published": post_id = str(post['id']) print(post_id) mapped_blog_post = general_blog_mapping.get(post_id, None) if mapped_blog_post: print(post['id']) print("found this id above in the csv - adding blog") mapped_programs = mapped_blog_post['program'].split(',') program_id = str(program_id) print('these are the mapped programs') print(mapped_programs) if program_id in mapped_programs: print(program_id) print("found program id above in the mapped programs") post_parent = get_program(program_id) parent_blog_homepage = get_content_homepage( post_parent, ProgramBlogPostsPage, 'Our Blog', ) general_blog_post_slug = post['slug'] general_blog_post = BlogPost.objects.filter( slug=general_blog_post_slug).first() if not general_blog_post and general_blog_post_slug: general_blog_post = BlogPost( search_description='', seo_title='', depth=5, show_in_menus=False, slug=general_blog_post_slug, title=post['title'], date=get_post_date(post['publish_at']), subheading=post['sub_headline'], body=json.dumps([{ 'type': 'paragraph', 'value': post['content'] }]), story_excerpt=get_summary(post['summary']), story_image=download_image( post['cover_image_url'], general_blog_post_slug + "_image.jpeg"), ) parent_blog_homepage.add_child( instance=general_blog_post) general_blog_post.save() get_post_authors(general_blog_post, post['authors']) connect_programs_to_post(general_blog_post, post['programs']) print( "----------------------ADDED NEW BLOG POST------") print(post_id)
def create(request): b = BlogPost(body=request.GET.get('body'), title=request.GET.get('title'), timestamp=timezone.now()) b.save() return archive(request)
def load_education_blog_posts(): """ Transferring blog posts from EdCentral CSV for Education Policy Program """ education_blog_mapping = edcentral_blog_mapping() for post in education_blog_mapping: if post['title'] == 'title': pass else: print(post['title']) post_parent = get_program('5') parent_blog_homepage = get_content_homepage( post_parent, ProgramBlogPostsPage, 'EdCentral', ) ed_blog_post_slug = post['slug'] print(ed_blog_post_slug) new_blog_post = BlogPost.objects.filter( slug=ed_blog_post_slug).first() if not new_blog_post and ed_blog_post_slug: new_blog_post = BlogPost( search_description='', seo_title='', depth=5, show_in_menus=False, slug=ed_blog_post_slug, title=post['title'], date=post['real_date'], body=json.dumps([{ 'type': 'paragraph', 'value': post['content'] }]), story_excerpt=get_summary(post['excerpt']), ) parent_blog_homepage.add_child(instance=new_blog_post) new_blog_post.save() print( "-------------------ADDED NEW EDCENTRAL POST----------------------" ) get_education_authors(new_blog_post, post['author']) connect_subprograms_to_post( new_blog_post, clean_subprograms_for_ed(post['categories'])) elif new_blog_post and ed_blog_post_slug: new_blog_post.search_description = '' new_blog_post.seo_title = '' new_blog_post.depth = 5 new_blog_post.show_in_menus = False new_blog_post.slug = ed_blog_post_slug new_blog_post.title = post['title'] new_blog_post.date = post['real_date'] new_blog_post.body = json.dumps([{ 'type': 'paragraph', 'value': post['content'] }]) new_blog_post.story_excerpt = get_summary(post['excerpt']) get_education_authors(new_blog_post, post['author']) connect_subprograms_to_post( new_blog_post, clean_subprograms_for_ed(post['categories'])) print( "-------------------UPDATED EXISTING EDCENTRAL POST----------------------" ) new_blog_post.save()
def test_model_str(self): foo = BlogPost(author=self.staff, title="foo", content="bar") foo.save() self.assertEqual("foo", str(foo))
def blogPostCreate(request,blog_id): post = dict() page = { 'title': "Create new blog post", 'post': post, 'blog_url':reverse('admin_blogPostCreate',kwargs={'blog_id':blog_id}), 'next_url': reverse('admin_blog',kwargs={'id':blog_id}), 'tag_url': reverse('admin_tag',kwargs={'blog_id':blog_id}), 'category_url': reverse('admin_category',kwargs={'blog_id':blog_id}), } if request.method == 'POST': # If the form has been submitted... response = {'result':'ok'} blogPost = simplejson.loads(request.raw_post_data ) tags = Tag.objects.filter(blog__id=blog_id,id__in = map(lambda x: x['id'],blogPost['tags'])) categories = Category.objects.filter(blog__id=blog_id,id__in = map(lambda x: x['id'],blogPost['categories'])) new_post = BlogPost(content=blogPost['content'], teaser=blogPost['teaser'], title=blogPost['title'], slug=blogPost['slug'], published=blogPost.get('published', False), comments_closed=blogPost.get('comments_closed', False), max_comment_count=blogPost['max_comment_count'], blog_id=blog_id, ) try: # we need to save the object in order to add manytomany field new_post.save() except IntegrityError as e: response['result'] = 'error' response['slug_error'] = 'There is another post with slug value "%s"'%blogPost['slug'] response['error'] = e.args[0] response['errorTitle'] = "Integrity Error" new_post.tags.add(*tags) new_post.categories.add(*categories) try: #this one saves many to many relationship new_post.save() except IntegrityError as e: response['result'] = 'error' response['slug_error'] = 'Error while adding tags to post' response['error'] = e.args[0] response['errorTitle'] = "Integrity Error" return HttpResponse(simplejson.dumps(response),mimetype='text/html') #get request: render page first time post.update({'title':"", 'slug' :"", 'published':True, 'teaser':"", 'content':"", 'comments_closed':False, 'max_comment_count':100}) def objFactory(source): result = dict() result['name'] = source.name result['selected'] = False result['id'] = source.id return result post['tags'] = map(objFactory,Tag.objects.filter(blog__id=blog_id).extra(select={'lower_name':'lower(name)'}).order_by('lower_name')) post['categories'] = map(objFactory,Category.objects.filter(blog__id=blog_id).extra(select={'lower_name':'lower(name)'}).order_by('lower_name')) page['post_json'] = simplejson.dumps(post) return render(request, 'admin/blogpostpage.html', { 'formAction': reverse('admin_blogPostCreate',kwargs={'blog_id':blog_id}), 'page': page, 'user':request.user, })
from blog.models import BlogPost f = open("E:\\bak\\sql.txt", "r") for line in f: content=line.split(","); print content[0],content[2] p1=BlogPost(title=content[0],content=content[1],timestamp=content[2]) p1.save() f.close()
def import_yaml(self, yaml_filename): with open(yaml_filename, 'r') as f: contents = yaml.load(f, Loader=yaml.FullLoader) BlogPost.objects.all().delete() for blog_post in contents: self.posts_nb += 1 filename = blog_post['file'] if not os.path.isabs(filename): base_dir = os.path.abspath(os.path.dirname(yaml_filename)) filename = os.path.join(base_dir, filename) if not os.path.isfile(filename): raise CommandError(f'In file {yaml_filename}, ' f'file {filename} does not exist') try: author = Author.objects.get(pseudo=blog_post['author']) except ObjectDoesNotExist: raise CommandError(f'Author {blog_post["author"]} ' f'referenced in file {filename} ' 'does not exist in the authors table') # a date is always naive, so we need to convert it to datetime # so that make_aware can convert it to an aware object pub_date = blog_post['pub_date'] pub_date = datetime(pub_date.year, pub_date.month, pub_date.day) header_img = None if 'header_img' in blog_post: header_img = blog_post['header_img'] md_as_html = md_convert(filename) soup = BeautifulSoup(md_as_html, 'html.parser') highest_heading = None for heading in range(1, 7): heading_text = 'h' + str(heading) if soup.find(heading_text): highest_heading = heading_text break if highest_heading is None: raise CommandError(f'Blog post file {filename} ' 'does not contain at least one header') title = soup.find(highest_heading).text db_post = BlogPost( title=title, content=md_as_html, author=author, pub_date=make_aware(pub_date), original_filename=filename ) if header_img is not None: db_post.header_img = header_img db_post.save()
def test_set_blog_post_slug__slug_is_not_none(self): post = BlogPost(title='My test blog', slug='my-custom-slug') post.save() self.assertEqual(post.slug, 'my-custom-slug')
def save(self): try: image = self.validated_data['image'] title = self.validated_data['title'] if len(title) < MIN_TITLE_LENGTH: raise serializers.ValidationError({ "response": "Enter a title longer than " + str(MIN_TITLE_LENGTH) + " characters." }) body = self.validated_data['body'] if len(body) < MIN_BODY_LENGTH: raise serializers.ValidationError({ "response": "Enter a body longer than " + str(MIN_BODY_LENGTH) + " characters." }) blog_post = BlogPost( author=self.validated_data['author'], title=title, body=body, image=image, ) url = os.path.join(settings.TEMP, str(image)) storage = FileSystemStorage(location=url) with storage.open('', 'wb+') as destination: for chunk in image.chunks(): destination.write(chunk) destination.close() if sys.getsizeof(image.file) > IMAGE_SIZE_MAX_BYTES: os.remove(url) raise serializers.ValidationError({ "response": "That image is too large. Images must be less than 3 MB. Try a different image." }) img = cv2.imread(url) dimensions = img.shape # gives: (height, width, ?) aspect_ratio = dimensions[1] / dimensions[0] # divide w / h if aspect_ratio < 1: os.remove(url) raise serializers.ValidationError({ "response": "Image height must not exceed image width. Try a different image." }) os.remove(url) blog_post.save() return blog_post except KeyError: raise serializers.ValidationError({ "response": "You must have a title, some content, and an image." })
def test_set_blog_post_slug__slug_is_none(self): post = BlogPost(title='My test blog', slug=None) post.save() self.assertEqual(post.slug, slugify('My test blog'))