def handle(self, *args, **options): theme = None num = options['num'] theme_id = options['theme'] last_instance = Post.objects.last() start_num = last_instance.id if last_instance else 1 end_num = start_num + int(num) if theme_id: theme = Themes.objects.get(id=theme_id) for idx in range(start_num, end_num): post = Post() post.title = TEST_TITLE % idx post.description = LOREM_DESCRIPTION post.posttext = LOREM_BODY if theme: post.theme = theme post.save() self.stdout.write(self.style.SUCCESS(SUCCESS_TEXT % idx))
def import_data(): # Initial Imports from django.contrib.auth.models import User # Processing model: posts.models.Post from posts.models import Post posts_post_1 = Post() posts_post_1.author = importer.locate_object(User, "id", User, "id", 1, {'id': 1, 'password': '******', 'last_login': datetime.datetime(2018, 11, 27, 6, 31, 56, 449061, tzinfo=<UTC>), 'is_superuser': True, 'username': '******', 'first_name': '', 'last_name': '', 'email': '*****@*****.**', 'is_staff': True, 'is_active': True, 'date_joined': datetime.datetime(2018, 11, 27, 6, 31, 35, 527568, tzinfo=<UTC>)} ) posts_post_1.link = 'https://stackoverflow.com/questions/3330435/is-there-an-sqlite-equivalent-to-mysqls-describe-table' posts_post_1.title = 'Initial Data' posts_post_1.description = 'Cool Description' posts_post_1 = importer.save_or_locate(posts_post_1) posts_post_2 = Post() posts_post_2.author = importer.locate_object(User, "id", User, "id", 1, {'id': 1, 'password': '******', 'last_login': datetime.datetime(2018, 11, 27, 6, 31, 56, 449061, tzinfo=<UTC>), 'is_superuser': True, 'username': '******', 'first_name': '', 'last_name': '', 'email': '*****@*****.**', 'is_staff': True, 'is_active': True, 'date_joined': datetime.datetime(2018, 11, 27, 6, 31, 35, 527568, tzinfo=<UTC>)} ) posts_post_2.link = 'https://simpleisbetterthancomplex.com/tutorial/2016/07/26/how-to-reset-migrations.html' posts_post_2.title = 'Reset Generator' posts_post_2.description = 'https://simpleisbetterthancomplex.com/tutorial/2016/07/26/how-to-reset-migrations.html' posts_post_2 = importer.save_or_locate(posts_post_2) # Processing model: posts.models.Vote from posts.models import Vote posts_vote_1 = Vote() posts_vote_1.voter = importer.locate_object(User, "id", User, "id", 1, {'id': 1, 'password': '******', 'last_login': datetime.datetime(2018, 11, 27, 6, 31, 56, 449061, tzinfo=<UTC>), 'is_superuser': True, 'username': '******', 'first_name': '', 'last_name': '', 'email': '*****@*****.**', 'is_staff': True, 'is_active': True, 'date_joined': datetime.datetime(2018, 11, 27, 6, 31, 35, 527568, tzinfo=<UTC>)} ) posts_vote_1.post = posts_post_1 posts_vote_1.liked = True posts_vote_1 = importer.save_or_locate(posts_vote_1) posts_vote_2 = Vote() posts_vote_2.voter = importer.locate_object(User, "id", User, "id", 2, {'id': 2, 'password': '******', 'last_login': None, 'is_superuser': False, 'username': '******', 'first_name': '', 'last_name': '', 'email': '', 'is_staff': False, 'is_active': True, 'date_joined': datetime.datetime(2018, 11, 27, 6, 35, 12, 746625, tzinfo=<UTC>)} ) posts_vote_2.post = posts_post_1 posts_vote_2.liked = True posts_vote_2 = importer.save_or_locate(posts_vote_2) # Processing model: posts.models.Comment from posts.models import Comment posts_comment_1 = Comment() posts_comment_1.description = 'My Cool Comment on Post 1 yeh.' posts_comment_1.author = importer.locate_object(User, "id", User, "id", 1, {'id': 1, 'password': '******', 'last_login': datetime.datetime(2018, 11, 27, 6, 31, 56, 449061, tzinfo=<UTC>), 'is_superuser': True, 'username': '******', 'first_name': '', 'last_name': '', 'email': '*****@*****.**', 'is_staff': True, 'is_active': True, 'date_joined': datetime.datetime(2018, 11, 27, 6, 31, 35, 527568, tzinfo=<UTC>)} ) posts_comment_1.post = posts_post_1 posts_comment_1 = importer.save_or_locate(posts_comment_1)
def _generate_posts(self, user): print(f"Creating posts by {user.first_name} {user.last_name}", end="\r") for _ in range( random.randint(self._min_number_posts_per_user, self._number_posts_per_user)): post = Post() post.title = self._faker.text(max_nb_chars=120) post.description = self._faker.text(max_nb_chars=1000) post.user = user post.save()
def save(country_data, country_code): print(f"Saving {country_code} data to DB...") for idx, row in enumerate(country_data): if (idx > 0): post_data = row.split(',') post = Post() post.title = post_data[2].replace('"', '') post.link = post_data[0].replace('"', '') post.description = post_data[1].replace('"', '') post.source = 'YOUTUBE' post.save()
def handle(self, *args, **options): num = options['num'] theme_id = options['theme'] if theme_id: theme = Themes.objects.get(id=theme_id) for idx in range(num): post = Post() post.title = '%s # %s' % (POST_TITLE, idx) post.description = DESC_TEXT post.posttext = BODY_TEXT if theme: post.theme = theme post.save()
def create_new_post(request): # POST to http://service/author/posts # Create a post to the currently authenticated user # First get the information out of the request body size = len(request.body) #body = json.load(body) # body = dict(x.split("=") for x in body.split("&")) #post = body['post'] post = request.POST new_post = Post() # Post ID's are created automatically in the database # new_post.id = post['id'] #: "de305d54-75b4-431b-adb2-eb6b9e546013", #: "A post title about a post about web dev", new_post.title = post['title'] # Source and origin are the same, and depend on the ID so we wait until after the post gets saved to # generate this URLS # new_post.source = post['source'] #: "http://lastplaceigotthisfrom.com/posts/yyyyy" # new_post.origin = post['origin'] #: "http://whereitcamefrom.com/posts/zzzzz" new_post.description = post[ 'description'] # : "This post discusses stuff -- brief", # If the post is an image, the content would have been provided as a file along with the upload if len(request.FILES) > 0: file_type = request.FILES['file'].content_type allowed_file_type_map = { 'image/png': Post.TYPE_PNG, 'image/jpg': Post.TYPE_JPEG } if file_type not in allowed_file_type_map.keys(): return JsonResponse({ 'success': 'false', 'msg': f'You uploaded an image with content type: {file_type}, but only one of {allowed_file_type_map.keys()} is allowed' }) new_post.contentType = allowed_file_type_map[ file_type] # : "text/plain" new_post.content = base64.b64encode( request.FILES['file'].read()).decode('utf-8') else: new_post.contentType = post['contentType'] # : "text/plain", new_post.content = post['content'] #: "stuffs", new_post.author = request.user # the authenticated user # Categories added after new post is saved new_post.count = 0 #: 1023, initially the number of comments is zero new_post.size = size #: 50, the actual size of the post in bytes # This is not a property that gets stored, but rather a link to the comments of this post that should # be generated on the fly. # new_post.next = post['next'] #: "http://service/posts/{post_id}/comments", # We do not permit adding comments at the same time a post is created, so this field is not created # new_post.comments = post['comments'] #: LIST OF COMMENT, current_tz = pytz.timezone('America/Edmonton') timezone.activate(current_tz) #: "2015-03-09T13:07:04+00:00", new_post.published = str(datetime.datetime.now()) new_post.visibility = post['visibility'].upper() #: "PUBLIC", new_post.unlisted = True if 'unlisted' in post and post[ 'unlisted'] == 'true' else False #: true new_post.save() # Now we can set source and origin new_post.source = settings.HOSTNAME + "/posts/" + str(new_post.id.hex) new_post.origin = settings.HOSTNAME + "/posts/" + str(new_post.id.hex) new_post.save() # Take the user uid's passed in and convert them into Authors to set as the visibleTo list uids = post.getlist('visibleTo') visible_authors = Author.objects.filter(uid__in=uids) for author in visible_authors: new_post.visibleTo.add(author) # Categories is commented out because it's not yet in the post data, uncomment once available for category in post['categories'].split('\r\n'): try: # Try connecting to existing categories cat_object = Category.objects.get(name=category) except Category.DoesNotExist as e: cat_object = Category.objects.create( name=category) # Create one if not new_post.categories.add(cat_object) #: LIST, # for key in body.keys(): # print(f'{key}: {body[key]}') if len(request.FILES) > 0: # If they uploaded a file this is an ajax call and we need to return a JSON response return JsonResponse({'success': 'true', 'msg': new_post.id.hex}) else: return redirect("/")
def publicPosts(request): '''List all public posts on the server''' if request.method == 'GET': # Default if not given page_num = request.GET.get('page', DEFAULT_PAGE_NUM) page_size = request.GET.get('size', DEFAULT_PAGE_SIZE) # Get all local and global comments, combine and paginate results all_posts = Post.objects.filter(visibility='PUBLIC').order_by('-published') #for post in all_posts: # print post.comments #num_comments = len(all_posts[0]['comments']) #print 'Comments: ' #print num_comments # Need this here or else the pagination bitches about it being unicode page_num = int(page_num) # Get the right page pages = Paginator(all_posts, page_size) page = pages.page(page_num+1) data = page.object_list response_obj = {} response_obj['query'] = 'posts' response_obj['count'] = len(all_posts) response_obj['size'] = page_size if page.has_next(): response_obj['next'] = settings.LOCAL_HOST + 'api/posts?page=' + str(page_num + 1) + '&size=' + str(page_size) if page.has_previous(): response_obj['previous'] = settings.LOCAL_HOST + 'api/posts?page=' + str(page_num - 1) + '&size=' + str(page_size) serializer = PostSerializer(data, many=True) response_obj['posts'] = serializer.data return Response(response_obj) elif request.method == 'POST': '''This method POSTS ''' auth = request.data['author'] try: author = Author.objects.get(author_id = auth) print(author) except Exception, e: print 'No Author!' return Response("Not a valid author...", status=status.HTTP_400_BAD_REQUEST) try: post = Post(author = author) post.title = request.data['title'] post.description = request.data['description'] post.contentType = request.data['contentType'] post.content = request.data['content'] post.visibility = request.data['visibility'] post.categories = request.data['categories'] post.set_source() post.set_origin() post.save() #post.set_origin() return Response("Post Successfully Added.", status=status.HTTP_201_CREATED) except: return Response("Post Not Added", status=status.HTTP_400_BAD_REQUEST)