def transform_usage_error(caller, self, request, *args, **kwargs): """ Can be used for both html and ajax requests, so only 'error' HTTP codes should be returned if an exception is encountered. """ dm = request.datamanager return_to_home_url = game_view_url("pychronia_game-homepage", datamanager=dm) return_to_home = HttpResponseRedirect(return_to_home_url) from ..authentication import TEMP_URL_USERNAME return_to_login_url = game_view_url("pychronia_game-login", datamanager=dm) return_to_login_next_url = request.build_absolute_uri() # we do a HACK to deal with in-url usernames (except UNIVERSAL_URL_USERNAME username, which stays as is) return_to_login_next_url = return_to_login_next_url.replace("/%s/" % dm.user.username, "/%s/" % TEMP_URL_USERNAME) return_to_login_qs = urllib.parse.urlencode(dict(next=return_to_login_next_url)) return_to_login = HttpResponseRedirect("%s?%s" % (return_to_login_url, return_to_login_qs)) assert urlresolvers.resolve(return_to_home_url) try: return caller(self, request, *args, **kwargs) except AccessDeniedError as e: if request.is_ajax(): return HttpResponseForbidden(repr(e)) if request.datamanager.user.is_impersonation: # Will mainly happen when we switch between two impersonations with different access rights, on a restricted page dm.user.add_warning(_("Currently impersonated user can't access view '%s'") % self.TITLE) else: dm.user.add_error(_("Access denied to page %s") % self.TITLE) dm.logger.warning("Access denied to page %s" % self.TITLE, exc_info=True) if not request.datamanager.user.impersonation_target and request.datamanager.user.is_anonymous: return return_to_login # special case for REAL anonymous users return return_to_home except (GameError, POSError) as e: if request.is_ajax(): return HttpResponseBadRequest(repr(e)) dm.logger.critical("Unexpected game error in %s" % self.NAME, exc_info=True) dm.user.add_error(_("An unexpected server error occurred, please retry (%s)") % ( e if dm.is_master() else _("contact webmaster if it persists"))) return return_to_home # else, we let 500 handler take are of all other (very abnormal) exceptions assert False
def search(request): if getattr(settings, 'PARLIAMENT_SEARCH_CLOSED', False): return closed(request, message=settings.PARLIAMENT_SEARCH_CLOSED) if 'q' in request.GET and request.GET['q']: if not 'page' in request.GET: resp = try_postcode_first(request) if resp: return resp if not request.is_ajax(): resp = try_politician_first(request) if resp: return resp query = request.GET['q'].strip() if request.GET.get('prepend'): query = request.GET['prepend'] + ' ' + query if 'page' in request.GET: try: pagenum = int(request.GET['page']) except ValueError: pagenum = 1 else: pagenum = 1 startfrom = (pagenum - 1) * PER_PAGE query_obj = SearchQuery(query, start=startfrom, limit=PER_PAGE, user_params=request.GET, facet=True) ctx = dict(query=query, pagenum=pagenum, discontinuity=query_obj.discontinuity, chart_years=[c[0] for c in query_obj.date_counts], chart_values=[c[1] for c in query_obj.date_counts], facet_fields=query_obj.facet_fields, page=SearchPaginator(query_obj.documents, query_obj.hits, pagenum, PER_PAGE)) ctx.update(query_obj.validated_user_params) else: ctx = { 'query': '', 'page': None, } if request.is_ajax(): t = loader.get_template("search/search_results.inc") else: t = loader.get_template("search/search.html") return HttpResponse(t.render(ctx, request))
def Add_like(request): if request.is_ajax(): blog_id = int(request.GET.get('blog_id')) blog = get_object_or_404(Blog, pk=blog_id) blog.likes = blog.likes + 1 blog.save() return HttpResponse('success')
def LLH_convert(request): strings = { 'CN': { 'ERR_LLH': '导出至LL Helper sd格式失败...', 'SUCCESS': '成功导出至LL Helper sd格式', 'ERR_NONAJAX': '服务器接收请求不是AJAX' }, 'EN': { 'ERR_LLH': 'Failed export to LL Helper sd format...', 'SUCCESS': 'Successfully export to LL Helper sd format', 'ERR_NONAJAX': 'The request is not AJAX' } } lang = request.POST.get('lang', 'EN') if request.is_ajax(): user_json = request.POST['user_json'] user_info = 'User Information: {0} from {1} LLH convert page'.format(str(get_client_ip(request)), lang) print(user_info) try: user_profile = GameData(user_json, file_type='pll', string_input=True) user_json = user_profile.to_LLHelper(filename=None) except: print('Failed to convert LL Helper sd format.') message = {'complete':False, 'msg':strings[lang]['ERR_LLH']} return JsonResponse(message) message = { 'complete': True, 'user_json': user_json, 'msg': strings[lang]['SUCCESS'] } else: message = {'complete':False, 'msg':strings[lang]['ERR_NONAJAX']} return JsonResponse(message)
def dropSessionData(request): print(request.method) if not (request.is_ajax() or request.method=='POST'): return HttpResponseNotAllowed(['POST']) del request.session['floatingRows'] request.session['floatingRows'] = [] return HttpResponse('ok')
def wrap(request, *args, **kwargs): def failure_http(): return render(request, 'captcha_fail.html',) def failure_ajax(): return HttpResponse('There was a problem with the captcha, please try again') if request.method == 'POST': url = "https://www.google.com/recaptcha/api/siteverify" values = { 'secret': settings.GOOGLE_RECAPTCHA_SECRET_KEY, 'response': request.POST.get('g-recaptcha-response', None), 'remoteip': request.META.get("REMOTE_ADDR", None), } data = urllib.parse.urlencode(values) req = urllib.request.Request(url, data) response = urllib.request.urlopen(req) result = json.loads(response.read()) # result["success"] will be True on a success if result["success"]: return view(request, *args, **kwargs) elif request.is_ajax(): return failure_ajax() else: return failure_http() return view(request, *args, **kwargs)
def takeaway_order_view(request): takeaway_orders = TakeawayOrder.objects.all() basket_items = BasketItem.objects.all() form = TakeawayStatusForm today_date = datetime.date(datetime.now()) data = { 'today_date': today_date, 'takeaway_orders': takeaway_orders, 'basket_items': basket_items, 'form': form, } # allow staff to update the status of order if request.method == 'POST' and request.is_ajax(): status = request.POST.get('order_status') order_id = request.POST.get('order_id') update_status = TakeawayOrder.objects.get(order_id=order_id) update_status.status = status update_status.save() print(update_status.status) return render(request, 'staff_templates/takeaway_orders.html', data)
def set_judge(request): if request.is_ajax(): team_name = request.POST.get('team_name') Team.objects.filter(name=team_name).first().delete() info = "已删除队伍\"" + str(team_name) + "\"" response = HttpResponse(json.dumps({"info": info})) return response
def search(request): try: if request.is_ajax(): what_search = request.POST.get('what_search', None) # getting data from input first_name id if what_search: # cheking if first_name have value search_data = {} index = 1 unit2 = ProductRough.objects.filter( name__icontains=what_search) for i in unit2: search_data[index] = {} search_data[index]['itemid'] = i.itemid search_data[index]['search_name'] = i.name search_data[index]['search_image'] = i.images[2:34] index += 1 a = json.dumps(search_data, ensure_ascii=False) response = { 'msg': a # response message } return JsonResponse(response) # return response as JSON # return render(request, 'suppliescmb.html', locals()) except: # messages.error(request, '查無商品!!!') return render(request, 'suppliescmb.html', locals())
def handle_save(request, entry_id, handle): if not request.is_ajax(): return HttpResponseBadRequest() command = request.POST.get("command") messages = [] entry = None if command: messages += version_check(request.POST.get("version")) if command == "check": pass elif command in ("save", "autosave", "recover"): entry = _save_command(request, entry_id, handle, command, messages) else: return HttpResponseBadRequest("unrecognized command") resp = json.dumps({'messages': messages}, ensure_ascii=False) response = HttpResponse(resp, content_type=JSON_TYPE) # We want to set ETag ourselves to the correct value because the # etag decorator will actually set it to the value it had before the # request was processed! if entry: response['ETag'] = quote_etag(entry.latest.etag) return response
def images_list(request): if request.method == 'POST' and request.is_ajax(): post_objects = ImagePalette.objects.filter(is_featured=True).order_by('-date') if not post_objects: return HttpResponse('empty') paginator = Paginator(post_objects, 15) page = request.POST.get('page') try: posts_paginator = paginator.page(page) except PageNotAnInteger: return HttpResponseBadRequest() except EmptyPage: return HttpResponseBadRequest() context = {'object_list': posts_paginator.object_list, 'user': request.user, 'is_featured': False} html = render_to_string('image-item.html', context) return HttpResponse(html) else: return render(request, 'images-list.html')
def add_central(request): return_obj = {} if request.is_ajax() and request.method == 'POST': url = request.POST['url'] title = request.POST['title'] if url.endswith('/'): url = url[:-1] if(checkCentral(url)): return_obj['message'] = 'Valid HIS Central Found' return_obj['status'] = True # Add to the database SessionMaker = app.get_persistent_store_database( Persistent_Store_Name, as_sessionmaker=True) session = SessionMaker() hs_one = HISCatalog(title=title, url=url) session.add(hs_one) session.commit() session.close() else: return_obj['message'] = 'Not a valid HIS Central Catalog' return_obj['status'] = False else: return_obj[ 'message'] = 'This request can only be made through a "POST" AJAX call.' return_obj['status'] = False return JsonResponse(return_obj)
def get_interview_info(request): if request.is_ajax(): interview = request.POST['interview'] interview_list = Interview.objects.all() team = "" date = "" start_time = "" end_time = "" location = "" remarks = "" for i in interview_list: interview_id = str(i.id) if interview_id == interview: team = i.team date = i.date start_time = i.start_time end_time = i.end_time location = i.location remarks = i.remarks break response = HttpResponse( json.dumps({ 'team': team, 'date': date, 'start_time': start_time, 'end_time': end_time, 'location': location, 'remarks': remarks })) return response
def del_mem(request): if request.is_ajax(): Member_num = request.POST.get('Member_num') Employee.objects.filter(number=Member_num).delete() info = "已删除成员\"" + str(Member_num) + "\"" response = HttpResponse(json.dumps({"info": info})) return response
def new_interview(request): if request.is_ajax(): print(request.body) json_data = json.loads(request.body.decode('utf-8')) print(json_data) print(json_data['team']) print(json_data['temp_list']) print(type(json_data['temp_list'])) list1 = json_data['temp_list'] aa = [] for i in list1: aa.append(i['number'] + " " + i['name'] + " " + i['phone_number'] + " " + i['mail']) bb = "++++".join(aa) Interview.objects.create(team=json_data['team'], date=json_data['date'], location=json_data['location'], start_time=json_data['start_time'], end_time=json_data['end_time'], judge_list=bb, remarks=json_data['remarks']) # info = "lalala" info = "已建立面试 \"" + str(request.body.decode('utf-8')) response = HttpResponse(json.dumps({"info": info})) return response
def profile_likes(request, id_profile): if request.method == 'POST' and request.is_ajax(): post_objects = GradientPalette.objects.filter(likes=id_profile).order_by('-date') return load_palettes(request, post_objects, False) else: profile = get_object_or_404(Profile, user_id=id_profile) return render(request, 'profile.html', {'profile': profile, 'active': 'likes'})
def get_interview_students(request): if request.is_ajax(): interview = request.POST.get('interview') # ms.objects.create(student_number='2016011123') interview_list = Interview.objects.all() msg = "" students = "" for i in interview_list: interview_id = str(i.id) if interview_id == interview: msg = i.team students = i.student_list break student_list = students.split() all_students = Employee.objects.all() student_names = "" for i in student_list: for j in all_students: if i == j.number: student_names = student_names + ' ' + j.name response = HttpResponse( json.dumps({ 'list': students, 'name_list': student_names, 'msg': msg })) return response
def get_ensembl_gene_info(request, analysis_id): if request.is_ajax(): ensembl_id = request.GET['id'] metadata = get_single_ensembl_metadata_online(ensembl_id) display_name = metadata['display_name'] if metadata is not None else '' infos = [] if metadata is not None: # selected = ['description', 'species', 'biotype', 'db_type', 'logic_name', 'strand', 'start', 'end'] selected = ['description', 'species'] for key in selected: value = metadata[key] if key == 'description': value = value[0:value.index('[')] # remove e.g. '[xxx]' from 'abhydrolase [xxx]' infos.append({'key': key.title(), 'value': value}) data = Harmonizome.get(Entity.GENE, name=display_name) try: description = data['description'] infos.append({'key': 'Description', 'value': description}) except KeyError: pass try: summary = get_entrez_summary(ensembl_id) infos.append({'key': 'Entrez Summary', 'value': truncate(summary)}) except TypeError: pass images = [] links = [ { 'text': 'Link to Ensembl', 'href': 'https://www.ensembl.org/id/' + ensembl_id }, { 'text': 'Link to GeneCard', 'href': 'https://www.genecards.org/cgi-bin/carddisp.pl?gene=' + display_name } ] # for x in metadata['Transcript']: # text = 'Transcript: ' + x['display_name'] # href = 'https://www.ensembl.org/id/' + x['id'] # links.append({'text': text, 'href': href}) annotation = get_annotation(analysis_id, ensembl_id, GENOMICS) annotation_url = get_annotation_url(analysis_id, ensembl_id, GENOMICS) data = { 'infos': infos, 'images': images, 'links': links, 'annotation': annotation, 'annotation_url': annotation_url, 'annotation_id': ensembl_id } measurements = get_grouped_measurements(analysis_id, ensembl_id, GENOMICS) if measurements is not None: data['plot_data'] = measurements return JsonResponse(data)
def login(request): if request.is_ajax(): id = request.POST.get('login_id') password = request.POST.get('login_pw') print('id', id) print('password', password) return JsonResponse({"a": "b"}) return render(request, 'sign/login.html')
def getLocation(request): if request.method == "POST" and request.is_ajax(): global lat, lag lat, lag = 0, 0 lat = request.POST.get('lat') lag = request.POST.get('lag') JsonBackInfo = {'json': '123'} return JsonResponse(JsonBackInfo)
def dlm(request): if request.method == 'POST' and request.is_ajax(): movid = request.POST.get('id') mov = Media.objects.get(pk=movid) mov.got = 1 mov.save() data = {'id': movid} return JsonResponse(data)
def image_list(request): if request.method == 'POST' and not request.is_ajax(): form = ImgUrl(request.POST) if not form.is_valid(): messages.error(request, 'invalid url') else: return redirect( f'/images/create/?url={form.cleaned_data["image_url"]}&title=default' ) try: if request.GET['error'] == 'invalid': messages.error(request, 'invalid url') if request.GET['error'] == 'neto': messages.error(request, 'invalid format') except BaseException: pass form = ImgUrl() images = Image.objects.all() paginator = Paginator(images, 5) page = request.GET.get('page') try: images = paginator.page(page) except PageNotAnInteger: # If page is not an integer deliver the first page images = paginator.page(1) except EmptyPage: if request.is_ajax(): # If the request is AJAX and the page is out of range # return an empty page return HttpResponse('') # If page is out of range deliver last page of results images = paginator.page(paginator.num_pages) if request.is_ajax(): return render(request, 'images/image/list_ajax.html', { 'section': 'images', 'images': images, 'form': form }) return render(request, 'images/image/list.html', { 'section': 'images', 'images': images, 'form': form })
def get_reactome_reaction_info(request, analysis_id): if request.is_ajax(): reactome_id = request.GET['id'] infos = [] # res = get_reactome_content_service(reactome_id) # summary_str = res['summation'][0]['text'] summary_str, is_inferred, original_species, inferred_species = get_summary_string(reactome_id) infos.append({'key': 'Summary', 'value': summary_str}) infos.append({'key': 'Species', 'value': original_species}) if is_inferred: inferred = 'Inferred from %s' % inferred_species infos.append({'key': 'Inferred', 'value': inferred}) # get all the participants temp = collections.defaultdict(list) results = get_reaction_entities([reactome_id])[reactome_id] for res in results: entity_id = res[1] display_name = res[2] relationship_types = res[3] if len(relationship_types) == 1: # ignore the sub-complexes rel = relationship_types[0] temp[rel].append((display_name, entity_id,)) for k, v in temp.items(): name_list, url_list = zip( *v) # https://stackoverflow.com/questions/12974474/how-to-unzip-a-list-of-tuples-into-individual-lists url_list = map(lambda x: 'https://reactome.org/content/detail/' + x if x is not None else '', url_list) name_str = ';'.join(name_list) url_str = ';'.join(url_list) infos.append({'key': k.title(), 'value': name_str, 'url': url_str}) images = [ 'https://reactome.org/ContentService/exporter/diagram/' + reactome_id + '.jpg?sel=' + reactome_id + "&quality=7" ] links = [ { 'text': 'Link to Reactome database', 'href': 'https://reactome.org/content/detail/' + reactome_id } ] annotation = get_annotation(analysis_id, reactome_id, REACTIONS) annotation_url = get_annotation_url(analysis_id, reactome_id, REACTIONS) data = { 'infos': infos, 'images': images, 'links': links, 'annotation': annotation, 'annotation_url': annotation_url, 'annotation_id': reactome_id } return JsonResponse(data)
def reportStandartToAjax(request): if request.is_ajax(): print(222222222) # deger = rapor Sonucu reportingStandartLizbon(request) data = str(raporSonucuStandart) print('\n\n\ndata: ', data) return HttpResponse(data) else: print("elseesesssesesese12")
def userListToAjax(request): if request.is_ajax(): deger = listUserToDB(request) if deger == 'HicUserYok': data = 'HicUserYok' else: data = deger data = json.dumps(data) return HttpResponse(data, content_type='application/json')
def ajax_posting(request): if request.is_ajax(): first_name = request.POST.get('first_name', None) # getting data from input first_name id if first_name: # cheking if first_name have value response = { 'msg': first_name # response message } return JsonResponse(response) # return response as JSON
def dl(request): if request.method == 'POST' and request.is_ajax(): epi = request.POST.get('epi') episode = Episode.objects.get(pk=epi) episode.downloaded = timezone.now() #if episode.rssdate is None: # episode.rssdate = dt_1000 episode.save() data = {'downloaded': ', <b>Downloaded:</b> ' + episode.downloaded_pretty(),'id': epi} return JsonResponse(data)
def hook_creation_process(request): if request.is_ajax(): if request.method == "POST": _data = request.body.decode('utf-8') project_name = json.loads(_data) project_name = project_name['project_name'] create_hook(access_token=request.session['oauth'], request=request, project_name=project_name) return HttpResponse(json.dumps({'success': True}), content_type='application/json')
def Tag_ajax(request): if request.is_ajax(): tagname = request.GET.get('tag') blog_type = request.GET.get('blog_type') tag = Tags.objects.get(name=tagname) if(blog_type): blogs = tag.blog_set.filter(blog_type=blog_type)[:10] else: blogs = tag.blog_set.all()[:10] return render(request, 'blog/list-content.html', {'blogs': blogs})
def page_item_delete(request, pk): try: page_item = PageItem.objects.get(pk=pk) except PageItem.DoesNotExist: raise Http404 if page_item.can_user_delete(request.user): page_item.delete() if request.is_ajax(): return HttpResponse() return redirect('page_list') return HttpResponseForbidden()
def userAddToAjax(request): if request.is_ajax(): deger = addUserToDB(request) if deger == 'varmis': data = 'BoyleBiriVarmis' else: data = 'YeniKullaniciEklendi' data = json.dumps(data) return HttpResponse(data, content_type='application/json')
def loginFromAjax(request): global gonderilecekVeri data = request.POST.get("data") gonderilecekVeri = data if request.is_ajax() and request.POST: data = {} return HttpResponse(data, content_type='application/json') else: print("else location add") return HttpResponse(data, content_type='application/json')
def tournamentCreator(request): if request.is_ajax(): if request.method == 'GET': tournament = Tournament() tournament.tournament_name = request.GET.get('name') tournament.category = request.GET.get('category') tournament.difficulty = 'Medium' tournament.start_date = datetime.datetime.now() tournament.end_date = datetime.datetime.now() tournament.save() return HttpResponse("%s" % tournament.tournament_name)
def geojson_handler(request): if request.is_ajax() and request.method == 'POST': polygon_data = json.loads( request.FILES.get('geojson_data').file.read().decode('UTF-8')) coordinates = polygon_data.get( 'features')[0]['geometry']['coordinates'] if coordinates: user_data.footprint = geojson_to_wkt(dict(polygon_data)) print(user_data.footprint) return HttpResponse('OK') return HttpResponse("Couldn't load data")
def userListFromAjax(request): global gonderilecekVeri data = request.POST.get("data") gonderilecekVeri = data if request.is_ajax() and request.POST: data = {} else: print("else user update") return HttpResponse(data, content_type='application/json')
def token_save_process(request): if request.is_ajax(): if request.method == "POST": _data = request.body.decode('utf-8') json_data = json.loads(_data) token_value = json_data['token'] token_value = token_value.strip() u = User.objects.filter(account_ID__exact=request.session['user_name']).first() u.access_token = token_value u.save() return HttpResponse(json.dumps({'success': True}), content_type='application/json')
def blend_details(request, blend_id): if request.method == 'POST' and request.is_ajax(): post_objects = GradientPalette.objects.filter(is_featured=True).order_by('-date') return load_palettes(request, post_objects, True) else: blend = get_object_or_404(GradientPalette, id=blend_id) gradients = GradientPalette.objects.filter(is_featured=True).order_by('-date_featured')[:10] palettes = ColorPalette.objects.filter(is_featured=True).order_by('-date_featured')[:10] images = ImagePalette.objects.filter(is_featured=True).order_by('-date_featured')[:10] context = {'object': blend, 'is_featured': False, 'gradients': gradients, 'palettes': palettes, 'images': images} return render(request, 'blend_details.html', context)
def page_item_refresh(request, pk): try: page_item = PageItem.objects.get(pk=pk) except PageItem.DoesNotExist: raise Http404 #page_item.refresh() request_link = 'https://graph.facebook.com/%d?fields=likes' % page_item.fb_id result = json.loads(urllib.request.urlopen(request_link).read().decode('utf-8')) page_item.last_like_count = result['likes'] page_item.save() if request.is_ajax(): return HttpResponse() return redirect('page_list')
def deleteInterfaceConfig(request): deleteDic={} info='Delete record successfully' try: if request.is_ajax() and request.method == 'POST': protocolGet=request.POST.get('protocol').strip() interfaceNameGet=str(request.POST.get('interfaceName')).strip() message=DeleteAPIJson(interfaceNameGet) interface.objects.filter(interfaceName=interfaceNameGet).filter(protocol=protocolGet).delete() except: info = '%s || %s' % (sys.exc_info()[0], sys.exc_info()[1]) deleteDic['message']=info deleteDic['time']=str(ctime()) return JsonResponse(deleteDic)
def editInterfaceConfig(request): editDic={} info='Delete record successfully' try: if request.is_ajax() and request.method == 'POST': protocolGet=request.POST.get('protocol').strip() interfaceNameGet=str(request.POST.get('interfaceName')).strip() businessNameGet=str(request.POST.get('businessName')).strip() parameterConfigGet=str(request.POST.get('configParameter')).strip() saveResponseFile(interfaceNameGet,parameterConfigGet) interface.objects.filter(interfaceName=interfaceNameGet).filter(protocol=protocolGet).update(businessName=businessNameGet,mockConfig=parameterConfigGet,updatetime=timezone.now()) except: info = '%s || %s' % (sys.exc_info()[0], sys.exc_info()[1]) editDic['message']=info editDic['time']=str(ctime()) print (editDic) return JsonResponse(editDic)
def add_tag(request): try: # obtenemos el perfil del usuario profile = request.user.profile except Profile.DoesNotExist: profile = Profile(user=request.user) # si no tiene perfil, se lo creamos profile.save() dbLogger.info(logMessages.profileCreated_message+request.user.username+'\'') tag = Tag() tag.perfil = profile # asignamos el perfil tag.text = "Etiqueta en blanco" # y un texto generico tag.save() # y lo guardamos dbLogger.info(logMessages.tagAdded_message+request.user.username+'\'') if(request.is_ajax()): tags = Tag.objects.filter(perfil=profile) tag_forms = get_tag_forms(tags) return render(request, 'web/es/tags.html', {'tag_forms' : tag_forms}) else: return redirect('/completar_perfil/', )
def More_ajax(request): if request.is_ajax(): tagname = request.GET.get('tag') num = int(request.GET.get('blogs_number')) blog_type = request.GET.get('blog_type') query = request.GET.get('query') no_more = False if tagname: tag = Tags.objects.get(name=tagname) blog_query = tag.blog_set else: blog_query = Blog.objects if blog_type: blog_query = blog_query.filter(blog_type=blog_type) if query: blog_query = blog_query.filter(name__contains=query) all_num = blog_query.count() if(all_num > num): blogs = blog_query.all()[:num] else: blogs = blog_query.all() no_more = True return render(request, 'blog/list-content.html', {'blogs': blogs, 'nomore': no_more})
def load_gradients(request): if request.method == 'POST' and request.is_ajax(): post_objects = GradientPalette.objects.filter(is_featured=True).order_by('-date') return load_palettes(request, post_objects, True) else: return render(request, 'gradients.html')
def index(request): all_entries = Films.objects.all() if len(all_entries) == 0: # database is empty filename = "sfmovies.csv" csv_filepathname = settings.MEDIA_ROOT + filename dataReader = csv.reader(open(csv_filepathname, encoding="utf-8"), delimiter=",", quotechar='"') for row in dataReader: if row[0] != "Title": # Ignore the header row, import everything else films = Films() films.title = row[0] films.release_year = int(row[1]) films.locations = row[2] films.fun_facts = row[3] films.production_company = row[4] films.distributor = row[5] films.director = row[6] films.writer = row[7] films.actor_1 = row[8] films.actor_2 = row[9] films.actor_3 = row[10] films.latitude = 0 films.longitude = 0 films.save() if request.is_ajax(): q = request.GET.get("term", "") film_list = Films.objects.filter(title__icontains=q) title_list = film_list.values("title").annotate(total=Count("title")) results = [] for film in title_list: results.append(film["title"]) data = json.dumps(results) mimetype = "application/json" return HttpResponse(data, mimetype) # if this is a POST request we need to process the form data elif request.method == "POST": # create a form instance and populate it with data from the request: form = FilmsForm(request.POST) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required # ... # redirect to a new URL: film_list = Films.objects.filter(title__icontains=request.POST["title"]) if len(film_list) == 0: # no records in database for given query form = FilmsForm() return render( request, "movies/index.html", { "error_message": "No records found. Search for something else.", "form": form, "film_list": film_list, }, ) else: title_list = film_list.values("title").annotate(total=Count("title")) title_len = len(title_list) title_string = request.POST["title"] context_list = [] for a in title_list: temp_list = film_list.filter(title__iexact=a["title"]) a_dict = {} a_dict["title"] = temp_list[0].title a_dict["release_year"] = temp_list[0].release_year a_dict["production_company"] = temp_list[0].production_company a_dict["distributor"] = temp_list[0].distributor a_dict["director"] = temp_list[0].director a_dict["writer"] = temp_list[0].writer a_dict["actor_1"] = temp_list[0].actor_1 a_dict["actor_2"] = temp_list[0].actor_2 a_dict["actor_3"] = temp_list[0].actor_3 location_list = [] for film in temp_list: if film.locations: # if location is available if film.latitude == 0: # no coordinates in database address = film.locations + ", San Francisco, CA" address = address.replace(" ", "+") key = "&key=AIzaSyCj1SDXgNgYPk11mBJEAMeX3tJpSOKJn_M" url = "https://maps.googleapis.com/maps/api/geocode/json?address=%s" % address url += key try: response = urllib.request.urlopen(url).read().decode("utf-8") except: smile = ":)" else: result = json.loads(response) if result["status"] == "OK": lat = float(str(result["results"][0]["geometry"]["location"]["lat"])) lng = float(str(result["results"][0]["geometry"]["location"]["lng"])) film.latitude = lat film.longitude = lng film.save() # end if loc_dict = {} loc_dict["loc"] = film.locations loc_dict["lat"] = film.latitude loc_dict["lng"] = film.longitude location_list.append(loc_dict) # end for a_dict["locations"] = location_list context_list.append(a_dict) # end for context = {"film_list": context_list, "title_len": title_len, "title_string": title_string} return render(request, "movies/result.html", context) # if a GET (or any other method) we'll create a blank form else: film_list = Films.objects.filter(~Q(latitude=0)) form = FilmsForm() return render(request, "movies/index.html", {"form": form, "film_list": film_list}) return render(request, "movies/index.html", {"form": form})
def Query_Blog(request): if request.is_ajax(): query = request.GET.get('query') blogs = Blog.objects.filter(name__contains=query)[:10] return render(request, 'blog/list-content.html', {'blogs': blogs})