def newpost(request): if request.method == 'POST': if request.POST['title']: if request.POST['body'] or request.FILES: post = Post() post.title = request.POST['title'] if request.POST['url']: if request.POST['url'].startswith( 'https://') or request.POST['url'].startswith( 'http://'): post.url = request.POST['url'] else: posts.url = "http://" + request.POST['url'] if request.POST['body']: post.body = request.POST['body'] if request.FILES: if request.FILES['image']: post.image = request.FILES['image'] post.author = request.user post.save() return redirect('home') else: return render( request, 'posts/newpost.html', {'error': "Il faut au moins du texte ou une image"}) else: return render(request, 'posts/newpost.html')
def post(self, request, *args, **kwargs): if not request.user.has_perm('accounts.view_profile'): return render(request, '401.html') searchText = '' found_msg = None found_file = None # deal with search if ('search' in request.POST): if request.POST['search'].strip(): searchText = '' found_msg = None found_file = None found_bulletin = None searchText = request.POST['search'] entry_query = get_query(searchText, ['context', 'title', 'tag1']) found_msg = Post.objects.filter(entry_query).order_by('-time') entry_query = get_query(searchText, ['docfile', 'doctypeTag']) found_file = Document.objects.filter(entry_query).order_by('-time') entry_query = get_query(searchText, ['title', 'context']) found_bulletin = Bulletin.objects.filter(entry_query).order_by('-time') datalist = sorted(chain(list(found_msg), list(found_file), list(found_bulletin)),key=lambda instance: instance.time, reverse = True) else: datalist = [] #datalist = found_msg return render(request, self.template_name, {'alldata':datalist}) # deal with create announcement elif ( 'announce_title' in request.POST and 'announce_text' in request.POST ): newdoc = Post() newdoc.title = request.POST['announce_title'] newdoc.context = request.POST['announce_text'] newdoc.tag1 = "announcement" newdoc.author = MyProfile.objects.get(user=request.user) newdoc.save() return redirect("/home")
def create_view(request): if request.method == 'POST': if request.user.is_authenticated(): title = request.POST['title'] body = request.POST['body'] if title and body: post = Post() post.title = title post.body = language_filter(body) post.pub_date = timezone.datetime.now() post.author = request.user post.save() return JsonResponse( { "status": "success", "message": "post created", "post_id": post.pk }, status=201) else: return JsonResponse( { "status": "failure", "message": "title and post body cannot be empty" }, status=406) else: return JsonResponse( { "status": "failure", "message": "user need to login" }, status=403) else: return render(request, 'posts/create-postd.html')
def editor(request): if 'post' in request: pass if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): if form.cleaned_data['id']: post = Post.objects.get(id=int(form.cleaned_data['id'])) else: post = Post() post.date = int(time.time()) post.author = User.objects.get(id=1) #post.author = request.user post.title = form.cleaned_data['title'] post.text = form.cleaned_data['text'] post.save() post.set_tags(form.cleaned_data['tags']) post.save() return HttpResponseRedirect("/") elif request.method == 'GET': if 'id' in request.GET: post = Post.objects.get(id=int(request.GET['id'])) data = {'id': post.id, 'title': post.title, 'text': post.text, 'tags': post.tags_as_raw()} form = PostForm(data) else: form = PostForm() return render(request, "editor.html", {'form': form})
def test_post(self): post = Post() user = User.objects.create_user('Testy McTest', '*****@*****.**', 'testpassword') user.save() group = Group() group.name = "Test Group" group.save() membership = Membership() membership.user = User.objects.get(id = user.id) membership.group = Group.objects.get(id = group.id) membership.save() post.author = Membership.objects.get(id = membership.id) post.message = "Testing321" post.save() test_post = Post.objects.get(id = post.id) self.assertEquals(test_post, post) self.assertEquals(test_post.author, Membership.objects.get(id = membership.id)) self.assertEquals(test_post.message, "Testing321") post.delete() membership.delete() group.delete() user.delete()
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 test_delete_post_view_authenticated_user_returns_status_ok(self): """Test post view returns status code 200.""" this_user = self.users[0] self.client.force_login(this_user) this_post = Post() this_post.author = this_user this_post.save() response = self.client.get('/posts/' + str(this_post.id) + '/delete') self.assertTrue(response.status_code == 200)
def test_post_edit_wrong_user(self): """Test post edit wrong user returns 404.""" this_user = self.users[0] self.client.force_login(this_user) this_post = Post() this_post.author = self.users[1] this_post.save() response = self.client.post('/posts/' + str(this_post.id) + '/edit') self.assertTrue(response.status_code == 404)
def post(self, request, *args, **kwargs): if not request.user.has_perm('accounts.view_profile'): return render(request, '401.html') newdoc = Post() newdoc.title = request.POST['title'] newdoc.context = request.POST['context'] newdoc.tag1 = request.POST['tag1'] newdoc.author = MyProfile.objects.get(user=request.user) newdoc.save() return redirect("/posts/list")
def create(self): headline = ' '.join(faker.lorem().split(' ')[:4]) post = Post() post.author = UserFactory.create() post.headline = headline post.slug = slugify(headline) post.text = faker.lorem() post.save() return post
def post(self, request): form = AddPostForm(request.POST) if form.is_valid(): data = form.cleaned_data post = Post() post.text = data['text'] post.author = request.user post.save() return redirect("posts:list") return render_to_response(self.template_name, {'form': form}, context_instance=RequestContext(request))
def test_posts_view_renders_template_title(self): """Test post view response content contains post title.""" this_user = self.users[0] this_post = Post() this_post.author = this_user this_post.content = 'tornado fire crocodile' this_post.title = 'marc ben benny built this site' this_post.save() self.client.force_login(this_user) response = self.client.get('/posts/', follow=True) self.assertContains(response, 'marc ben benny built this site')
def post(self, request): post = Post() post.author = request.user form = PostForm(request.POST, instance=post) if form.is_valid(): new_post = form.save() messages.success( request, 'Post created successfully with ID {0}'.format(new_post.pk)) form = PostForm() context = {'form': form} return render(request, 'posts/new.html', context)
def test_other_user_post_view_authenticated_user_returns_status_ok(self): """Test other post view with authenticated client... ...returns status code 200. """ this_user = self.users[0] this_post = Post() this_post.author = this_user this_post.save() self.client.force_login(this_user) response = self.client.get('/posts/' + str(this_post.id), follow=True) self.assertTrue(response.status_code == 200)
def test_posts_view_renders_correct_template(self): """Test post view response renders the post.html template.""" this_user = self.users[0] this_post = Post() this_post.author = this_user this_post.content = 'tornado fire crocodile' this_post.title = 'marc ben benny built this site' this_post.save() self.client.force_login(this_user) response = self.client.get('/posts/', follow=True) self.assertTemplateUsed(response, "base.html") self.assertTemplateUsed(response, "posts/posts.html")
def test_view_other_user_post_on_posts_view(self): """Test other user posts' content shows on posts page.""" this_user = self.users[0] this_post = Post() this_post.author = this_user this_post.content = 'tornado fire crocodile' this_post.title = 'marc ben benny built this site' this_post.save() other_user = self.users[1] self.client.force_login(other_user) response = self.client.get('/posts/', follow=True) self.assertContains(response, 'tornado fire crocodile') self.assertContains(response, 'marc ben benny built this site')
def test_posts_render_on_other_profile(self): """Test profile view response content contains post content.""" this_user = self.users[0] this_post = Post() this_post.author = this_user this_post.content = 'tornado fire crocodile' this_post.title = 'marc ben benny built this site' this_post.save() self.client.force_login(self.users[1]) response = self.client.get( '/profile/' + str(this_user.username), follow=True) self.assertContains(response, 'tornado fire crocodile')
def test_post_comment_200(self): """Test post comment view returns status code 200.""" this_user = self.users[0] self.client.force_login(this_user) this_post = Post() this_post.author = this_user this_post.save() this_comment = Comment() this_comment.by_user = this_user this_comment.on_post = this_post this_comment.save() response = self.client.post('/posts/' + str(this_post.id)) self.assertTrue(response.status_code == 200)
def make_post(request): form = PostForm() if request.method == "POST": form = PostForm(request.POST) if form.is_valid(): post = Post(**form.cleaned_data) post.author = request.user post.slug = slugify(post.title) post.save() messages.add_message(request, messages.INFO, 'Your post was published.') return redirect('home') return render(request, 'posts/post_form.html', {'form': form})
def test_comment_when_not_logged_in(self): """Should return Forbidden Status Code.""" this_user = self.users[0] this_post = Post() this_post.author = this_user this_post.save() this_comment = Comment() this_comment.by_user = this_user this_comment.on_post = this_post this_comment.save() response = self.client.post( '/posts/' + str(this_post.id), follow=True, comment='yo') self.assertTrue(response.status_code == 403)
def form_valid(self, form): valid_response = super(PostCreateView, self).form_valid(form) # handling post creation post_text = form.cleaned_data.get('post_text') post = Post(post_text=post_text) post.author = self.request.user Post.save(post) # handling post images saving attachments = self.request.FILES.getlist('post_attachments') if len(attachments) > 0: self._save_attachments(attachments, post) return valid_response
def post(self, request, pk): data = {} group = Groups.objects.get(id=pk) post = Post() title = request.POST.get('group_post_title') post.title = title post.author = request.user post.save() group.posts.add(post) data['status'] = 1 return HttpResponse(json.dumps(data), content_type='application/x-json')
def test_comment_length_render_on_profile(self): """Test comment length render on profile post.""" this_user = self.users[0] self.client.force_login(this_user) this_post = Post() this_post.author = this_user this_post.save() this_comment = Comment() this_comment.by_user = this_user this_comment.on_post = this_post this_comment.save() this_comment = Comment() this_comment.by_user = this_user this_comment.on_post = this_post this_comment.save() response = self.client.get('/profile/') self.assertContains(response, 'Comments: (2)')
def test_comment_content_renders_on_posts_view(self): """Test comment comntent is in post request.""" this_user = self.users[0] self.client.force_login(this_user) this_post = Post() this_post.author = this_user this_post.content = 'tornado fire crocodile' this_post.title = 'marc ben benny built this site' this_post.save() this_comment = Comment() this_comment.by_user = this_user this_comment.on_post = this_post this_comment.comment = 'this comment' this_comment.save() response = self.client.post( '/posts/' + str(this_post.id), follow=True) self.assertContains(response, 'this comment')
def create(request): if request.method == 'POST': if request.POST['title'] and request.POST['url']: post = Post() post.title = request.POST['title'] if request.POST['url'].startswith('http://') or request.POST['url'].startswith('https://'): post.url = request.POST['url'] else: post.url = 'http://' + request.POST['url'] post.pub_date = timezone.datetime.now() post.author = request.user post.save() return redirect('home') else: return render(request, 'posts/create.html', {'error':'ERROR: You must include a title and u URL to create a post.'}) else: return render(request, 'posts/create.html')
def create(self, request, *args, **kwargs): serializer = PostSerializer(data=request.data) if serializer.is_valid(): post = Post(**serializer.validated_data) post.author = request.user post.save() if settings.ENABLE_SSE: self.redis_con.publish(settings.REDIS_SSE_CHANNEL, sse_event("post.created", post)) serializer = PostSerializer(post) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response( { 'status': 'Bad request', 'message': 'Post could not be created with received data.' }, status=status.HTTP_400_BAD_REQUEST)
def save_fetched_post(post_cache_key, rank, fetch_id): """Save Fetched Post Extracts fetched post from the cache to update the post properties and create snapshots of time varying post data in the database. """ # Get post from cache post = cache.get(post_cache_key, None) # Check for existence if not post: logger.error('Post not in cache') return # Consume post cache.delete(post_cache_key) # Get or create post model try: p = Post.objects.get(id=post.id) except Post.DoesNotExist: p = Post(id=post.id) # Update all fields p.title = post.title p.author = post.author p.url = post.url p.domain = post.domain p.over_18 = post.over_18 p.subreddit = post.subreddit p.created_on_reddit = datetime.utcfromtimestamp(post.created_utc).replace(tzinfo=pytz.UTC) p.save() fetch = Fetch.objects.get(id=fetch_id) post_snapshot = PostSnapshot( # Relations post = p, fetch = fetch, # Time data up_votes = post.ups, down_votes = post.downs, rank = rank, num_comments = post.num_comments ) post_snapshot.save()
def post(self, request, *args, **kwargs): if not request.user.has_perm('accounts.view_profile'): return render(request, '401.html') searchText = '' found_msg = None found_file = None # deal with search if ('search' in request.POST): if request.POST['search'].strip(): searchText = '' found_msg = None found_file = None found_bulletin = None searchText = request.POST['search'] entry_query = get_query(searchText, ['context', 'title', 'tag1']) found_msg = Post.objects.filter(entry_query).order_by('-time') entry_query = get_query(searchText, ['docfile', 'doctypeTag']) found_file = Document.objects.filter(entry_query).order_by( '-time') entry_query = get_query(searchText, ['title', 'context']) found_bulletin = Bulletin.objects.filter(entry_query).order_by( '-time') datalist = sorted(chain(list(found_msg), list(found_file), list(found_bulletin)), key=lambda instance: instance.time, reverse=True) else: datalist = [] #datalist = found_msg return render(request, self.template_name, {'alldata': datalist}) # deal with create announcement elif ('announce_title' in request.POST and 'announce_text' in request.POST): newdoc = Post() newdoc.title = request.POST['announce_title'] newdoc.context = request.POST['announce_text'] newdoc.tag1 = "announcement" newdoc.author = MyProfile.objects.get(user=request.user) newdoc.save() return redirect("/home")
def test_posts_view_preview(self): """A post of more than 40 chars is shortened.""" this_user = self.users[0] this_post = Post() this_post.author = this_user this_post.content = ( '11111111111111111111' + '11111111111111111111' + '11111111111111111111') this_post.title = 'marc ben benny built this site' this_post.save() self.client.force_login(self.users[1]) response = self.client.get( '/posts/', follow=True) self.assertContains( response, ('11111111111111111111' + '11111111111111111111' + '...') )
def create(request): '''title and url coming from create.html textfield''' if request.method == 'POST': if request.POST['title'] and request.POST['url']: post = Post() post.title = request.POST['title'] if request.POST['url'].startswith( 'http://') or request.POST['url'].startswith('https://'): post.url = request.POST['url'] else: post.url = "http://" + request.POST['url'] post.pub_date = timezone.datetime.now() post.author = request.user post.save() return redirect('home') else: return render(request, 'posts/create.html', {'error': 'ERROR. Fill in all the Field'}) else: return render(request, 'posts/create.html')
def test_comment_length_render_on_other_user_profile(self): """Test comment length render on profile post.""" this_user = self.users[0] this_post = Post() this_post.author = this_user this_post.save() this_comment = Comment() this_comment.by_user = this_user this_comment.on_post = this_post this_comment.save() this_comment = Comment() this_comment.by_user = this_user this_comment.on_post = this_post this_comment.save() this_comment = Comment() this_comment.by_user = this_user this_comment.on_post = this_post this_comment.save() self.client.force_login(self.users[1]) response = self.client.get( '/profile/' + str(this_user.username), follow=True) self.assertContains(response, 'Comments: (3)')
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 initialize_calendar(data): post_new_years = Post() post_new_years.author = Account.objects.get(username = data['username']) post_new_years.content = 'New Year\'s Day' post_new_years.start_time = datetime.date(2015, 1, 1) post_new_years.day_of_week = 'Thursday' post_new_years.is_holiday = True post_new_years.save() post_mlk = Post() post_mlk.author = Account.objects.get(username = data['username']) post_mlk.content = 'Martin Luther King Day' post_mlk.start_time = datetime.date(2015, 1, 19) post_mlk.day_of_week = 'Monday' post_mlk.is_holiday = True post_mlk.save() post_groundhog_day = Post() post_groundhog_day.author = Account.objects.get(username = data['username']) post_groundhog_day.content = 'Groundhog Day' post_groundhog_day.start_time = datetime.date(2015, 2, 1) post_groundhog_day.day_of_week = 'Monday' post_groundhog_day.is_holiday = True post_groundhog_day.save() post_rosa_parks = Post() post_rosa_parks.author = Account.objects.get(username = data['username']) post_rosa_parks.content = 'Rosa Parks Day' post_rosa_parks.start_time = datetime.date(2015, 2, 4) post_rosa_parks.day_of_week = 'Wednesday' post_rosa_parks.is_holiday = True post_rosa_parks.save() post_lincolns_bday = Post() post_lincolns_bday.author = Account.objects.get(username = data['username']) post_lincolns_bday.content = 'Lincoln\'s Birthday' post_lincolns_bday.start_time = datetime.date(2015, 2, 12) post_lincolns_bday.day_of_week = 'Thursday' post_lincolns_bday.is_holiday = True post_lincolns_bday.save() post_valentine = Post() post_valentine.author = Account.objects.get(username = data['username']) post_valentine.content = 'Valentine\'s Day' post_valentine.start_time = datetime.date(2015, 2, 14) post_valentine.day_of_week = 'Saturday' post_valentine.is_holiday = True post_valentine.save() post_presidents = Post() post_presidents.author = Account.objects.get(username = data['username']) post_presidents.content = 'President\'s Day' post_presidents.start_time = datetime.date(2015, 2, 16) post_presidents.day_of_week = 'Monday' post_presidents.is_holiday = True post_presidents.save() post_ash = Post() post_ash.author = Account.objects.get(username = data['username']) post_ash.content = 'Ash Wednesday Day' post_ash.start_time = datetime.date(2015, 2, 18) post_ash.day_of_week = 'Wednesday' post_ash.is_holiday = True post_ash.save() post_chinese = Post() post_chinese.author = Account.objects.get(username = data['username']) post_chinese.content = 'Chinese New Year' post_chinese.start_time = datetime.date(2015, 2, 19) post_chinese.day_of_week = 'Thursday' post_chinese.is_holiday = True post_chinese.save() post_texas = Post() post_texas.author = Account.objects.get(username = data['username']) post_texas.content = 'Texas Independence Day' post_texas.start_time = datetime.date(2015, 3, 2) post_texas.day_of_week = 'Monday' post_texas.is_holiday = True post_texas.save() post_employee = Post() post_employee.author = Account.objects.get(username = data['username']) post_employee.content = 'Employee Appreciation Day' post_employee.start_time = datetime.date(2015, 3, 6) post_employee.day_of_week = 'Friday' post_employee.is_holiday = True post_employee.save() post_daylight = Post() post_daylight.author = Account.objects.get(username = data['username']) post_daylight.content = 'Daylight Saving\'s Time' post_daylight.start_time = datetime.date(2015, 3, 6) post_daylight.day_of_week = 'Friday' post_daylight.is_holiday = True post_daylight.save() post_patrick = Post() post_patrick.author = Account.objects.get(username = data['username']) post_patrick.content = 'St. Patrick\'s Day' post_patrick.start_time = datetime.date(2015, 3, 17) post_patrick.day_of_week = 'Tuesday' post_patrick.is_holiday = True post_patrick.save() post_spring = Post() post_spring.author = Account.objects.get(username = data['username']) post_spring.content = 'Spring Solstice' post_spring.start_time = datetime.date(2015, 3, 20) post_spring.day_of_week = 'Friday' post_spring.is_holiday = True post_spring.save() post_friday = Post() post_friday.author = Account.objects.get(username = data['username']) post_friday.content = 'Good Friday' post_friday.start_time = datetime.date(2015, 4, 3) post_friday.day_of_week = 'Friday' post_friday.is_holiday = True post_friday.save() post_passover = Post() post_passover.author = Account.objects.get(username = data['username']) post_passover.content = 'Passover' post_passover.start_time = datetime.date(2015, 4, 4) post_passover.day_of_week = 'Saturday' post_passover.is_holiday = True post_passover.save() post_easter = Post() post_easter.author = Account.objects.get(username = data['username']) post_easter.content = 'Easter Sunday' post_easter.start_time = datetime.date(2015, 4, 5) post_easter.day_of_week = 'Sunday' post_easter.is_holiday = True post_easter.save() post_tax = Post() post_tax.author = Account.objects.get(username = data['username']) post_tax.content = 'Tax Day' post_tax.start_time = datetime.date(2015, 4, 15) post_tax.day_of_week = 'Wednesday' post_tax.is_holiday = True post_tax.save() post_cinco = Post() post_cinco.author = Account.objects.get(username = data['username']) post_cinco.content = 'Cinco de Mayo' post_cinco.start_time = datetime.date(2015, 5, 5) post_cinco.day_of_week = 'Tuesday' post_cinco.is_holiday = True post_cinco.save() post_mother = Post() post_mother.author = Account.objects.get(username = data['username']) post_mother.content = 'Mother\'s Day' post_mother.start_time = datetime.date(2015, 5, 15) post_mother.day_of_week = 'Sunday' post_mother.is_holiday = True post_mother.save() post_armed = Post() post_armed.author = Account.objects.get(username = data['username']) post_armed.content = 'Armed Forces Day' post_armed.start_time = datetime.date(2015, 5, 16) post_armed.day_of_week = 'Saturday' post_armed.is_holiday = True post_armed.save() post_memorial = Post() post_memorial.author = Account.objects.get(username = data['username']) post_memorial.content = 'Memorial Day' post_memorial.start_time = datetime.date(2015, 5, 25) post_memorial.day_of_week = 'Monday' post_memorial.is_holiday = True post_memorial.save() post_dday = Post() post_dday.author = Account.objects.get(username = data['username']) post_dday.content = 'D-Day Day' post_dday.start_time = datetime.date(2015, 6, 6) post_dday.day_of_week = 'Saturday' post_dday.is_holiday = True post_dday.save() post_flag = Post() post_flag.author = Account.objects.get(username = data['username']) post_flag.content = 'Flag Day' post_flag.start_time = datetime.date(2015, 6, 14) post_flag.day_of_week = 'Sunday' post_flag.is_holiday = True post_flag.save() post_summer = Post() post_summer.author = Account.objects.get(username = data['username']) post_summer.content = 'Summer Starts' post_summer.start_time = datetime.date(2015, 6, 21) post_summer.day_of_week = 'Sunday' post_summer.is_holiday = True post_summer.save() post_father = Post() post_father.author = Account.objects.get(username = data['username']) post_father.content = 'Father\'s Day' post_father.start_time = datetime.date(2015, 6, 21) post_father.day_of_week = 'Sunday' post_father.is_holiday = True post_father.save() post_independence = Post() post_independence.author = Account.objects.get(username = data['username']) post_independence.content = 'Independence Day' post_independence.start_time = datetime.date(2015, 7, 4) post_independence.day_of_week = 'Saturday' post_independence.is_holiday = True post_independence.save() post_labor = Post() post_labor.author = Account.objects.get(username = data['username']) post_labor.content = 'Labor Day' post_labor.start_time = datetime.date(2015, 9, 7) post_labor.day_of_week = 'Monday' post_labor.is_holiday = True post_labor.save() post_patriot = Post() post_patriot.author = Account.objects.get(username = data['username']) post_patriot.content = 'Patriot Day' post_patriot.start_time = datetime.date(2015, 9, 11) post_patriot.day_of_week = 'Friday' post_patriot.is_holiday = True post_patriot.save() post_constitution = Post() post_constitution.author = Account.objects.get(username = data['username']) post_constitution.content = 'Constitution Day' post_constitution.start_time = datetime.date(2015, 9, 17) post_constitution.day_of_week = 'Thursday' post_constitution.is_holiday = True post_constitution.save() post_fall = Post() post_fall.author = Account.objects.get(username = data['username']) post_fall.content = 'Autumnal Equinox' post_fall.start_time = datetime.date(2015, 9, 23) post_fall.day_of_week = 'Wednesday' post_fall.is_holiday = True post_fall.save() post_columbus = Post() post_columbus.author = Account.objects.get(username = data['username']) post_columbus.content = 'Columbus Day' post_columbus.start_time = datetime.date(2015, 10, 12) post_columbus.day_of_week = 'Monday' post_columbus.is_holiday = True post_columbus.save() post_halloween = Post() post_halloween.author = Account.objects.get(username = data['username']) post_halloween.content = 'Halloween' post_halloween.start_time = datetime.date(2015, 10, 31) post_halloween.day_of_week = 'Saturday' post_halloween.is_holiday = True post_halloween.save() post_light = Post() post_light.author = Account.objects.get(username = data['username']) post_light.content = 'Daylight Saving Time Ends' post_light.start_time = datetime.date(2015, 11, 1) post_light.day_of_week = 'Sunday' post_light.is_holiday = True post_light.save() post_election = Post() post_election.author = Account.objects.get(username = data['username']) post_election.content = 'Election Day' post_election.start_time = datetime.date(2015, 11, 3) post_election.day_of_week = 'Tuesday' post_election.is_holiday = True post_election.save() post_thanksgiving = Post() post_thanksgiving.author = Account.objects.get(username = data['username']) post_thanksgiving.content = 'Thanksgiving' post_thanksgiving.start_time = datetime.date(2015, 11, 26) post_thanksgiving.day_of_week = 'Tuesday' post_thanksgiving.is_holiday = True post_thanksgiving.save() post_presidents = Post() post_presidents.author = Account.objects.get(username = data['username']) post_presidents.content = 'President\'s Day' post_presidents.start_time = datetime.date(2015, 11, 27) post_presidents.day_of_week = 'Friday' post_presidents.is_holiday = True post_presidents.save() post_black = Post() post_black.author = Account.objects.get(username = data['username']) post_black.content = 'Black Friday' post_black.start_time = datetime.date(2015, 11, 27) post_black.day_of_week = 'Friday' post_black.is_holiday = True post_black.save() post_monday = Post() post_monday.author = Account.objects.get(username = data['username']) post_monday.content = 'Cyber Monday' post_monday.start_time = datetime.date(2015, 11, 30) post_monday.day_of_week = 'Monday' post_monday.is_holiday = True post_monday.save() post_han = Post() post_han.author = Account.objects.get(username = data['username']) post_han.content = 'Hanukkah' post_han.start_time = datetime.date(2015, 12, 7) post_han.day_of_week = 'Monday' post_han.is_holiday = True post_han.save() post_pearl = Post() post_pearl.author = Account.objects.get(username = data['username']) post_pearl.content = 'Pearl Harbor Remembrance Day' post_pearl.start_time = datetime.date(2015, 12, 7) post_pearl.day_of_week = 'Monday' post_pearl.is_holiday = True post_pearl.save() post_winter = Post() post_winter.author = Account.objects.get(username = data['username']) post_winter.content = 'Winter Solstice' post_winter.start_time = datetime.date(2015, 12, 22) post_winter.day_of_week = 'Tuesday' post_winter.is_holiday = True post_winter.save() post_xmas_eve = Post() post_xmas_eve.author = Account.objects.get(username = data['username']) post_xmas_eve.content = 'Christmas Eve' post_xmas_eve.start_time = datetime.date(2015, 12, 24) post_xmas_eve.day_of_week = 'Thursday' post_xmas_eve.is_holiday = True post_xmas_eve.save() post_xmas = Post() post_xmas.author = Account.objects.get(username = data['username']) post_xmas.content = 'Christmas Day' post_xmas.start_time = datetime.date(2015, 12, 25) post_xmas.day_of_week = 'Friday' post_xmas.is_holiday = True post_xmas.save() post_nye = Post() post_nye.author = Account.objects.get(username = data['username']) post_nye.content = 'New Year\'s Eve' post_nye.start_time = datetime.date(2015, 12, 31) post_nye.day_of_week = 'Thursday' post_nye.is_holiday = True post_nye.save()
def savepost(request): if request.method == 'POST': title = request.POST.get("title", "") #message = request.POST.get("message", "") message = request.POST.get("message", "") if request.user.id: users_id = request.user.id user = User.objects.get(id=users_id) ac_token = user.ac_token linkedin_id = user.linkedin_id if request.POST.get('sent_on'): post_obj = Post() sent_on = request.POST.get('sent_on') user = User.objects.get(id=users_id) post_obj.content = message post_obj.title = title post_obj.author = user post_obj.sent_on = sent_on post_obj.type = 0 # personal profile =0 = page = 2 group = 3 post_obj.status = 0 # pending 0 sent 1 post_obj.save() return render(request, 'dashboard.html') else: api_url = "https://api.linkedin.com/v2/ugcPosts" #"author": "urn:li:person:" + linkedin_id, #"author": "urn:li:organization:" + linkedin_id, post_data = { "author": "urn:li:person:"+linkedin_id, "lifecycleState": "PUBLISHED", "specificContent": { "com.linkedin.ugc.ShareContent": { "shareCommentary": { "text": message }, "shareMediaCategory": "NONE" }, }, "visibility": { "com.linkedin.ugc.MemberNetworkVisibility": "PUBLIC" }, } headers = {'X-Restli-Protocol-Version': '2.0.0', 'Content-Type': 'application/json', 'Authorization': f'Bearer {ac_token}'} response = requests.post(api_url, headers=headers, json=post_data) if response.status_code == 201: print("Success") post_obj = Post() user = User.objects.get(id=users_id) post_obj.content = message post_obj.title = title post_obj.author = user post_obj.type = 0 # personal profile =0 = page = 2 group = 3 post_obj.status = 1 # sent post_obj.save() return render(request, 'dashboard.html') else: print(response.content) return render(request, 'addpost.html') else: return render(request, 'login.html') return render(request, 'addpost.html')
def repeat_events(event): start_time = event.start_time end_repeat_date = event.end_repeat repeat_type = event.repeat num_repeat = find_repeat(start_time, end_repeat_date, repeat_type) for x in range(1, num_repeat + 1): temp_event = Post() temp_event.author = event.author temp_event.content = event.content temp_event.notification = event.notification temp_event.notify_when = event.notify_when temp_event.location_event = event.location_event temp_event.description_event = event.description_event temp_event.begin_time = event.begin_time temp_event.end_time = event.end_time temp_event.end_repeat = event.end_repeat temp_event.need_repeat = False temp_event.start_time = event.start_time temp_event.not_all_day = event.not_all_day temp_event.repeat = event.repeat if repeat_type == 'Daily': temp_event.start_time = temp_event.start_time + datetime.timedelta( days=x) temp_event.notify_when = temp_event.notify_when + datetime.timedelta( days=x) print 'datetime.timedelta' + str(datetime.timedelta(days=x)) elif repeat_type == 'Monthly': temp_event.start_time = temp_event.start_time + relativedelta( months=+x) temp_event.notify_when = temp_event.notify_when + relativedelta( months=+x) elif repeat_type == 'Weekly': temp_event.start_time = temp_event.start_time + datetime.timedelta( days=7) * x temp_event.notify_when = temp_event.notify_when + datetime.timedelta( days=7) * x if temp_event.start_time.weekday() == 0: temp_event.day_of_week = 'Monday' elif temp_event.start_time.weekday() == 1: temp_event.day_of_week = 'Tuesday' elif temp_event.start_time.weekday() == 2: temp_event.day_of_week = 'Wednesday' elif temp_event.start_time.weekday() == 3: temp_event.day_of_week = 'Thursday' elif temp_event.start_time.weekday() == 4: temp_event.day_of_week = 'Friday' elif temp_event.start_time.weekday() == 5: temp_event.day_of_week = 'Saturday' elif temp_event.start_time.weekday() == 6: temp_event.day_of_week = 'Sunday' print 'Temp_Event Date: ' + str(temp_event.start_time) print 'Temp Event Day of Week: ' + str(temp_event.day_of_week) temp_event.show_date = str(temp_event.start_time)[5:7] + "/" + str( temp_event.start_time)[8:10] + "/" + str( temp_event.start_time)[0:4] temp_event.show_begin_time = str(temp_event.begin_time)[11:16] temp_event.show_end_time = str(temp_event.begin_time)[11:16] temp_event.is_date_set = True temp_event.is_week_set = True if temp_event.day_of_week == 'Sunday': temp_event.week_num = temp_event.start_time.isocalendar()[1] + 1 else: temp_event.week_num = temp_event.start_time.isocalendar()[1] print 'in repeat py day of week: ' + str(temp_event.week_num) temp_event.save()
def repeat_events(event): start_time = event.start_time end_repeat_date = event.end_repeat repeat_type = event.repeat num_repeat = find_repeat(start_time, end_repeat_date, repeat_type) for x in range(1, num_repeat + 1): temp_event = Post() temp_event.author = event.author temp_event.content = event.content temp_event.notification = event.notification temp_event.notify_when = event.notify_when temp_event.location_event = event.location_event temp_event.description_event = event.description_event temp_event.begin_time = event.begin_time temp_event.end_time = event.end_time temp_event.end_repeat = event.end_repeat temp_event.need_repeat = False temp_event.start_time = event.start_time temp_event.not_all_day = event.not_all_day temp_event.repeat = event.repeat if repeat_type == 'Daily': temp_event.start_time = temp_event.start_time + datetime.timedelta(days=x) temp_event.notify_when = temp_event.notify_when + datetime.timedelta(days=x) print 'datetime.timedelta' + str(datetime.timedelta(days=x)) elif repeat_type == 'Monthly': temp_event.start_time = temp_event.start_time + relativedelta( months = +x ) temp_event.notify_when = temp_event.notify_when + relativedelta( months = +x ) elif repeat_type == 'Weekly': temp_event.start_time = temp_event.start_time + datetime.timedelta(days=7) * x temp_event.notify_when = temp_event.notify_when + datetime.timedelta(days=7) * x if temp_event.start_time.weekday() == 0: temp_event.day_of_week = 'Monday' elif temp_event.start_time.weekday() == 1: temp_event.day_of_week = 'Tuesday' elif temp_event.start_time.weekday() == 2: temp_event.day_of_week = 'Wednesday' elif temp_event.start_time.weekday() == 3: temp_event.day_of_week = 'Thursday' elif temp_event.start_time.weekday() == 4: temp_event.day_of_week = 'Friday' elif temp_event.start_time.weekday() == 5: temp_event.day_of_week = 'Saturday' elif temp_event.start_time.weekday() == 6: temp_event.day_of_week = 'Sunday' print 'Temp_Event Date: ' + str(temp_event.start_time) print 'Temp Event Day of Week: ' + str(temp_event.day_of_week) temp_event.show_date = str(temp_event.start_time)[5:7] + "/" + str(temp_event.start_time)[8:10] + "/" + str(temp_event.start_time)[0:4] temp_event.show_begin_time = str(temp_event.begin_time)[11:16] temp_event.show_end_time = str(temp_event.begin_time)[11:16] temp_event.is_date_set = True temp_event.is_week_set = True if temp_event.day_of_week == 'Sunday': temp_event.week_num = temp_event.start_time.isocalendar()[1] + 1 else: temp_event.week_num = temp_event.start_time.isocalendar()[1] print 'in repeat py day of week: ' + str(temp_event.week_num) temp_event.save()