def signed(request, pet_id): p = get_object_or_404(Petition, pk=pet_id) userobject = get_object_or_404(Member, user=request.user) print userobject print "^^userobject^^" already_signed = SignPetition.objects.filter(user=userobject).filter( signedpet_id=pet_id) print already_signed if request.method == 'POST': signform = PetitionSignForm(request.POST) if already_signed: print "user already signed this petition!!!" elif signform.is_valid(): print 'user not signed yet. going to update database' instance = signform.save(commit=False) instance.user = userobject instance.signedpet = p instance.save() p.current_num = p.current_num + 1 p.save() new_hist = History() new_hist.user = userobject new_hist.item_type = "SIGN" new_hist.timestamp = datetime.datetime.now() new_hist.item_id = instance.id new_hist.save() return HttpResponseRedirect('/petitions/' + pet_id + '/')
def res(request): f = Cart.objects.filter(customer=request.user) print(f) for i in range(0, len(f)): h = History() h.item = f[i].name h.quantity = f[i].quantity h.totalcost = f[i].totalcost h.customer = f[i].customer h.order_date = timezone.datetime.now() #h.reserve_time = s print(f[i]) f[i].delete() h.save() print(h) t = Transactions() t.customer = request.user t.totalcost = (request.POST['cost']) t.order_date = timezone.datetime.now() t.save() #------------------------------------send mail---------------------------------------------- hi = History.objects.filter(customer=request.user, status="P") rec = str(request.user.email) html_content = render_to_string('transaction/email.html', {'hi': hi}) text_content = strip_tags(html_content) email = EmailMultiAlternatives("Your Order", text_content, settings.EMAIL_HOST_USER, [rec]) email.attach_alternative(html_content, "text/html") email.send() return redirect('home')
def friend_accept(request): if request.GET['username']: friend_username = request.GET['username'] try: friend = User.objects.get(username__exact=friend_username) except: friend = None try: friend_relation = MemberRelations.objects.get( Q(member_who_added__exact = friend.members) & Q(member_who_was_added__exact = request.user.members) ) except: return HttpResponseRedirect("/profile/") friend_relation.active = True friend_relation.save() new_hist=History() new_hist.user=request.user.members new_hist.item_type="FRIEND" new_hist.timestamp=datetime.datetime.now() new_hist.item_id=friend_relation.id new_hist.save() next_hist=History() next_hist.user=friend.members next_hist.item_type="FRIEND" next_hist.timestamp=datetime.datetime.now() next_hist.item_id=friend_relation.id next_hist.save() return HttpResponseRedirect("/notifications/") return HttpResponseRedirect("/profile/")
def index(request): userobject = Member.objects.get(user=request.user) print userobject if request.method == 'POST': form = PetitionForm(request.POST) if form.is_valid(): newpetobj = form.save(commit=False) newpetobj.user = userobject newpetobj.current_num = 0 newpetobj.timestamp = datetime.datetime.now() newpetobj.save() new_hist = History() new_hist.user = userobject new_hist.item_type = "PETITION" new_hist.timestamp = newpetobj.timestamp new_hist.item_id = newpetobj.id new_hist.save() return HttpResponseRedirect('/petitions/') else: form = PetitionForm() return render_to_response('user_pages/home/base_home_petitions.html', { 'form': form, }, context_instance=RequestContext(request))
def poll_create(request): if request.user.is_authenticated(): if request.method == 'POST': poll_form = PollCreateForm(request.POST, prefix="poll") if poll_form.is_valid(): print 'Valid Form' unsaved_poll = poll_form.save(commit=False) unsaved_poll.member = request.user.members unsaved_poll.save() history = History(user = request.user.members, item_type = 'POLL', item_id = unsaved_poll.id) history.save() return HttpResponseRedirect("/polls/"+str(unsaved_poll.id)) poll_form = PollCreateForm(prefix="poll") try: polls = Poll.objects.filter(member = request.user.members) except: polls = [] template_dict = { 'error': '', 'poll_form' : poll_form, 'polls': polls } return render_to_response( 'user_pages/polls/poll_create.html', template_dict, context_instance=RequestContext(request) ) else: return HttpResponseRedirect("/login/")
def index(request): userobject = Member.objects.get(user=request.user) inv_list = Invited.objects.filter(invited_user=userobject).values_list( 'debateinvite_id', flat=True) debate_list = Debate.objects.filter(id__in=inv_list) part_list = Participants.objects.filter( participant=userobject).values_list('debateparticipate_id', flat=True) part_deb_list = Debate.objects.filter(id__in=part_list) if request.method == 'POST': #form1=InviteDebateForm() form2 = ParticipantDebateForm() form = CreateDebateForm(request.POST) print 'request method is post(index)' if form.is_valid(): print 'form is valid(index)' new_debate = form.save(commit=False) new_debate.created_by = userobject new_debate.privacy = "none" new_debate.timestamp = datetime.datetime.now() new_debate.save() # # HISTORY TABLE UPDATION>>> # new_hist = History() new_hist.user = userobject new_hist.item_type = "DEBATE" new_hist.timestamp = new_debate.timestamp new_hist.item_id = new_debate.id new_hist.save() #p=get_object_or_404(Debate,pk=pet_id) print new_debate.num_part formset1 = formset_factory(InviteDebateForm, extra=new_debate.num_part) form1 = formset1() return render_to_response('user_pages/home/base_home_debate.html', { 'dform1': form1, 'dform2': form2, 'new_debate': new_debate, 'cur_user': request.user }, context_instance=RequestContext(request)) else: form = CreateDebateForm() return render_to_response('user_pages/home/base_home_debate.html', { 'debate_list': debate_list, 'part_deb_list': part_deb_list, 'dform': form, }, context_instance=RequestContext(request)) else: form = CreateDebateForm() return render_to_response('user_pages/home/base_home_debate.html', { 'debate_list': debate_list, 'part_deb_list': part_deb_list, 'dform': form, }, context_instance=RequestContext(request))
def defeat(self, event): profile = Profile.objects.get(user_id=event['data']['player']) profile.defeat = profile.defeat + 1 profile.save() history = History(user_id=event['data']['player'], text="Lose a fight", type="defeat") history.save()
def victory(self, event): profile = Profile.objects.get(user_id=event['data']['player']) profile.victory = profile.victory + 1 profile.save() history = History(user_id=event['data']['player'], text="Won a fight", type="victory") history.save()
def post(self, request, *args, **kwargs): try: data = request.data history = History(profile_id=data['profile'], movie_id=data.get('movie', None), tv_show_id=data.get('tv_show', None)) history.clean() history.save() return Response({"detail": "has been added successfully!"}) except Exception as e: return Response({"detail": str(e)}, status=404)
def create_trip(request, traveller_id): traveller_user = get_object_or_404(Traveller, pk=traveller_id) traveller_user_logged_in = get_object_or_404(Traveller, email=request.user) guide_user = get_object_or_404(Guide, email=request.user) if 'confirm' in request.POST: traveller = traveller_user.email guide = request.user place = Place.objects.filter(name=request.POST['place']).first() no_of_people = request.POST['no_of_people'] no_of_children = request.POST['no_of_children'] total_hours = request.POST['travel_hours'] nop = float(no_of_people) noc = float(no_of_children) noh = float(total_hours) if ((nop + noc * 0.75) <= 2): tp = 2 * noh * float(guide_user.price) tp = int(tp) elif ((nop + noc * 0.75) >= 8): tp = 8 * noh * float(guide_user.price) tp = int(tp) else: tp = (nop + noc * 0.75) * noh * float(guide_user.price) tp = int(tp) history = History(traveller=traveller, guide=guide, place=place, no_of_people=no_of_people, no_of_children=no_of_children, total_hours=total_hours, total_price=tp) history.save() trip_notification = Trip_Notification( receiver_email=traveller_user.email, sender_email=request.user, form=history) trip_notification.save() traveller_id = request.POST['traveller_id'] return redirect('/view_profile/' + traveller_id) places = guide_user.places.all() place_pattern = '' for place in places: place_pattern = place.name + '|' + place_pattern context = { 'traveller_user': traveller_user, 'logged_in_user': traveller_user_logged_in, 'places': places, 'place_pattern': place_pattern[:-1], 'guide_user': guide_user, } # print(guide_user.place) return render(request, 'travellers/create_trip.html', context)
def create_list_archive(list): request = {} request['LANGUAGE_CODE'] = 'en' sections = Section.tree.filter(list=list) sections_has_complementary = [] for section in sections: if SectionPharmForm.objects.filter(section=section).filter( complementary_list=True).count() > 0: sections_has_complementary.append(section.id) pharm_section = {} for section in sections: query = SectionPharmForm.objects.filter(section=section) pharm_section[section.id] = query output = {'list': list} output['nodes'] = sections output['pharm_section'] = pharm_section output['sections_has_complementary'] = sections_has_complementary output['request'] = request output['is_history'] = True list_xml = render_to_string('history/xml_list.tpl', output) list_xml = list_xml.strip() list_html = render_to_string('history/show_list.html', output) list_html = list_html.strip() history = History(name=list.name, abbreviation=list.abbreviation, year=list.year, edition=list.edition, type=list.type, subtype=list.subtype, published=list.published, obs=list.obs, created=datetime.now()) history.content = list_html history.xml = list_xml # save history main history.save() # save history translations save_translated_list_archive(list, history, output, request, 'pt-br') save_translated_list_archive(list, history, output, request, 'es')
def cards_sell(request): try: profile = request.user.profile card = profile.cards.get(id=request.POST.get('id')) profile.cards.remove(card) profile.credits += 1 history = History(user=request.user, text="Sold the card '" + card.name + "'", type='sell') history.save() profile.save() except ObjectDoesNotExist: return render(request, 'cards/cards_sell.html', {'success': False}) return render(request, 'cards/cards_sell.html', {'success': True})
def buy(request): profile = request.user.profile package = Package.objects.get(id=request.POST.get('id')) if package.price > profile.credits: return render(request, 'store/buy.html', {'success': False}) cards = Card.objects.get_random(package.cards_count) profile.cards.add(*cards) profile.credits -= package.price profile.save() history = History(user=request.user, text="Bought a new pack of " + package.cards_count.__str__() + " cards", type='store') history.save() return render(request, 'store/buy.html', {'success': True, 'package': package, 'cards': cards})
def create_history(history_type_dict, source_object=None, data=None): history_type = get_object_or_404(HistoryType, namespace=history_type_dict['namespace'], name=history_type_dict['name']) new_history = History(history_type=history_type) if source_object: new_history.content_object = source_object if data: new_dict = {} for key, value in data.items(): new_dict[key] = {} if isinstance(value, models.Model): new_dict[key]['value'] = serializers.serialize('json', [value]) elif isinstance(value, models.query.QuerySet): new_dict[key]['value'] = serializers.serialize('json', value) else: new_dict[key]['value'] = json.dumps(value) new_dict[key]['type'] = pickle.dumps(type(value)) new_history.dictionary = json.dumps(new_dict) new_history.save()
def create_history(history_type_dict, source_object=None, data=None): history_type = get_object_or_404(HistoryType, namespace=history_type_dict['namespace'], name=history_type_dict['name']) new_history = History(history_type=history_type) if source_object: new_history.content_object = source_object if data: new_dict = {} for key, value in data.items(): new_dict[key] = {} if isinstance(value, models.Model): new_dict[key]['value'] = serializers.serialize('json', [value]) elif isinstance(value, models.query.QuerySet): new_dict[key]['value'] = serializers.serialize('json', value) else: new_dict[key]['value'] = json.dumps(value) new_dict[key]['type'] = pickle.dumps(type(value)) new_history.dictionary = json.dumps(new_dict) new_history.save()
def blog_edit(request, blog_id = None): if request.user.is_authenticated(): try: existing_member = Member.objects.get(user__exact=request.user) except: existing_member = None try: blog = BlogPost.objects.get(pk__exact=blog_id) if blog.member != request.user.members: return HttpResponseRedirect("/blog/") except: blog = None if request.method == 'POST': print 'Posted' print request.POST form = BlogEditForm(request.POST, instance = blog ) if form.is_valid(): blog_post = form.save(commit=False) blog_post.member = request.user.members blog_post.save() if blog_id == None: history = History(user = request.user.members, item_type = 'BLOG', item_id = blog_post.id) history.save() return HttpResponseRedirect("/blog/"+str(blog_post.id)+"/") else: print 'not valid' form = BlogEditForm(instance = blog ) template_dict = { 'error': '', 'form' : form, 'member': existing_member, } return render_to_response( 'user_pages/blogs/blog_edit.html', template_dict, context_instance=RequestContext(request) ) else: return HttpResponseRedirect("/login/")
def index(request): if 'history' in request.session: history = json.loads(request.session['history']) print(history) else: history = [] if request.POST: if request.POST['URL']: filename, status = getImage(request.POST['URL']) #For testing #filename = str(uuid.uuid4()) + ".png" if status is '0': if request.user.is_authenticated: newhistory = History(url=request.POST['URL'], filename=filename, querytime=timezone.now(), user=request.user) newhistory.save() else: newhistory = { 'url': request.POST['URL'], 'filename': filename, 'querytime': timezone.now() } history.append(newhistory) request.session['history'] = json.dumps(history) return render(request, "index.html", { 'link': filename, 'status': status }) else: return render(request, "index.html") else: return render(request, "index.html")
def index(request): userobject = get_object_or_404(Member, user=request.user) print userobject.id user_albums = Album.objects.filter(user=userobject) dic = [] i = 0 print user_albums print "^^look here" print "now" if user_albums: for alb in user_albums: print alb print "---" try: pic = Photo.objects.filter(album=alb).latest('timestamp') dic.append([{ 'albumid': alb.id }, { 'albuma': alb.name }, { 'photo': pic.filename }]) except: dic.append([{'albumid': alb.id}, {'albuma': alb.name}]) print dic[i] i = i + 1 print "look down" print dic if request.method == 'POST': form = CreateAlbumForm(request.POST) #uploading image form2 = UploadImageForm(request.POST, request.FILES) f = request.FILES['file'] filename = ''.join( random.choice(string.ascii_lowercase + string.ascii_uppercase + string.digits) for x in range(80)) originalfilename = str(userobject.id) + "-" + datetime.datetime.now( ).strftime("%Y-%m-%d-%H-%M-%S") + "-" + filename + '.jpeg' if form.is_valid() and form2.is_valid(): new_album = form.save(commit=False) new_album.user = userobject new_album.timestamp = datetime.datetime.now() new_album.save() #uploding image foldername = settings.PHOTO_DIR try: os.mkdir(foldername) except OSError as exc: # Python >2.5 if exc.errno == errno.EEXIST and os.path.isdir(foldername): pass else: raise with open('ups/albumpics/' + originalfilename, 'wb+') as destination: for chunk in f.chunks(): destination.write(chunk) size = 150, 150 infile = 'ups/albumpics/' + originalfilename outfile = infile + "_thumbnail.jpeg" # outfile=os.path.splitext(infile)[0]+"_thumbnail.jpeg" if infile != outfile: try: im = Image.open(infile) im.thumbnail(size, Image.ANTIALIAS) im.save(outfile, "JPEG") except IOError: print "cannot create thumbnail" savepic = form2.save(commit=False) savepic.album_id = new_album.id savepic.filename = originalfilename savepic.timestamp = datetime.datetime.now() savepic.save() new_hist = History() new_hist.user = userobject new_hist.item_type = "ALBUM" new_hist.timestamp = new_album.timestamp new_hist.item_id = new_album.id new_hist.save() print "saving object with" print new_album.user print new_album.timestamp print new_album.name return HttpResponseRedirect('/albumlist/' + str(new_album.id) + '/') else: form = CreateAlbumForm() uploadform = UploadImageForm() return render_to_response('user_pages/photo/gallery.html', { 'albumlist': dic, 'form': form, 'imageform': uploadform }, context_instance=RequestContext(request))
def profile_view(request, profile_id): if ((profile_id is None) or profile_id == ''): profile_id = request.user.username print profile_id try: user = User.objects.get(username__exact=profile_id) except: return HttpResponseRedirect("/profile/") try: member = Member.objects.get(user__exact=user) except: return HttpResponseRedirect("/profile/") try: owner_member = Member.objects.get(user__exact=request.user) except: owner_member = None if request.method == 'POST': print "++++++++++++++++++++++++method post before try" try: print "++++++++++++++++++++++++method post after try" post_add_form = PostAddForm(request.POST) form = post_add_form.save(commit=False) form.member = request.user.members form.member_to = member form.save() print "+++++++++++++++loop starts" print "+++++++++++++++loop ends" post_history = History(user = request.user.members, item_type = 'POST', item_id = form.id) post_history.save() except: pass posts = Post.objects.order_by('-timestamp').filter(member_to=member) home_feed = [] for post in posts: print 'post: ', post test = {} test['owner_member'] = post.member test['type'] = "POST" test['item_id'] = post.id try: pin = PostPinned.objects.get( Q(post = test['item_id']) & Q(post_type = test['type']) & Q(member = request.user.members) ) except: pin = None if pin is not None: test['pin'] = True else: test['pin'] = False #Data for populating each activity Template test['parent_activity'] = post test['upvotes_number'] = post.upvotes_number test['downvotes_number'] = post.downvotes_number test['comments_number'] = post.comments_number print 'home_feed inside loop: ', home_feed home_feed.append(test) print 'home_feed: ', home_feed post_add_form = PostAddForm() template_dict = { 'error': '', 'member': member, 'owner_member': owner_member, 'profile_user': user, 'posts': posts, 'post_add_form': post_add_form, 'home_feed': home_feed, } return render_to_response('user_pages/profile/profile_view.html', template_dict, context_instance=RequestContext(request))
def parse_jabong(request): website = Website.objects.get(name="Jabong") brand = Brand.objects.get(name="Adidas") category = Category.objects.get(name="Shoes") url = 'http://www.jabong.com/men/shoes/men-sports-shoes/Adidas/?special_price=1&page=4' user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' values = {} headers = { 'User-Agent': user_agent, 'X-Requested-With': 'XMLHttpRequest' } data = urllib.urlencode(values) req = urllib2.Request(url, data, headers) response = urllib2.urlopen(req) html = response.read() tree = lxml.html.fromstring(html) for el in tree.cssselect("li.itm a.itm-link"): print el.cssselect(".itm-title")[0].text.strip() try: search_item = Item.objects.get(name=el.cssselect(".itm-title")[0].text.strip()) except: search_item = None print search_item if search_item is None: print "Item does not exist. Creating new" item = Item() item.name = el.cssselect(".itm-title")[0].text.strip() print item.name item.gender_type = "MALE" product_url = el.attrib["href"] item.url = product_url item.category = category item.brand = brand item.website = website item.slug = slugify(item.name + "=" + item.website.slug) old_price_text = el.cssselect(".itm-price.old")[0].text new_price_text = el.cssselect(".itm-price.special-b")[0].text discount_rate_text = el.cssselect(".itm-price.discount")[0].text re_float = re.compile(r'.*?(?P<number>\d+\.?\d*).*?') old_price = re_float.match(old_price_text).group("number") new_price = re_float.match(new_price_text).group("number") discount_rate = re_float.match(discount_rate_text).group("number") user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' values = {} headers = { 'User-Agent': user_agent, } data = urllib.urlencode(values) req = urllib2.Request(product_url, data, headers) product_response = urllib2.urlopen(req) product_html = product_response.read() product_tree = lxml.html.fromstring(product_html) print product_tree print product_tree.cssselect(".prd-image") print product_tree.cssselect(".prd-image")[0].attrib["src"] item.image_url1 = product_tree.cssselect("#prdImage")[0].attrib["src"] item.details = product_tree.cssselect(".prd-description")[0].text item.save() history = History() history.item = item history.offer_text = item.brand.name + " " + item.name + " " + old_price_text + " " + new_price_text + " " + discount_rate_text history.selling_price = float(new_price) history.actual_price = float(old_price) history.discount_rate = float(discount_rate) history.is_on_sale = True history.save() print item print "#######################################" return HttpResponse(html)
def recognition(request): face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml') eye_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_eye.xml') # smile_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_smile.xml') # 调用摄像头 cap = cv2.VideoCapture(0) # a=1 while (True): # 获取摄像头拍摄到的画面 ret, frame = cap.read() faces = face_cascade.detectMultiScale(frame, 1.3, 2) # faces = face_engine.detectMultiScale(img,scaleFactor = 1.3,minNeighbors = 5) img = frame for (x, y, w, h) in faces: img = cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2) face_area = img[y:y + h, x:x + w] eyes = eye_cascade.detectMultiScale(face_area, 1.3, 15) for (ex, ey, ew, eh) in eyes: cv2.rectangle(face_area, (ex, ey), (ex + ey, ey + eh), (0, 255, 0), 1) # 实时展示效果画面 cv2.imshow('frame', img) # 每5毫秒监听一次键盘动作 # a = True if cv2.waitKey(5) & 0xFF == ord('0'): face_encodings = face_recognition.face_encodings(img) # print(face_encodings[0]) user = Users.objects.filter(pk=request.session['uid']).first() y = face_recognition.face_encodings(cv2.imread(user.u_face))[0] res = face_recognition.compare_faces([y], face_encodings[0], tolerance=0.5) break cv2.destroyAllWindows() cap.release() # print(type(res)) statistic = Statistic.objects.get(pk=1) if res[0] == True: # print("欢迎业主回家") context = {"res": '欢迎业主回家'} history = History(h_username=request.session['username'], h_house_number=request.session['house_number'], h_datetime=timezone.now(), h_event='进门') history.save() # statistic = Statistic(s_true = ) statistic.s_true += 1 statistic.save() # print("欢迎业主回家") return JsonResponse(context) # return HttpResponse("欢迎业主回家") else: context = {"res": '抱歉,您不是手机持有者'} # print("请重新识别") # statistic = Statistic.objects.get(pk = 1) statistic.s_false += 1 statistic.save() return JsonResponse(context)
def create_user_profile(sender, instance, created, **kwargs): if created: history = History(user_id=instance.user.id, text="Created a new deck", type="deck") history.save()
def save_history_page(url, user): history = History(user=user, page=url) history.save()
def parse_jabong(request): website = Website.objects.get(name="Jabong") brand = Brand.objects.get(name="Adidas") category = Category.objects.get(name="Shoes") url = 'http://www.jabong.com/men/shoes/men-sports-shoes/Adidas/?special_price=1&page=4' user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' values = {} headers = {'User-Agent': user_agent, 'X-Requested-With': 'XMLHttpRequest'} data = urllib.urlencode(values) req = urllib2.Request(url, data, headers) response = urllib2.urlopen(req) html = response.read() tree = lxml.html.fromstring(html) for el in tree.cssselect("li.itm a.itm-link"): print el.cssselect(".itm-title")[0].text.strip() try: search_item = Item.objects.get( name=el.cssselect(".itm-title")[0].text.strip()) except: search_item = None print search_item if search_item is None: print "Item does not exist. Creating new" item = Item() item.name = el.cssselect(".itm-title")[0].text.strip() print item.name item.gender_type = "MALE" product_url = el.attrib["href"] item.url = product_url item.category = category item.brand = brand item.website = website item.slug = slugify(item.name + "=" + item.website.slug) old_price_text = el.cssselect(".itm-price.old")[0].text new_price_text = el.cssselect(".itm-price.special-b")[0].text discount_rate_text = el.cssselect(".itm-price.discount")[0].text re_float = re.compile(r'.*?(?P<number>\d+\.?\d*).*?') old_price = re_float.match(old_price_text).group("number") new_price = re_float.match(new_price_text).group("number") discount_rate = re_float.match(discount_rate_text).group("number") user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' values = {} headers = { 'User-Agent': user_agent, } data = urllib.urlencode(values) req = urllib2.Request(product_url, data, headers) product_response = urllib2.urlopen(req) product_html = product_response.read() product_tree = lxml.html.fromstring(product_html) print product_tree print product_tree.cssselect(".prd-image") print product_tree.cssselect(".prd-image")[0].attrib["src"] item.image_url1 = product_tree.cssselect( "#prdImage")[0].attrib["src"] item.details = product_tree.cssselect(".prd-description")[0].text item.save() history = History() history.item = item history.offer_text = item.brand.name + " " + item.name + " " + old_price_text + " " + new_price_text + " " + discount_rate_text history.selling_price = float(new_price) history.actual_price = float(old_price) history.discount_rate = float(discount_rate) history.is_on_sale = True history.save() print item print "#######################################" return HttpResponse(html)
def home(request): if request.user.is_authenticated(): if not request.user.is_active: return HttpResponseRedirect("/profile/edit/") user = User.objects.get(username__exact=request.user.username) print user try: member = Member.objects.get(user__exact=request.user) except: member = None if request.method == 'POST': try: post_add_form = PostAddForm(request.POST) form = post_add_form.save(commit=False) form.member = member form.member_to = member form.save() post_history = History(user=request.user.members, item_type='POST', item_id=form.id) post_history.save() except: pass try: relations = MemberRelations.objects.filter( (Q(member_who_added=member) | Q(member_who_was_added=member)) & Q(active=True)) except: relations = None friends_list = [] for relation in relations: if relation.member_who_added == member: friend = relation.member_who_was_added else: friend = relation.member_who_added friends_list.append(friend) friends_list.append(request.user.members) print "####Friends List####" print friends_list try: friends_history = History.objects.filter(user__in=friends_list) except: friends_history = None friends_history = friends_history.reverse() print "####Friends History####" print friends_history home_feed = [] for each_friend_history in friends_history: test = {} test['owner_member'] = each_friend_history.user test['type'] = each_friend_history.item_type test['item_id'] = each_friend_history.item_id try: pin = PostPinned.objects.get( Q(post=test['item_id']) & Q(post_type=test['type']) & Q(member=request.user.members)) except: pin = None if pin is not None: test['pin'] = True else: test['pin'] = False #Data for populating each activity Template if test['type'] == "POST": try: post = Post.objects.get(pk__exact=test['item_id']) test['parent_activity'] = post test['upvotes_number'] = post.upvotes_number test['downvotes_number'] = post.downvotes_number test['comments_number'] = post.comments_number except: post = None elif test['type'] == "ALBUM": try: album = Album.objects.get(pk__exact=test['item_id']) except: album = None try: photos = Photo.objects.order_by('-timestamp').filter( album=album)[:3] test['parent_activity'] = album test['album_photos'] = photos test['upvotes_number'] = album.upvotes_number test['downvotes_number'] = album.downvotes_number test['comments_number'] = album.comments_number except: photos = [] elif test['type'] == "PETITION": try: petition = Petition.objects.get(pk__exact=test['item_id']) test['parent_activity'] = petition test['upvotes_number'] = petition.upvotes_number test['downvotes_number'] = petition.downvotes_number test['comments_number'] = petition.comments_number except: petition = None elif test['type'] == "FRIEND": try: relation = MemberRelations.objects.get( pk__exact=test['item_id']) test['parent_activity'] = relation except: relation = None elif test['type'] == "DEBATE": try: debate = Debate.objects.get(pk__exact=test['item_id']) test['parent_activity'] = debate except: debate = None elif test['type'] == "POLL": try: poll = Poll.objects.get(pk__exact=test['item_id']) test['parent_activity'] = poll except: poll = None test['upvotes_number'] = poll.upvotes_number test['downvotes_number'] = poll.downvotes_number test['comments_number'] = poll.comments_number choices = [] try: choices = Choice.objects.filter(poll=poll) except: choices = [] print choices choices_list = [] total_votes_number = 0 for choice in choices: each_choice = {} voted_by = json.dumps(choice.voted_by) if request.user.username in voted_by: print '++++++++++++++++++++++++++++++++++++ present in voted_by', voted_by each_choice['voted'] = True each_choice['percentage'] = choice.votes_number each_choice['choice'] = choice choices_list.append(each_choice) total_votes_number += choice.votes_number #print ('choices_list ',choices_list) if total_votes_number != 0: for each_choice in choices_list: print('each_choice', each_choice) each_choice['percentage'] = each_choice[ 'percentage'] * 100 / total_votes_number print('each choice percentage', each_choice['percentage']) print('Total no of votes', total_votes_number) test['choices_list'] = choices_list home_feed.append(test) print "####Home Feed####" print home_feed home_feed.reverse() print home_feed post_add_form = PostAddForm() template_dict = { 'error': '', 'page_name': 'news', 'user': request.user, 'member': member, 'owner_member': member, 'post_add_form': post_add_form, 'home_feed': home_feed } return render_to_response('user_pages/home/page_news.html', template_dict, context_instance=RequestContext(request)) else: return HttpResponseRedirect("/login/")