def post_ajax(self, request, *args, **kwargs): # TODO # in fact this whole approach is a disgrace. Figure out how # to use Djangos modelformsets with AJAX and save things properly # to start with you should inherit from some view that has the # get_context_data method, then use that to pull some info ctx = {} # extract the forms id from out the dictionaries keys for x in request.POST.items(): if x[0].endswith('-id'): form_id = int(x[0][-4]) # id of form on html page # extract the values from the submitted form and create a # new dictionary out of it that is actually usuable prefix = "form-{}-".format(form_id) form = {} for x in request.POST.items(): if prefix in x[0]: left, right = x[0].split(prefix) form[right] = x[1] else: form[x[0]] = x[1] # query the DB to get the form in question post = PostQueue.objects.get(id=form['id']) # figure out which button they pressed (save, deactivate, or delete) # and perform different actions in response if form['btn_type'] in ('delete', 'draft'): # TODO # update facebook via the API. Note: the fbook_post_id will # need to be deleted for those posts that are now marked # as a draft fb = Fbook(user_id=request.user.id) draft = True if form['btn_type'] == 'draft' else False post_error = fb.deletePost(request, post.fbook_post_id, draft) if post_error: ctx['msg'] = 'your post was successfully deleted' return self.render_json_response(ctx) else: ctx['msg'] = 'An error occurred and we were unable to delete your post' return self.render_json_response(ctx) if form['btn_type'] == 'draft': post.status = 'draft' # TODO # write code here that sends a delete request to # facebook like is done above, only this time alter the # local copy of the post to be a draft. # TODO # check to see if there were any changes made to the form on save # If no changes were made then do not send Facebook an API request # to modify your message. If changes were made then send the request. # Note that if Facebook returns an error then do not resave this form. # code goes here # check if the item has an existing fbook_post_id. # if it does then this means they are updating/rescheduling a post # update the posts fields with the submitted information post.biz_id = form['biz'] post.message = form['message'] post.updated_by = request.user post.updated_on = datetime.datetime.utcnow().replace(tzinfo=utc) # construct the new date ptime = '{} {}:{}{}'.format( form['post_date_0'], form['post_date_1'], form['post_date_2'], form['post_date_3']) post.post_date = dateutil.parser.parse(ptime) # TODO # find a way to get the social site info # post.social_sites = [u'facebook'] post.save() # TODO - load the given post for the submitted post id # AKA only load a post when the user request it # VS what your doing right now which is loading # all the posts and just hiding them with AJAX ctx['hi'] = form['id'] ctx['msg'] = 'your post was saved successfully' return self.render_json_response(ctx)
def post(self, request, *args, **kwargs): ctx = self.get_context_data(**kwargs) form = PostQueueForm(request.POST or None) ctx['form'] = form if form.is_valid(): params = {} # add the missing values for created_by and created_on since # modelForms seem to have trouble automaticlly inheriting them the_post = form.save(commit=False) the_post.created_by = request.user the_post.created_on = datetime.datetime.utcnow().replace(tzinfo=utc) params['message'] = the_post.message # check which social networks they specified and configure the # parameters for your API request accordingly if 'facebook' in the_post.social_sites: fb = Fbook(user_id=request.user.id) # confirm that the messages in the insightfever DB matches # those scheduled on Facebook. If a descrepancy is found # then update either facebook or your own DB appropriately facebook_posts = fb.sync_managed_posts(the_post.biz_id) data = facebook_posts['data'] for d in data: log.info(d) # TODO # convert the unix timestamp in d['created_time'] to # a datetime object and figure out if the message has # already been posted yet. If a time descrepancy is found # then prompt the user with a dialogue box asking if they # want to overwrite the insightfever data with the facebook # or if they want to overwrite facebook data with ifever. # d['source_id'] # d['post_id'] # d['created_time'] # d['message'] # search the message for links. If found then request the page # for your first URL and search for facebook metatags so that # you can autofill some of the required fields: urls = fever_utils.find_urls(the_post.message) if urls: # TODO: # grab the link parameters from the javascript in the # page. AKA, create some hidden forms from which to # store your retrived javascript values, and on submit # to Facebook, inject those values into the API call params['link'] = urls[0] params = fb.getLinkParams(params) params['scheduled_publish_time'] = the_post.post_date # Post your message to the facebook page result = fb.postToPage(request, params, the_post.biz_id) # make sure Facebook acknowledged our post by returning an id if 'id' in result: the_post.fbook_post_id = result['id'] else: msg = "Facebook failed to return a post 'id'. You message failed to post" log.error(msg) message.error(request, msg) # if they chose to post to Twitter if 'twitter' in the_post.social_sites: # twit = connect_to_tweepy(request.user.id, the_post.biz_id) # NOTE # if posting a picture you need to use the # update_with_media parameter # https://dev.twitter.com/docs/api/1.1/post/statuses/update_with_media pass the_post.save() messages.info(request, 'Your post has been scheduled') return HttpResponseRedirect(reverse('social_post', args=(self.kwargs['biz_id'],))) messages.error(request, 'Your form did not validate') return self.render_to_response(ctx)